Table of Contents
Expand operator
Remaining parameters
String interpolation
Abbreviated attributes
Method attribute
Destructuring assignment
Array method
Promises Async/Await
模块
箭头函数和字典作用域 this
结语
Home Web Front-end JS Tutorial What are the features of javascript

What are the features of javascript

Jun 30, 2021 am 11:23 AM
javascript

Javascript features include: 1. Expansion operator; 2. Remaining parameters; 3. String interpolation; 4. Abbreviation attributes; 5. Method attributes; 6. Destructuring assignment; 7. Array methods; 8. Modules ; 9. Promises Async/Await; 10. Arrow functions and dictionary scope.

What are the features of javascript

The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.

What are the features of javascript?

Ten super practical JS features

Original work by Chris Noring, translated content reproduced from New Frontend.

You may be new to JavaScript, or may have only used it occasionally. Regardless, JavaScript has changed a lot, and some features are well worth using. This article introduces some features that, in my opinion, a serious JavaScript developer will use at some point every day.

References

The following two sites about ES6 are my favorites:

  • ES6 Features

  • MDN

Expand operator

As the name suggests, it is used to expand the operator (...) before the object or array. A structure expands into a list. Demonstrate it:

let firstHalf = [ 'one', 'two'];
let secondHalf = ['three', 'four', ...firstHalf];
Copy after login

Is this writing method elegant and concise enough? If the expansion operator is not used, we have to write like this:

let firstHalf = [ 'one', 'two'];
let secondHalf = ['three', 'four'];
for(var i=0, i <firstHalf.length; i++ ) {
  secondHalf.push(firstHalf[i]);
}
Copy after login

The expansion operator is also suitable for merging the properties of objects:

const hero = {
  name: &#39;Xena - Warrior Princess&#39;,
  realName: &#39;Lucy Lawless&#39;
}


const heroWithSword = {
 ...hero,
 weapon: &#39;sword&#39;
}
Copy after login

If the expansion operator is not used, you need to traverse the properties of the object:

let keys = Object.keys(hero);
let obj = {};

for(var i=0; i< keys.length; i++) {
   obj[keys[i]] = keys[props[i]];
}
Copy after login

Remaining parameters

The remaining parameters will be included in the sequence. The characteristic of JavaScript is that the number of parameters is very flexible. There is usually an arguments variable collecting the arguments. Let's look at an example:

function add(first, second, ...remaining) {
  return first + second;
}
Copy after login

The above piece of code only adds first and second, that is, calling add(1, 2) and add(1, 2, 3, 4) will get the same the result of. Let's correct it below:

function add(first, second, ...remaining) {
  return first + second + remaining.reduce((acc, curr) => acc + curr, 0);
}
Copy after login

As mentioned before, ...remaining collects the remaining parameters, provides us with a naming of these parameters, and clearly indicates our intention to process the remaining parameters. I remember that ES5 already has arguments at the latest, but few people know about it.

String interpolation

Have you ever seen such a statement?

class Product {
 constructor(name, description, price) {
   this.name = name;
   this.description = description;
   this.price = price;
 }

 getDescription() {
   return " Full description \n" + 
   " name: " + this.name + 
   " description: " + this.description
 }
}
Copy after login

Of course, I am referring to the long, unreadable multi-line statement in the getDescription() method. A similar phenomenon exists in most programming languages. Several languages ​​provide string interpolation, and luckily, JavaScript is one of them. Let’s rewrite the getDescription() method:

getDescription() {
   return `Full description \n: 
   name: ${this.name}
   description ${this.description}
   `;
}
Copy after login

${} interpolation can be used in a pair of `-wrapped strings. It looks much more comfortable now.

Abbreviated attributes

Must be written like this in ES5:

function createCoord(x, y) {
  return {
    x: x,
    y: y
  }
}
Copy after login

In ES6, you can use abbreviated attributes in the future:

function createCoord(x, y) {
  return {
    x,
    y
  }
}
Copy after login

Doesn’t it look more refreshing?

Method attribute

Method attribute is an attribute defined in the object that points to a method. Consider the following piece of ES5 code as an example:

const math = {
  add: function(a,b) { return a + b; },
  sub: function(a,b) { return a - b; }, 
  multiply: function(a,b) { return a * b; }
}
Copy after login

ES6 In the future, you only need to write:

const math = {
  add(a,b) { return a + b; },
  sub(a,b) { return a - b; },
  multiply(a,b) { return a * b; }
}
Copy after login

Destructuring assignment

Destructuring assignment is beneficial to the mental health of the developer himself.

Consider the following code:

function handle(req, res) {
 const name = req.body.name;
 const description = req.body.description;
 const url = req.url;

 log('url endpoint', url);

 // 大量代码逻辑
 dbService.createPerson(name, description)
}
Copy after login

No matter from any perspective, the above code is not perfect, but it does reflect an application scenario where we want to view objects from different levels retrieve data. You may ask, what's the problem here? Well, I can save myself some keystrokes by not declaring so many variables.

function handle(req, res) {
 const { body: { name, description }, url } = req;

 log('url endpoint', url);

 // 大量代码逻辑
 dbService.createPerson(name, description)
Copy after login

Look, our above code compresses three lines into one.

Destructuring assignment is not limited to objects. It works equally well with arrays. Consider the following code:

const array = [1,2,3,4,5,6];
const a = array[0];
const c = array[2];
Copy after login

The above code can be rewritten in a more elegant way:

const array = [1,2,3,4,5,6];
const [a, ,c, ...remaining] = arr;

// remaining = [4,5,6]
Copy after login

We can use the above pattern matching to decompose the values ​​of the array. We use , , to skip certain values. The remaining parameters mentioned above can also be used here. Here we capture the remaining array members through the remaining parameters.

Destructuring assignment can also be used for functions and parameters. When a function has more than 2-3 parameters, it is a de facto standard in JavaScript to use an object to collect all parameters. For example, the following function:

function doSomething(config) {
  if(config.a) { ... }
  if(config.b) { ... }
  if(config.c) { ... }
}
Copy after login

has a better way of writing:

function doSomething({ a, b, c }) {
  if(a) { ... }
  if(b) { ... }
  if(c) { ... }
}
Copy after login

Array method

ES6 introduces many useful array methods, such as:

  • find(), finds the member in the list, returns null to indicate that it was not found.
  • findIndex(), finds the index of the list member,
  • some(), checks whether an assertion is at least True on a member of the list
  • includes, whether the list contains an item

The following code will help you understand their usage:

const array = [{ id: 1, checked: true }, { id: 2 }];
arr.find(item => item.id === 2) // { id: 2 }
arr.findIndex(item => item.id === 2) // 1
arr.some(item => item.checked) // true

const numberArray = [1,2,3,4];
numberArray.includes(2) // true
Copy after login

Promises Async/Await

If you have been in this circle for a few years, you may remember that there was a time when we only had callbacks, like this:

function doSomething(cb) {
  setTimeout(() =>  {
    cb('done')
  }, 3000)
}

doSomething((arg) => {
 console.log('done here', arg);
})
Copy after login

We use callbacks because some operations are Asynchronous and takes time to complete. Then we got the promise library and people started using it. Then JavaScript gradually added native support for promises.

function doSomething() {
  return new Promise((resolve, reject) => {
    setTimeout(() =>  {
      resolve('done')
    }, 3000)
  })
}

doSomething().then(arg => {
 console.log('done here', arg);
})
Copy after login

We can even call it like this to string promises together:

getUser()
  .then(getOrderByUser)
  .then(getOrderItemsByOrder)
  .then(orderItems => {
    // 处理排序后的成员
  })
Copy after login

后来生活更加美好,我们有了 async/await, 上面一段代码可以这样写:

async function getItems() {
  try {
    const user = await getUser();
    const order = await getOrderByUser(user);
    const items = await getOrderItemsByOrder(order);
    return items;
  } catch(err) {
    // 在这里处理错误,建议返回某个值或者重新抛出错误
  }
}

getItems().then(items => {
  // 处理排序后的成员
})
Copy after login

模块

差不多任何编程语言都支持模块这一概念,也就是将代码分为多个文件,每个文件是一个自我包含的单元(模块)。 考虑下面的代码:

// math.js

export function add(a,b) { return a + b; }
export function sub(a,b) { return a - b; }

export default mult(a,b) => a * b;

// main.js
import mult, { add, sub } from './math';

mult(2, 4) // 8
add(1,1)   // 2
sub(1,2)   // -1
Copy after login

我们在上面用 export 关键字注明了 add 和 sub 这两个结构对任何引入该模块的模块都公开可见。 export default 关键字则注明仅仅 import 模块时得到的结构。 在 main.js 中,我们将导入的 default 命名为 mult,同时指明我们引入 add() 和 sub() 这两个方法。

箭头函数和字典作用域 this

我在这篇文章中很多地方都用到了箭头函数,它不过是另一种函数表示法。 过去我们只能这么声明函数:

function printArray(arr) {
 // 具体操作
}
Copy after login

现在我们也可以这么写:

const printArray = (arr) => {
 // 具体操作
}
Copy after login

我们也可以将函数声明写到一行里:

const add = (a,b) => a + b
Copy after login

上面的代码表明我们进行操作并返回结果。 我们也可以采用下面的语法返回一个对象:

const create = (a,b) = > ({ x: a, y: b })
Copy after login

过去会碰到搞不清 this 是什么的问题。 考虑下面的代码:

let array = [1,2,3];

function sum() {
  this.total = 0;

  arr.forEach(function(item) {
    this.total+= item;  // 糟糕,`this` 是内层函数的 `this`
  })
  return total;
}
Copy after login

上面代码中的 this 指向 forEach 内部函数的 this,这可不是我们想要的。 过去我们通过以下方式解决这个问题:

function sum() {
  this.total = 0;
  var self = this;

  arr.forEach(function(item) {
    self.total+= item;  // 这里我们使用 `self`,它能解决问题,但是感觉有点别扭
  })
  return total;
}
Copy after login

箭头函数可以解决问题,再也不用 self 了,现在代码看起来是这样的:

function sum() {
  this.total = 0;

  arr.forEach((item) => {
    this.total+= item;  // 一切安好,`this` 指向外层函数
  })
  return total;
}
Copy after login

大胜!

结语

我还可以讲讲更多 ES6 方面的内容,不过这篇文章中我只打算介绍我最偏爱的特性。 我觉得你应该从今天开始使用这些特性。

【相关推荐:javascript高级教程

The above is the detailed content of What are the features of javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles