Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

History

39 Commits

Repository files navigation

javascript/react-clean_code

One liner clean code snippets in javascript/react with ES6 syntax

Click ⭐if you like the project and follow @KrishnaKant for more updates.


Table of Contents

No.Questions
1Conditional statement
2Add a key-value pair in object conditionally
3Deleting a particular key from object
4Filling array with dummy values
5Call function if it exists
6String to Number
7Console related optimisation
8Overwrite by default values
9Conditional default value assignment for numbers

  1. Conditional Statement

    Plain conditional operation

    constis_employee=true;letcompanyif(is_employee){company='Inventives.ai';}else{company=null;}
    • We will use Ternary operator

      constis_employee=true;letcompany=is_employee?company='Inventives.ai':company=null;

    ⬆ Back to Top

  2. Add a key-value pair in object conditionally

    Plain conditional operation

    constis_employee=true;conststudent={name:'Krishna Kant',roll:'AD203'};if(is_employee){student.company='Inventives.ai';};

    We will use Spread operator to spread new object with one property inside the previously defined object and the conditional operator && to achieve the task conditionally

    1. While defining the object:
    • We are injecting the new property at time of defining the object only
    constis_employee=true;conststudent={name:'Krishna Kant',roll:'AD203',stream:'MERN stack web development',
    ...(is_employee&&{company:'Inventives.ai})
    };
    1. After object has been defined
    • We are injecting the new property after the object has been defined with its default key value pairs.
    constis_employee=true;letstudent={name:'Krishna Kant',roll:'AD203'};student={
    ...student,
    ...(is_employee&&{company: 5})};

    ⬆ Back to Top

  3. Deleting a particular key from object

    Plain conditional operation

    constis_employee=true;conststudent={name:'Krishna Kant',roll:'AD203',stream:'MERN stack web development',company:'Inventives.ai'};deletestudent.salary;
    • We will use Spread operator to delete one property inside the previously defined object.

      letstudent={name:'Krishna Kant',roll:'AD203',stream:'MERN stack web development',company:'Inventives.ai'};let{company, ...newStudent}=student;student=newStudent;

    ⬆ Back to Top

  4. Filling array with dummy values

    Plain conditional operation

    constarr_length=6;for(leti=0;i<arr_length;i++){dummyArr[i]{'written_by' : 'Krishna Kant'};}
    • We will use Array instance with Higher Order Function--> array.map()

      constarr_length=6;letdummyArr=newArray(arr_length).fill(null).map(()=>({'written_by' : 'Krishna Kant'}));

    ⬆ Back to Top

  5. Call function if it exists

    Plain javascript conditional calling

    constfun=()=>{
    <!-- do something -->
    }<!--callfunfunctionifitexists -->
    if(fun){fun();}
    • We will use logical AND operator to achieve same task

      constfun=()=>{
      <!-- do something -->
      }<!--callfunfunctionifitexists -->
      fun&&fun();
      • Better way to do this
      constfun=()=>{
      <!-- do something -->
      }fun?.();

    ⬆ Back to Top

  6. String to Number

    Plain javascript conversion

    constnum='22';console.log(Number(num));
    • Better way to do this using unary plus operator

      constnum='22';console.log(+num);

    ⬆ Back to Top

  7. Console related optimization

    i. Plain javascript conditional console

    constcountry='India';if(country){console.log(`country is:${country}`);}
    • Better way to do console using console.assert

      constcountry='India';console.assert(country,`country is ${country}`);

    ii. Named variable console

    • Often we need to console for debugging, to keep track of variable, part and line of code, variable named console can be done by using object format.

      constname='Krishna Kant';console.log(name);
  • Better way to do it

    constname='Krishna Kant';console.log({name});

iii. Grouping a set of console together

  • Often we need to console a set of variables in a given component or function for debugging, to keep track of variable, part and line of code, we can bind them together using console.group

    constname='Krishna Kant';constcountry='India';constemployee_details={organisation: 'Inventives.ai',project: 'health care product',team_size:'5'}console.group('general');console.log({name});console.log({country});console.groupEnd();console.group('employe_details');console.log({name});console.log({country});console.groupEnd();

    ⬆ Back to Top

  1. Overwrite blocked variables by default values

  • There might be instances where some variables from database could have undefined/null values and could break the code operation potentially, so we need to replace them by default values set by us manually.

Noob assignment

 ```javascript
let name = 'Krishna Kant';
let organisation = 'Inventives.ai';
let project = 'health care product';
let team_size = '5';
function print(name, organisation, project, team_size){
const employee_name = name || 'Krishna';
const employee_organisation = organisation || 'Inventives';
const project = project || 'health care startup project';
}
```
  • Better way to achieve this task using default parameters, what it does is if the value is not null or undefined, it will be assigned to the new variable otherwise new variable value assignment will pick up default values.

    letname='Krishna Kant';letorganisation='Inventives.ai';letproject='health care product';letteam_size='5';functionredefine(name='Krishna',organisation='Inventives',project='health care startup project',team_size='five'){constemployee_name=name;constemployee_organisation;constproject=project;}

    ⬆ Back to Top

  1. Conditional default value assignment for numbers

    • Using *** || *** operator with number data types might be problematic while logical default value assignment if some variables have value 0 because 0 is read as falsey value by logical operators,

Plain logical assignment by || operator

 ```javascript
const age = 0;
const pending_tasks =0;
const team_size = 5;
const age_copy = age || 1; <! --results 1 -->
const pending_tasks_copy = pending_tasks || 1; <! --results 1 -->
const team_size_copy = team_size || 2; <! --results 5 -->
```
  • Better way to achieve this task using default parameters, what it does is if the value is not null or undefined, it will be assigned to the new variable otherwise new variable value assignment will pick up default values.

    constage=0;constpending_tasks=0;constteam_size=5;constage_copy=age ? 1;<!--results0-->constpending_tasks_copy=pending_tasks||1;<!--results0-->constteam_size_copy=team_size||2;<!--results5-->

    ⬆ Back to Top

  • More code snippets are being added

Disclaimer

These code snippets are not to understand how to do a task from scratch, assuming that you already know how to achieve a given task successfully, above snippets focus more on clean, reusability, optimisation and lesser-code principle to make the code simple, organised and enhanced. The code snippets mentioned in this repository are the summary of frequently used codes in Javascript and/or React with ES6 syntax. We cannot guarantee that only these snippets will actually make the code cleaner, smoother and optimised, nor should you focus on copying and pasting them all. The primary purpose is for you to get a sense of how some bulk codes might be replaced with one-liner ES6 conditional and operational statements!

Happy Coding 😊


About

One liner clean code snippets in javascript/react with ES6 syntax

Topics

Resources

Stars

27 stars

Watchers

1 watching

Forks

Contributors