search
HomeWeb Front-endJS Tutorial19 useful shorthand techniques for JavaScript

19 useful shorthand techniques for JavaScript

Jan 03, 2018 pm 02:56 PM
javascriptjsshare

This article mainly shares 19 useful JavaScript abbreviation techniques with you, hoping to help everyone.

1. Ternary operator

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

<span style="font-size: 16px;">const x = 20;<br>let answer;<br>if (x > 10) {<br>    answer = 'is greater';<br>} else {<br>    answer = 'is lesser';<br>}<br></span>

Abbreviation:
<span style="font-size: 16px;">const answer = x > 10 ? 'is greater' : 'is lesser';</span>

You can also nest if statements:
<span style="font-size: 16px;">const big = x > 10 ? " greater 10" : x</span>

2. Short-circuit evaluation abbreviation

When assigning another value to a variable, you want to make sure that the original value is not null, undefined or empty. You can write a multi-condition if statement.

<span style="font-size: 16px;">if (variable1 !== null || variable1 !== undefined || variable1 !== '') {<br>     let variable2 = variable1;<br>}<br></span>

Or you can use the short-circuit evaluation method:
<span style="font-size: 16px;">const variable2 = variable1 || 'new';</span>

3. Abbreviated method of declaring variables

<span style="font-size: 16px;">let x;<br>let y;<br>let z = 3;<br></span>

Abbreviated method:
<span style="font-size: 16px;">let x, y, z=3 ;</span>

4.if exists condition abbreviation method

##if (likeJavaScript === true)<span style="font-size: 16px;"></span>

Abbreviation:
if (likeJavaScript)<span style="font-size: 16px;"></span>

only when likeJavaScript is true , the two statements are equal

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

