美文网首页技术雷达Node.js 极简教程SpringBoot极简教程 · Spring Boot
JavaScript ES6 — 少即是多,以少胜多,四两拨千斤

JavaScript ES6 — 少即是多,以少胜多,四两拨千斤

作者: 光剑书架上的书 | 来源:发表于2018-11-05 17:51 被阅读9次

JavaScript ES6 brings new syntax and new awesome features to make your code more modern and more readable. It allows you to write less code and do more. ES6 introduces us to many great features like arrow functions, template strings, class destruction, Modules… and more. Let’s take a look.

const and let

const is a new keyword in ES6 for declaring variables. const is more powerful than var. Once used, the variable can’t be reassigned. In other words, it’s an immutable variable except when it used with objects.

简单讲,就是 Java 中的 final, Kotlin 中的 val。

This is really useful for targeting the selectors. For example, when we have a single button that fires an event, or when you want to select an HTML element in JavaScript, use const instead of var. This is because var is ‘hoisted’. It’s always preferable to use const when don’t want to reassign the variable .

In the code above, const will not change and cannot be reassigned. If you try to give it a new value, it will return you an error.

// ES5
var a = 1;
a = a + 1;
console.log(a); // 2

// ES 6
const b = 1;
b = b + 1; // error
console.log(b);

报错日志:

$ node es6_demo.js 
2
/Users/jack/WebstormProject/node-tutorials/hello-node/es6_demo.js:8
b = b + 1;
  ^

TypeError: Assignment to constant variable.
    at Object.<anonymous> (/Users/jack/WebstormProject/node-tutorials/hello-node/es6_demo.js:8:3)
    at Module._compile (internal/modules/cjs/loader.js:688:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
    at Module.load (internal/modules/cjs/loader.js:598:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
    at Function.Module._load (internal/modules/cjs/loader.js:529:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:741:12)
    at startup (internal/bootstrap/node.js:285:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:739:3)

let can be reassigned and take new value. It creates a mutable variable.

let is the same as const in that both are blocked-scope. It means that the variable is only available within its scope.

Arrow functions: ()=>{}

The arrow function is really awesome, and makes your code more readable, more structured, and look like modern code. Instead of using this:

Use this:

As you see, the arrow function seems more readable and clean! You won’t need to use the old syntax anymore.

Also, you can use Arrow function with map, filter, and reduce built-in functions.

The map function with arrows looks more clear and readable than map in ES5. With ES6 you can write shorter and smarter code. You can use the same with filter and reduce.

Template Literals

Template literals or template strings are pretty cool. We don’t have to use the plus (+) operator to concatenate strings, or when we want to use a variable inside a string.

The old syntax:

With new ES6 syntax:

So simple! It’s a really huge difference between the old syntax and ES6. When playing with strings, the literal string in ES6 looks more organized and well structured than ES5.

Default parameters

When I work in PHP, I usually use default parameters. These allow you to define a parameter in advance.

So, when you forget to write the parameter, it won’t return an undefined error because the parameter is already defined in the default. So when you run your function with a missed parameter, it will take the value of the default parameter t, and it will not return an error!

Look at this example:

The function above returns undefined, because we forgot to give it the second parameter age.

But if we used the default parameter, it won’t return undefined, and it will use its value when we forget to assign a parameter!

As you see, the function returns a value even though we missed the second parameter. Now with the default parameter we can handle the error in advance.

Array and object destructing

Destruction makes the assignment of the values of an array or object to the new variable easier.

The old syntax:

With ES6 syntax:

With ES5, we have to assign each value to each variable. With ES6, we just put our values within curly brackets to get any property of the object.

Note: if you assign a variable that is not identical to the name of property, it will return undefined. For example, if the name of the property is name and we assign it to a username variable, it will return undefined.

We always have to name the variable the same as the name of the property. But in case we want to rename the variable, we can use the colon : instead.

For the array, we use the same syntax as the object. We have just to replace the curly brackets with square brackets.

Import and export

Using import and export in your JavaScript application makes it more powerful. They allow you to create separate and reusable components.

If you are familiar with any JavaScript MVC framework, you will see that they use import and export to handle the components most of the time. So how do they really work?

It is simple! export allows you to export a module to be used in another JavaScript component. We use import to import that module to use it in our component.

For example, we have two files. The first is named detailComponent.js and the second is named homeComponent.js.

In detailComponent.js we are going to export the detail function.

And if we want to use this function in homeComponent.js, we will just use import.

If we want to import more than one module, we just put them within curly brackets.

So cool, isn’t it?!

不过,在 Node.js 中, 还不能直接使用ES6中的 import / export 模块语法。但是也有解决方案:

Node.js 中使用 ES6 中的 import / export 的方法大全

Promises

Promises are a new feature of ES6. It’s a method to write asynchronous code. It can be used when, for example, we want to fetch data from an API, or when we have a function that takes time to be executed. Promises make it easier to solve the problem, so let’s create our first Promise!

If you log your console, it will return a Promise. So, if we want to execute a function after data is fetched, we will use a Promise. The Promise takes two parameters: resolve and reject to handle an expected error.

Note: the fetch function returns a Promise itself!

const url='https://jsonplaceholder.typicode.com/posts';
const getData=(url)=>{
return fetch(url);
}
getData(url).
then(data=> data.json()).
then(result=> console.log(result));

Now if you log your console it will return an array of data.

Rest parameter and Spread operator
The rest parameters are used to get the argument of an array, and return a new array.

The spread operator has the same syntax as the rest parameter, but the spread operator takes the Array itself and not just the arguments. We can use the Spread parameter to get the values of an Array, instead of using a for loop or any other method.

const arr=['said',20,'JavaScript enthusiast','Hi','Said','How are you?'];
const Func=(...anArray)=>{
return anArray;
}
console.log(Func(arr));

//output  ["said", 20, "JavaScript enthusiast", "Hi", "Said", "How are you?"

Classes
Classes are the core of object oriented programming (OOP). They make your code more secure and encapsulated. Using classes gives your code a nice structure and keeps it oriented.

To create a class, use the class keyword followed by the name of the class with two curly brackets.

Now we can access the class methods and properties using the new keyword.

class myClass{
    constructor(name,age){
    this.name=name;
    this.age=age;
}
}
const Home= new myClass("said",20);
console.log(Home.name)//  said

To inherit from another class, use the extends keyword followed by the name of the class you want to inherit from.

You can learn more about Classes here.

ES6 has other amazing features — you can explore them here.

原文链接:https://medium.freecodecamp.org/write-less-do-more-with-javascript-es6-5fd4a8e50ee2


Kotlin 开发者社区

国内第一Kotlin 开发者社区公众号,主要分享、交流 Kotlin 编程语言、Spring Boot、Android、React.js/Node.js、函数式编程、编程思想等相关主题。

开发者社区 QRCode.jpg

相关文章

  • JavaScript ES6 — 少即是多,以少胜多,四两拨千斤

    JavaScript ES6 brings new syntax and new awesome features...

  • 1208.少即是多,以少胜多

    有的人喜欢写长文章,他们一写起来就收不住口,有一发不可收拾之势,仿佛写少了就说不清楚,讲不明白。所以他们笔下全是长...

  • 少即是多,多即是少

    这是我每天写一篇原创文章的第1496天 少即是多,多即是少。 这挺有意思的。 现在我们获取信息太容易了,简直就是信...

  • 发现和应用自己的临界知识

    为什么临界知识能够四两拨千斤? 我们对临界知识能够四两拨千斤,实现少即是多的效果,主要是建立在两个重要的建设上面:...

  • 阅读,多即是少,少即是多

    俗话说“多多益善”,我们在阅读中也经常抱有这种心态。下单了很多书,搜集了很多电子书,收藏了很多文章。 然而,这些书...

  • 少即是多,少即是得

    正在调整自己早睡早起的习惯,昨天按照作息来的。早早起来,大概四五点钟就醒了,有意识的就起床了,再也没有往日赖床的心...

  • 少即是多

    彭臻华 文 周末看了一部最近在国内热播的印度电影《起跑线》,讲述的就是一对中产阶级的印度夫妇拉吉和米图,为了让女儿...

  • 少即是多

    少即是多 少=多? 为什么?在什么情况下成立 答:因为在有限的时间内,一个观点容易被记住,而很多的观点,每个都记不...

  • 少即是多

    生活中有太多的身不由己,“自由”成为内心深处由来已久的渴望。总以为只要自己努力,能力提升了,自由度就会大了,可是越...

  • 少即是多

    也会会犯错但我不想什么都不做

网友评论

    本文标题:JavaScript ES6 — 少即是多,以少胜多,四两拨千斤

    本文链接:https://www.haomeiwen.com/subject/bcasxqtx.html