On six small characteristics of ES6 (2)

  • 2021-07-22 08:33:48
  • OfStack

Preface

Everyone in the Javascript community loves the new API, syntax updates, and features that provide a better, smarter, and more efficient way to accomplish important tasks.

Following the previous article, "Brief Talk about 6 Small Features of ES6", this time I will share 6 ways to reduce code and maximize efficiency.

1.Object Shorthand

The new object declaration method allows us not to declare the key of an object:


var x = 12;
var y = yes;
var z = {one:'1',two:'2'};

// The old way
var obj = {
 x:x,
 y:y,
 z:z
}
// The new way
var obj = {x,y,z};

2.Method Properties

Avoid function keyword declaration functions:


var davidwalsh = {
 makeItHappen(param){
 // do stuff
 }
}

It must be admitted that removing the function keyword really makes the code concise and easier to maintain.

3.Blocks vs Immediately Executed Functions

The following pattern for creating an immediate execution method is a bit ugly:


(function(){
 // do stuff
})();

With ES6, we can create block-level actions with {} and let to complete the immediate execution function:


{
 let j = 12;
 let divs = document.querySelectorAll('div');

 // do stuff
}

j; // ReferenceError: j is not defined...

If a function is declared inside Block, it will be accessed externally. However, if you use the let keyword to declare function arguments, you will implement the functions of IEF without using parentheses.

4. for loops and let

Because there are variable elevations in JS, we often declare "useless" iteration variables in front of the scope, such as (for var x = …). ES 6 solves this annoying problem with let:


for(let x = 0; x < len; i++){
 //do stuff
}

x; // ReferenceError: x is not defined

let will be used more soon.

5.get and set for Classes


class Cart{
 constructor(total){
 this._total = total;
 }
 get total(){return this._total;}
 set total(v){this._total = Number(v);}
}

var cart = new Cart(100);

cart.total // 100

get can be set for properties, and set is the best in this part. No special settings need to be made using functions. When obj. prop = {value}, Cut 1 is automatically executed.

6.startsWith,endsWith and includes


"MooTools".startsWith("Moo"); // true;
"MooTools".startsWith("moo"); // false;

"MooTools".endsWith("Tools"); // true;

"MooTools".includes("oo"); // true;

Note: The compatibility of includes method is still a lot. There was an online bug, which was caused by not supporting this method.

Original: https://davidwalsh.name/es6-features-ii/amp

Summarize

The above is the whole content of this article. I hope the content of this article can bring 1 certain help to everyone's study or work. If you have any questions, you can leave a message for communication.


Related articles: