Original title:

Photo by Shahadat Rahman on Unsplash

There are many tricks you can use to make javascript code shorter and simpler. I’m going to share four such techniques that have greatly reduced my workload and development time while coding.

“Short circuit”

“Short circuit” means that the following expression will not be executed if the preceding condition is not set.

Common “short-circuit operator” && and | |.

For example condition1&&condition2, condition1 will not be executed if condition1 is false.

Such as condition1 | | condition2, if condition1 to true, then condition2 will not be executed.

When you are using simple if conditions, you can abbreviate code in this way, which is very effective.

if( x == 0 ){
  foo()
}
Copy the code

“Short circuit” can be implemented using the && operator. If the condition before && evaluates to false, the code after && will not be executed.

// If the expression 'x == 0' is flase, the following expression 'foo()' will not be executed
x == 0 && foo()
Copy the code

Instead of multiple if expressions, you can use chaining to use &&

x == 0 && y == 0 && foo()
Copy the code

use?Operator to determine whether an object property exists

If you are dealing with scenarios such as API calls or objects that you are not sure whether they or their keys have been initialized, use? It would be useful to access object properties

Suppose an object studentObject with the key name name. Accessing the key value directly using studentobject.name may throw an error. One way to determine whether an object has a key name is to use nested if conditions.

if(studentObject){
  if(studentObject.name}{
    console.log('student name exists')}}Copy the code

Can the above code be used? Operator to simplify code. If studentObject does not exist, it will be evaluated as false.

if(studentObject? .name){console.log('student name exists')}Copy the code

Null-value merge operator (??)

The ternary operators already make the code shorter than if else statements. This is handy if the amount of code to execute is small.

const foo = () = > {
  x ? x : 'x do not exist'
}
Copy the code

In the example above, if you had to return the operand to “?” To the left, you can use “?? Operators make code shorter.

const foo = () = > {
  x ?? 'x do not exist'
}
Copy the code

Use return instead of if else nesting

Consider the following function that checks the value of “x”.

const foo = () = > {
  if(x<1) {return 'x is less than 1'
  }else{
    if(x > 1) {return 'x is greater than 1'
    }else{
      return 'x is equal to 1'}}}Copy the code

Removing the else condition reduces the complexity of if-else nesting because the return statement stops function execution and returns the result.

const foo = () = > {
  if(x<1) {return 'less than 1'
  }
  if(x>1) {return 'x is greater than 1'
  }
  return 'x is equal to 1'
}
Copy the code