Home Web Front-end JS Tutorial Introduction to the abbreviation of js

Introduction to the abbreviation of js

Jul 09, 2017 am 09:39 AM
javascript introduce Writing method

A very popular article from abroad recently. The abbreviation of js can improve your js writing level to a certain extent and your understanding of js will be closer.

Original link, very popular recently An article

This really is a must read for any JavaScript-based developer. I have written this article as a vital source of reference for learning shorthand JavaScript coding techniques that I have picked up over the years. To help you understand what is going on I have included the longhand versions to give some coding perspective.

This article is a must-read for any JavaScript-based developer, I write this This article is about learning JavaScript abbreviations that I have been familiar with for many years. To help everyone learn and understand, I have compiled some non-abbreviated writing methods.

June 14th, 2017: This article was updated to add new shorthand tips based on ES6. If you want to learn more about the changes in ES6, sign up for SitePoint Premium and check out our screencast A Look into ES6

1. Ternary operator

When you want to write an if...else statement, use the ternary operator instead.

Common writing:


const x = 20;
let answer;
if (x > 10) {
  answer = 'is greater';
} else {
  answer = 'is lesser';
}
Copy after login

Abbreviation:


const answer = x > 10 ? 'is greater' : 'is lesser';
Copy after login

You can also nest if statements:


const big = x > 10 ? " greater 10" : x
Copy after login

2. Short-circuit evaluation abbreviation

When assigning another value to a variable, you want to determine the source value Not null, undefined or an empty value. You can write a multi-condition if statement.


if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
   let variable2 = variable1;
}
Copy after login

Or you can use the short-circuit evaluation method:


const variable2 = variable1 || 'new';
Copy after login

3. Declaring variable abbreviation method


let x;
let y;
let z = 3;
Copy after login

Abbreviation method:


let x, y, z=3;
Copy after login

4.if exists condition abbreviation method


if (likeJavaScript === true)
Copy after login

Abbreviation:


if (likeJavaScript)
Copy after login

The two statements are equal only when likeJavaScript is a true value

If the judgment value is not a true value, you can do this:


let a;
if ( a !== true ) {
// do something...
}
Copy after login

Abbreviation:


let a;
if ( !a ) {
// do something...
}
Copy after login

5. JavaScript loop abbreviation method


for (let i = 0; i < allImgs.length; i++)
Copy after login

Abbreviation:


for (let index in allImgs)
Copy after login

You can also use Array .forEach


