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'; }
Abbreviation:
const answer = x > 10 ? 'is greater' : 'is lesser';
You can also nest if statements:
const big = x > 10 ? " greater 10" : x
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; }
Or you can use the short-circuit evaluation method:
const variable2 = variable1 || 'new';
3. Declaring variable abbreviation method
let x; let y; let z = 3;
Abbreviation method:
let x, y, z=3;
4.if exists condition abbreviation method
if (likeJavaScript === true)
Abbreviation:
if (likeJavaScript)
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... }
Abbreviation:
let a; if ( !a ) { // do something... }
5. JavaScript loop abbreviation method
for (let i = 0; i < allImgs.length; i++)
Abbreviation:
for (let index in allImgs)
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
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 = 'localhost'; }
Abbreviation:
const dbHost = process.env.DB_HOST || 'localhost';
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++) {}
Abbreviation:
for (let i = 0; i < 1e7; i++) {} // 下面都是返回true 1e0 === 1; 1e1 === 10; 1e2 === 100; 1e3 === 1000; 1e4 === 10000; 1e5 === 100000;
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 };
Abbreviation:
const obj = { x, y };
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('Hello', name); } setTimeout(function() { console.log('Loaded') }, 2000); list.forEach(function(item) { console.log(item); });
Abbreviation:
sayHello = name => console.log('Hello', name); setTimeout(() => console.log('Loaded'), 2000); list.forEach(item => console.log(item));
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 return
Keyword)
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 }; };
Abbreviation:
calcCircumference = diameter => ( Math.PI * diameter; ) var func = () => ({ foo: 1 });
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; }
Abbreviation:
volume = (l, w = 3, h = 4 ) => (l * w * h); volume(2) //output: 24
12. Template string
In traditional JavaScript language, the output template is usually written like this.
const welcome = 'You have logged in as ' + first + ' ' + last + '.' const db = 'http://' + host + ':' + port + '/' + database;
ES6 can use backticks and ${}
abbreviation:
const welcome = `You have logged in as ${first} ${last}`; const db = `http://${host}:${port}/${database}`;
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('mobx/observable'); const action = require('mobx/action'); const runInAction = require('mobx/runInAction'); 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;
Abbreviation:
import { observable, action, runInAction } from 'mobx'; const { store, form, loading, errors, entity } = this.props;
You can also assign variable name :
const { store, form, loading, errors, entity:contact } = this.props; //最后一个变量名为contact
14. Multi-line string abbreviation
If you need to output a multi-line string, you need to use + to splice it:
const lorem = 'Lorem ipsum dolor sit amet, consectetur\n\t' + 'adipisicing elit, sed do eiusmod tempor incididunt\n\t' + 'ut labore et dolore magna aliqua. Ut enim ad minim\n\t' + 'veniam, quis nostrud exercitation ullamco laboris\n\t' + 'nisi ut aliquip ex ea commodo consequat. Duis aute\n\t' + 'irure dolor in reprehenderit in voluptate velit esse.\n\t'
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.`
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()
简写:
// 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];
不像concat()
函数,可以使用扩展运算符来在一个数组中任意处插入另一个数组。
const odd = [1, 3, 5 ]; const nums = [2, ...odd, 4 , 6];
也可以使用扩展运算符解构:
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 }
16.强制参数简写
JavaScript中如果没有向函数参数传递值,则参数为undefined
。为了增强参数赋值,可以使用if
语句来抛出异常,或使用强制参数简写方法。
function foo(bar) { if(bar === undefined) { throw new Error('Missing parameter!'); } return bar; }
简写:
mandatory = () => { throw new Error('Missing parameter!'); } foo = (bar = mandatory()) => { return bar; }
17.Array.find简写
想从数组中查找某个值,则需要循环。在ES6中,find()
函数能实现同样效果。
const pets = [ { type: 'Dog', name: 'Max'}, { type: 'Cat', name: 'Karl'}, { type: 'Dog', name: 'Tommy'}, ] function findDog(name) { for(let i = 0; i<pets.length; ++i) { if(pets[i].type === 'Dog' && pets[i].name === name) { return pets[i]; } } }
简写:
pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy'); console.log(pet); // { type: 'Dog', name: 'Tommy' }
18.Object[key]简写
考虑一个验证函数
function validate(values) { if(!values.first) return false; if(!values.last) return false; return true; } console.log(validate({first:'Bruce',last:'Wayne'})); // true
假设当需要不同域和规则来验证,能否编写一个通用函数在运行时确认?
// 对象验证规则 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:'Bruce'})); // false console.log(validate(schema, {first:'Bruce',last:'Wayne'})); // true
现在可以有适用于各种情况的验证函数,不需要为了每个而编写自定义验证函数了
19.双重非位运算简写
有一个有效用例用于双重非运算操作符。可以用来代替Math.floor()
,其优势在于运行更快,可以阅读此文章了解更多位运算。
Math.floor(4.9) === 4 //true
简写
~~4.9 === 4 //true
到此就完成了相关的介绍,推荐大家继续看下面的相关文章
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!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment