This is the fifth day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021

Arrow function

Tip: Black for base, red for ES6 (update JavaScript syntax)

With the popularity of ES6, the application of the new ES6 syntax is more and more accepted by everyone. The arrow function is the most basic point of ES6. In addition to the simple syntax, this points to a clearer problem.

function sayHi(n){
  console.log(n);
}

sayHi = n= > concole.log(n)
Copy the code

Short for timer

The abbreviation of timer, in fact, is based on the arrow function, the timer needs to execute the function through the arrow function to write.

setTimeout(function(){
  console.log('name');
},2000)

setTimeout( () = > console.log('name'),2000 );
Copy the code

Traverse the shorthand

Where you need to use a function, the general arrow function to replace, of course, traversal not only forEach, but also map,each, etc

list.forEach(function(n){
  console.log(n);
})

list.forEach( n= > console.log(n) );
Copy the code

Implicit return value shorthand

This is still the domain of arrow functions, but instead of just replacing functions, there is another aspect to the problem of return values.

function calc(die){
  return Math.PI * die; // An active return is required
}

calc = die= > ( Math.PI * de ) // The result is returned by default without the body of {} braces

var func = function func(){
  return {foo : 1};
}

var func = () = >({ foo : 1});Copy the code

Data deconstruction

Data structure is ES6, for assignment, value transfer is a big change, simplify the operation of copy, automatic object, array, value exchange, etc., in the actual development can greatly simplify the code, mention the code readability, and do not lose the code readability.

// Assign
var x = 'a', 
    y= 'b';

var [x, y] = ['a'.'b'];  //

// Swap values
var temp = x;
x = y;
y = temp;

[x, y] = [y, x] //

// Object shorthand
var x = 'a', 
    y = 'b';
obj = {x: x, y: y};

var [x, y] = ['a'.'b'].//
obj = {x, y};
Copy the code

Parameter default value

When calling a function, in order to avoid null parameter values, we usually need to check whether the parameter has a value and assign a default value. ES6 simplifies this step.

function get(bool){
  if(bool = null) bool = true;
  console.log(bool);
}
get(); // true;

//
function get(bool = true){
  console.log(bool);
}
get() // true
Copy the code