function logArrayElements(element, index, array) {
 console.log("a[" + index + "] = " + element);
}
[2, 5, 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[2] = 9
Copy after login

6. Short-circuit evaluation

The value assigned to a variable is determined by judging whether its value If it is null or undefined, then:


let dbHost;
if (process.env.DB_HOST) {
 dbHost = process.env.DB_HOST;
} else {
 dbHost = &#39;localhost&#39;;
}
Copy after login

Abbreviation:


const dbHost = process.env.DB_HOST || &#39;localhost&#39;;
Copy after login

7. Decimal exponent

When you need to write a number with many zeros (such as 10000000), you can use the exponent (1e7) to replace this number:


for (let i = 0; i < 10000000; i++) {}
Copy after login

Abbreviation:


for (let i = 0; i < 1e7; i++) {}

// 下面都是返回true
1e0 === 1;
1e1 === 10;
1e2 === 100;
1e3 === 1000;
1e4 === 10000;
1e5 === 100000;
Copy after login

8. Object attribute abbreviation

If the attribute name is the same as If the key names are the same, you can use the ES6 method:


const obj = { x:x, y:y };
Copy after login

Abbreviation:


const obj = { x, y };
Copy after login

9. Arrow function abbreviation

The traditional function writing method is easy to understand and write, but when it is nested in another function, these advantages are lost.


function sayHello(name) {
 console.log(&#39;Hello&#39;, name);
}

setTimeout(function() {
 console.log(&#39;Loaded&#39;)
}, 2000);

list.forEach(function(item) {
 console.log(item);
});
Copy after login

Abbreviation:


sayHello = name => console.log(&#39;Hello&#39;, name);
setTimeout(() => console.log(&#39;Loaded&#39;), 2000);
list.forEach(item => console.log(item));
Copy after login

10. Implicit return value abbreviation

Often use the return statement to return the final result of a function. An arrow function with a single statement can implicitly return its value (the function must be omitted {}In order to omit returnKeyword)

To return a multi-line statement (such as object literal expression), you need to use () to surround the function body.


function calcCircumference(diameter) {
 return Math.PI * diameter
}

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

Abbreviation:


calcCircumference = diameter => (
 Math.PI * diameter;
)

var func = () => ({ foo: 1 });
Copy after login

11.Default parameter value

In order to pass default values ​​to parameters in functions, it is usually written using if statements, but using ES6 to define default values ​​will be very concise:


function volume(l, w, h) {
 if (w === undefined)
  w = 3;
 if (h === undefined)
  h = 4;
 return l * w * h;
}
Copy after login

Abbreviation:


volume = (l, w = 3, h = 4 ) => (l * w * h);
volume(2) //output: 24
Copy after login

12. Template string

In traditional JavaScript language, the output template is usually written like this.


const welcome = &#39;You have logged in as &#39; + first + &#39; &#39; + last + &#39;.&#39;

const db = &#39;http://&#39; + host + &#39;:&#39; + port + &#39;/&#39; + database;
Copy after login

ES6 can use backticks and ${} abbreviation:


const welcome = `You have logged in as ${first} ${last}`;

const db = `http://${host}:${port}/${database}`;
Copy after login

13. Destructuring assignment shorthand method

In web frameworks, it is often necessary to pass data in the form of arrays or object literals back and forth between components and APIs, and then need to deconstruct it


const observable = require(&#39;mobx/observable&#39;);
const action = require(&#39;mobx/action&#39;);
const runInAction = require(&#39;mobx/runInAction&#39;);

const store = this.props.store;
const form = this.props.form;
const loading = this.props.loading;
const errors = this.props.errors;
const entity = this.props.entity;
Copy after login

Abbreviation:


import { observable, action, runInAction } from &#39;mobx&#39;;

const { store, form, loading, errors, entity } = this.props;
Copy after login

You can also assign variable name :


const { store, form, loading, errors, entity:contact } = this.props;
//最后一个变量名为contact
Copy after login

14. Multi-line string abbreviation

If you need to output a multi-line string, you need to use + to splice it:


const lorem = &#39;Lorem ipsum dolor sit amet, consectetur\n\t&#39;
  + &#39;adipisicing elit, sed do eiusmod tempor incididunt\n\t&#39;
  + &#39;ut labore et dolore magna aliqua. Ut enim ad minim\n\t&#39;
  + &#39;veniam, quis nostrud exercitation ullamco laboris\n\t&#39;
  + &#39;nisi ut aliquip ex ea commodo consequat. Duis aute\n\t&#39;
  + &#39;irure dolor in reprehenderit in voluptate velit esse.\n\t&#39;
Copy after login

Using backticks can achieve the abbreviation function:


const lorem = `Lorem ipsum dolor sit amet, consectetur
  adipisicing elit, sed do eiusmod tempor incididunt
  ut labore et dolore magna aliqua. Ut enim ad minim
  veniam, quis nostrud exercitation ullamco laboris
  nisi ut aliquip ex ea commodo consequat. Duis aute
  irure dolor in reprehenderit in voluptate velit esse.`
Copy after login

15.扩展运算符简写

扩展运算符有几种用例让JavaScript代码更加有效使用,可以用来代替某个数组函数。


// joining arrays
const odd = [1, 3, 5];
const nums = [2 ,4 , 6].concat(odd);

// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = arr.slice()
Copy after login

简写:


// joining arrays
const odd = [1, 3, 5 ];
const nums = [2 ,4 , 6, ...odd];
console.log(nums); // [ 2, 4, 6, 1, 3, 5 ]

// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = [...arr];
Copy after login

不像concat()函数,可以使用扩展运算符来在一个数组中任意处插入另一个数组。


const odd = [1, 3, 5 ];
const nums = [2, ...odd, 4 , 6];
Copy after login

也可以使用扩展运算符解构:


const { a, b, ...z } = { a: 1, b: 2, c: 3, d: 4 };
console.log(a) // 1
console.log(b) // 2
console.log(z) // { c: 3, d: 4 }
Copy after login

16.强制参数简写

JavaScript中如果没有向函数参数传递值,则参数为undefined。为了增强参数赋值,可以使用if语句来抛出异常,或使用强制参数简写方法。


function foo(bar) {
 if(bar === undefined) {
  throw new Error(&#39;Missing parameter!&#39;);
 }
 return bar;
}
Copy after login

简写:


mandatory = () => {
 throw new Error(&#39;Missing parameter!&#39;);
}

foo = (bar = mandatory()) => {
 return bar;
}
Copy after login

17.Array.find简写

想从数组中查找某个值,则需要循环。在ES6中,find()函数能实现同样效果。


const pets = [
 { type: &#39;Dog&#39;, name: &#39;Max&#39;},
 { type: &#39;Cat&#39;, name: &#39;Karl&#39;},
 { type: &#39;Dog&#39;, name: &#39;Tommy&#39;},
]

function findDog(name) {
 for(let i = 0; i<pets.length; ++i) {
  if(pets[i].type === &#39;Dog&#39; && pets[i].name === name) {
   return pets[i];
  }
 }
}
Copy after login

简写:


pet = pets.find(pet => pet.type ===&#39;Dog&#39; && pet.name === &#39;Tommy&#39;);
console.log(pet); // { type: &#39;Dog&#39;, name: &#39;Tommy&#39; }
Copy after login

18.Object[key]简写

考虑一个验证函数


function validate(values) {
 if(!values.first)
  return false;
 if(!values.last)
  return false;
 return true;
}

console.log(validate({first:&#39;Bruce&#39;,last:&#39;Wayne&#39;})); // true
Copy after login

假设当需要不同域和规则来验证,能否编写一个通用函数在运行时确认?


// 对象验证规则
const schema = {
 first: {
  required:true
 },
 last: {
  required:true
 }
}

// 通用验证函数
const validate = (schema, values) => {
 for(field in schema) {
  if(schema[field].required) {
   if(!values[field]) {
    return false;
   }
  }
 }
 return true;
}


console.log(validate(schema, {first:&#39;Bruce&#39;})); // false
console.log(validate(schema, {first:&#39;Bruce&#39;,last:&#39;Wayne&#39;})); // true
Copy after login

现在可以有适用于各种情况的验证函数,不需要为了每个而编写自定义验证函数了

19.双重非位运算简写

有一个有效用例用于双重非运算操作符。可以用来代替Math.floor(),其优势在于运行更快,可以阅读此文章了解更多位运算。

Math.floor(4.9) === 4 //true
Copy after login

简写

~~4.9 === 4 //true
Copy after login

到此就完成了相关的介绍,推荐大家继续看下面的相关文章

The above is the detailed content of Introduction to the abbreviation of js. 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)

Detailed introduction to what wapi is Detailed introduction to what wapi is Jan 07, 2024 pm 09:14 PM

Users may have seen the term wapi when using the Internet, but for some people they definitely don’t know what wapi is. The following is a detailed introduction to help those who don’t know to understand. What is wapi: Answer: wapi is the infrastructure for wireless LAN authentication and confidentiality. This is like functions such as infrared and Bluetooth, which are generally covered near places such as office buildings. Basically they are owned by a small department, so the scope of this function is only a few kilometers. Related introduction to wapi: 1. Wapi is a transmission protocol in wireless LAN. 2. This technology can avoid the problems of narrow-band communication and enable better communication. 3. Only one code is needed to transmit the signal

Detailed explanation of whether win11 can run PUBG game Detailed explanation of whether win11 can run PUBG game Jan 06, 2024 pm 07:17 PM

Pubg, also known as PlayerUnknown's Battlegrounds, is a very classic shooting battle royale game that has attracted a lot of players since its popularity in 2016. After the recent launch of win11 system, many players want to play it on win11. Let's follow the editor to see if win11 can play pubg. Can win11 play pubg? Answer: Win11 can play pubg. 1. At the beginning of win11, because win11 needed to enable tpm, many players were banned from pubg. 2. However, based on player feedback, Blue Hole has solved this problem, and now you can play pubg normally in win11. 3. If you meet a pub

Detailed introduction to whether i5 processor can install win11 Detailed introduction to whether i5 processor can install win11 Dec 27, 2023 pm 05:03 PM

i5 is a series of processors owned by Intel. It has various versions of the 11th generation i5, and each generation has different performance. Therefore, whether the i5 processor can install win11 depends on which generation of the processor it is. Let’s follow the editor to learn about it separately. Can i5 processor be installed with win11: Answer: i5 processor can be installed with win11. 1. The eighth-generation and subsequent i51, eighth-generation and subsequent i5 processors can meet Microsoft’s minimum configuration requirements. 2. Therefore, we only need to enter the Microsoft website and download a "Win11 Installation Assistant" 3. After the download is completed, run the installation assistant and follow the prompts to install Win11. 2. i51 before the eighth generation and after the eighth generation

Introducing the latest Win 11 sound tuning method Introducing the latest Win 11 sound tuning method Jan 08, 2024 pm 06:41 PM

After updating to the latest win11, many users find that the sound of their system has changed slightly, but they don’t know how to adjust it. So today, this site brings you an introduction to the latest win11 sound adjustment method for your computer. It is not difficult to operate. And the choices are diverse, come and download and try them out. How to adjust the sound of the latest computer system Windows 11 1. First, right-click the sound icon in the lower right corner of the desktop and select "Playback Settings". 2. Then enter settings and click "Speaker" in the playback bar. 3. Then click "Properties" on the lower right. 4. Click the "Enhance" option bar in the properties. 5. At this time, if the √ in front of "Disable all sound effects" is checked, cancel it. 6. After that, you can select the sound effects below to set and click

PyCharm Beginner's Guide: Comprehensive Analysis of Replacement Functions PyCharm Beginner's Guide: Comprehensive Analysis of Replacement Functions Feb 25, 2024 am 11:15 AM

PyCharm is a powerful Python integrated development environment with rich functions and tools that can greatly improve development efficiency. Among them, the replacement function is one of the functions frequently used in the development process, which can help developers quickly modify the code and improve the code quality. This article will introduce PyCharm's replacement function in detail, combined with specific code examples, to help novices better master and use this function. Introduction to the replacement function PyCharm's replacement function can help developers quickly replace specified text in the code

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

What is Dogecoin What is Dogecoin Apr 01, 2024 pm 04:46 PM

Dogecoin is a cryptocurrency created based on Internet memes, with no fixed supply cap, fast transaction times, low transaction fees, and a large meme community. Uses include small transactions, tips, and charitable donations. However, its unlimited supply, market volatility, and status as a joke coin also bring risks and concerns. What is Dogecoin? Dogecoin is a cryptocurrency created based on internet memes and jokes. Origin and History: Dogecoin was created in December 2013 by two software engineers, Billy Markus and Jackson Palmer. Inspired by the then-popular "Doge" meme, a comical photo featuring a Shiba Inu with broken English. Features and Benefits: Unlimited Supply: Unlike other cryptocurrencies such as Bitcoin

Detailed information on the location of the printer driver on your computer Detailed information on the location of the printer driver on your computer Jan 08, 2024 pm 03:29 PM

Many users have printer drivers installed on their computers but don't know how to find them. Therefore, today I bring you a detailed introduction to the location of the printer driver in the computer. For those who don’t know yet, let’s take a look at where to find the printer driver. When rewriting content without changing the original meaning, you need to The language is rewritten to Chinese, and the original sentence does not need to appear. First, it is recommended to use third-party software to search. 2. Find "Toolbox" in the upper right corner. 3. Find and click "Device Manager" below. Rewritten sentence: 3. Find and click "Device Manager" at the bottom 4. Then open "Print Queue" and find your printer device. This time it is your printer name and model. 5. Right-click the printer device and you can update or uninstall it.

See all articles