<span style="font-size: 16px;">let a;<br>if ( a !== true ) {<br>// do something...<br>}<br></span>

Abbreviation:

<span style="font-size: 16px;">let a;<br>if ( !a ) {<br>// do something...<br>}<br></span>

5. JavaScript loop abbreviation method

for (let i = 0; i

Abbreviation:
for (let index in allImgs)<span style="font-size: 16px;"></span>
You can also use Array.forEach:

<span style="font-size: 16px;">function logArrayElements(element, index, array) {<br>  console.log("a[" + index + "] = " + element);<br>}<br>[2, 5, 9].forEach(logArrayElements);<br>// logs:<br>// a[0] = 2<br>// a[1] = 5<br>// a[2] = 9<br></span>

6. Short-circuit evaluation

The value assigned to a variable is determined by judging whether the value is null or undefined, then you can:

<span style="font-size: 16px;">let dbHost;<br>if (process.env.DB_HOST) {<br>  dbHost = process.env.DB_HOST;<br>} else {<br>  dbHost = 'localhost';<br>}<br></span>

Abbreviation:
const dbHost = process.env.DB_HOST || 'localhost';<span style="font-size: 16px;"></span>

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
Abbreviation:

<span style="font-size: 16px;">for (let i = 0; i <br>// 下面都是返回true<br>1e0 === 1;<br>1e1 === 10;<br>1e2 === 100;<br>1e3 === 1000;<br>1e4 === 10000;<br>1e5 === 100000;<br></span>

8. Object attribute abbreviation

If the attribute name is the same as the key name, you can use the ES6 method:
const obj = { x: x, y:y };<span style="font-size: 16px;"></span>

Abbreviation:
const obj = { x, y };<span style="font-size: 16px;"></span>

9. Arrow function abbreviation

The traditional function writing method is easy for people to understand and write, but when nested in another function, then These advantages are gone.

<span style="font-size: 16px;">function sayHello(name) {<br>  console.log('Hello', name);<br>}<br><br>setTimeout(function() {<br>  console.log('Loaded')<br>}, 2000);<br><br>list.forEach(function(item) {<br>  console.log(item);<br>});<br></span>

Abbreviation:

<span style="font-size: 16px;">sayHello = name => console.log('Hello', name);<br><br>setTimeout(() => console.log('Loaded'), 2000);<br><br>list.forEach(item => console.log(item));<br></span>

10. Implicit return value abbreviation

Return is often used statement to return the final result of a function, an arrow function with a single statement can implicitly return its value (the function must omit {} in order to omit the return keyword)

is a statement that returns multiple lines (for example Object literal expression), you need to surround the function body with ().

<span style="font-size: 16px;">function calcCircumference(diameter) {<br>  return Math.PI * diameter<br>}<br><br>var func = function func() {<br>  return { foo: 1 };<br>};<br></span>

Abbreviation:

<span style="font-size: 16px;">calcCircumference = diameter => (<br>  Math.PI * diameter;<br>)<br><br>var func = () => ({ foo: 1 });<br></span>

11.Default parameter value

In order to provide parameters in the function Passing default values ​​is usually written using if statements, but using ES6 to define default values ​​will be very concise:

<span style="font-size: 16px;">function volume(l, w, h) {<br>  if (w === undefined)<br>    w = 3;<br>  if (h === undefined)<br>    h = 4;<br>  return l * w * h;<br>}<br></span>

Abbreviation:

<span style="font-size: 16px;">volume = (l, w = 3, h = 4 ) => (l * w * h);<br><br>volume(2) //output: 24<br></span>

12. Template string

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

<span style="font-size: 16px;">const welcome = 'You have logged in as ' + first + ' ' + last + '.'<br><br>const db = 'http://' + host + ':' + port + '/' + database;<br></span>

ES6 can use backticks and ${} abbreviation:

<span style="font-size: 16px;">const welcome = `You have logged in as ${first} ${last}`;<br><br>const db = `http://${host}:${port}/${database}`;<br></span>

13.解构赋值简写方法

在web框架中,经常需要从组件和API之间来回传递数组或对象字面形式的数据,然后需要解构它

<span style="font-size: 16px;">const observable = require('mobx/observable');<br>const action = require('mobx/action');<br>const runInAction = require('mobx/runInAction');<br><br>const store = this.props.store;<br>const form = this.props.form;<br>const loading = this.props.loading;<br>const errors = this.props.errors;<br>const entity = this.props.entity;<br></span>

简写:

<span style="font-size: 16px;">import { observable, action, runInAction } from 'mobx';<br><br>const { store, form, loading, errors, entity } = this.props;<br></span>

也可以分配变量名:

<span style="font-size: 16px;">const { store, form, loading, errors, entity:contact } = this.props;<br>//最后一个变量名为contact<br></span>

14.多行字符串简写

需要输出多行字符串,需要使用+来拼接:

<span style="font-size: 16px;">const lorem = 'Lorem ipsum dolor sit amet, consectetur\n\t'<br>    + 'adipisicing elit, sed do eiusmod tempor incididunt\n\t'<br>    + 'ut labore et dolore magna aliqua. Ut enim ad minim\n\t'<br>    + 'veniam, quis nostrud exercitation ullamco laboris\n\t'<br>    + 'nisi ut aliquip ex ea commodo consequat. Duis aute\n\t'<br>    + 'irure dolor in reprehenderit in voluptate velit esse.\n\t'<br></span>

使用反引号,则可以达到简写作用:

<span style="font-size: 16px;">const lorem = `Lorem ipsum dolor sit amet, consectetur<br>    adipisicing elit, sed do eiusmod tempor incididunt<br>    ut labore et dolore magna aliqua. Ut enim ad minim<br>    veniam, quis nostrud exercitation ullamco laboris<br>    nisi ut aliquip ex ea commodo consequat. Duis aute<br>    irure dolor in reprehenderit in voluptate velit esse.`<br></span>

15.扩展运算符简写

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

<span style="font-size: 16px;">// joining arrays<br>const odd = [1, 3, 5];<br>const nums = [2 ,4 , 6].concat(odd);<br><br>// cloning arrays<br>const arr = [1, 2, 3, 4];<br>const arr2 = arr.slice()<br></span>

简写:

<span style="font-size: 16px;">// joining arrays<br>const odd = [1, 3, 5 ];<br>const nums = [2 ,4 , 6, ...odd];<br>console.log(nums); // [ 2, 4, 6, 1, 3, 5 ]<br><br>// cloning arrays<br>const arr = [1, 2, 3, 4];<br>const arr2 = [...arr];<br></span>

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

<span style="font-size: 16px;">const odd = [1, 3, 5 ];<br>const nums = [2, ...odd, 4 , 6];<br></span>

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

<span style="font-size: 16px;">const { a, b, ...z } = { a: 1, b: 2, c: 3, d: 4 };<br>console.log(a) // 1<br>console.log(b) // 2<br>console.log(z) // { c: 3, d: 4 }<br></span>

16.强制参数简写

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

<span style="font-size: 16px;">function foo(bar) {<br>  if(bar === undefined) {<br>    throw new Error('Missing parameter!');<br>  }<br>  return bar;<br>}<br></span>

简写:

<span style="font-size: 16px;">mandatory = () => {<br>  throw new Error('Missing parameter!');<br>}<br><br>foo = (bar = mandatory()) => {<br>  return bar;<br>}<br></span>

17.Array.find简写

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

<span style="font-size: 16px;">const pets = [<br>  { type: 'Dog', name: 'Max'},<br>  { type: 'Cat', name: 'Karl'},<br>  { type: 'Dog', name: 'Tommy'},<br>]<br><br>function findDog(name) {<br>  for(let i = 0; i<pets.length></pets.length>    if(pets[i].type === 'Dog' && pets[i].name === name) {<br>      return pets[i];<br>    }<br>  }<br>}<br></span>

简写:

<span style="font-size: 16px;">pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy');<br>console.log(pet); // { type: 'Dog', name: 'Tommy' }<br></span>

18.Object[key]简写

考虑一个验证函数

<span style="font-size: 16px;">function validate(values) {<br>  if(!values.first)<br>    return false;<br>  if(!values.last)<br>    return false;<br>  return true;<br>}<br><br>console.log(validate({first:'Bruce',last:'Wayne'})); // true<br></span>

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

<span style="font-size: 16px;">// 对象验证规则<br>const schema = {<br>  first: {<br>    required:true<br>  },<br>  last: {<br>    required:true<br>  }<br>}<br><br>// 通用验证函数<br>const validate = (schema, values) => {<br>  for(field in schema) {<br>    if(schema[field].required) {<br>      if(!values[field]) {<br>        return false;<br>      }<br>    }<br>  }<br>  return true;<br>}<br><br><br>console.log(validate(schema, {first:'Bruce'})); // false<br>console.log(validate(schema, {first:'Bruce',last:'Wayne'})); // true<br></span>

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

19.双重非位运算简写

有一个有效用例用于双重非运算操作符。可以用来代替Math.floor(),其优势在于运行更快,可以阅读此文章了解更多位运算。
<span style="font-size: 16px;">Math.floor(4.9) === 4  //true</span>

简写:
<span style="font-size: 16px;">~~4.9 === 4  //true</span>

相关推荐:

js判断是否为空字符串的简写方法实例详解

js的简写写法介绍

怎么简写php 中的三元运算符

The above is the detailed content of 19 useful shorthand techniques for JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

See all articles

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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

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),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment