search
HomeWeb Front-endJS Tutorial18 JavaScript Optimization Tips You Need to Know

In this article, let’s take a look at 18 optimization techniques for JavaScript. It is suitable for all developers who are using JavaScript programming. The purpose of this article is to help you become more proficient in using the JavaScript language for development work. I hope it will be useful to everyone. help.

18 JavaScript Optimization Tips You Need to Know

1. Judgment of multiple conditions

When we need to judge multiple values , we can use the includes method of the array.

//Bad
if (x === 'iphoneX' || x === 'iphone11' || x === 'iphone12') {
//code... 
}
//Good
if (['iphoneX', 'iphone11', 'iphone12'].includes(x)) {
//code...
}

2. If true ... else

When the inside of the if-else condition does not contain greater logic, the ternary operator will be better.

// Bad
let test= boolean;
if (x > 100) {
test = true;
} else {
test = false;
}
// Good
let test = (x > 10) ? true : false;
//or we can simply use
let test = x > 10;

After nesting the conditions, we retain the content as shown below (three eyes of complex points):

let x = 300,
let test2 = (x > 100) ? &#39;greater 100&#39; : (x < 50) ? &#39;less 50&#39; : &#39;between 50 and 100&#39;;
console.log(test2); // "greater than 100"

3. Null, Undefined, '' null value Check

Sometimes we need to check whether the variable we reference for the value is not null or Undefined or '', we can use the short-circuit writing

// Bad
if (first !== null || first !== undefined || first !== &#39;&#39;) {
let second = first;
}
// Good 短路写法
let second = first|| &#39;&#39;;

4. Null value check and assign default value

When we assign a value and find that the variable is empty and need to assign a default value, we can use the following short-circuit writing method

let first = null,
let second = first || &#39;default&#39;
console.log(second)

4. Double-bit operators

Bit operators are the basic knowledge points in JavaScript beginner tutorials, but we don’t often use bit operators. Because no one wants to work with 1s and 0s without dealing with binary.

But the double-bit operator has a very practical case. You can use double-bit operators instead of Math.floor( ). The advantage of the double negative bit operator is that it performs the same operation faster

// Bad
Math.floor(4.9) === 4  //true
// Good
~~4.9 === 4  //true

5. ES6 common small optimizations - Object properties

const x,y = 5
// Bad
const obj = { x:x, y:y }
// Good
const obj = { x, y }

6. ES6 common minor optimizations - arrow functions

//Bad
function sayHello(name) {
  console.log(&#39;Hello&#39;, name);
}
setTimeout(function() {
  console.log(&#39;Loaded&#39;)
}, 2000)
list.forEach(function(item) {
  console.log(item)
})
// Good
const sayHello = name => console.log(&#39;Hello&#39;, name)
setTimeout(() => console.log(&#39;Loaded&#39;), 2000)
list.forEach(item => console.log(item))

7. ES6 common minor optimizations - implicit return values

Return value is the keyword we usually use to return the final result of the function. An arrow function with only one statement can return a result implicitly (the function must omit the parentheses ({ }) in order to omit the return keyword).

To return a multi-line statement (such as object text), you need to use () instead of {} to wrap the function body. This ensures that the code is evaluated as a single statement.

//Bad
function calcCircumference(diameter) {
  return Math.PI * diameter
}
// Good
const calcCircumference = diameter => (
  Math.PI * diameter
)

8. ES6 common minor optimizations - destructuring assignment

const form = { a:1, b:2, c:3 }
//Bad
const a = form.a
const b = form.b
const c = form.c
// Good
const { a, b, c } = form

9. ES6 common minor optimizations - expansion operations The symbol

The return value is the keyword we usually use to return the final result of the function. An arrow function with only one statement can return a result implicitly (the function must omit the parentheses ({ }) in order to omit the return keyword).

To return a multi-line statement (such as object text), you need to use () instead of {} to wrap the function body. This ensures that the code is evaluated as a single statement.

const odd = [ 1, 3, 5 ]
const arr = [ 1, 2, 3, 4 ]
// Bad
const nums = [ 2, 4, 6 ].concat(odd)
const arr2 = arr.slice( )
// Good
const nums = [2 ,4 , 6, ...odd]
const arr2 = [...arr]

10. Common array processing

Master the common methods of arrays and keep them in your mind. Don’t look at the API when writing. This can effectively improve coding efficiency. After all, these methods are used every day

every some filter map forEach find findIndex reduce includes

const arr = [1,2,3]
//every 每一项都成立,才会返回true
console.log( arr.every(it => it>0 ) ) //true
//some 有一项都成了,就会返回true
console.log( arr.some(it => it>2 ) ) //true
//filter 过滤器
console.log( arr.filter(it => it===2 ) ) //[2]
//map 返回一个新数组
console.log( arr.map(it => it==={id:it} ) ) //[ {id:1},{id:2},{id:3} ]
//forEach 没有返回值
console.log( arr.forEach(it => it===console.log(it)) ) //undefined
//find 查找对应值 找到就立马返回符合要求的新数组
console.log( arr.find(it => it===it>2) ) //3
//findIndex 查找对应值 找到就立马返回符合要求新数组的下标
console.log( arr.findIndex(it => it===it>2) ) //2
//reduce 求和或者合并数组
console.log( arr.reduce((prev,cur) => prev+cur) ) //6
//includes 求和或者合并数组
console.log( arr.includes(1) ) //true
//数组去重
const arr1 = [1,2,3,3]
const removeRepeat = (arr) => [...new Set(arr1)]//[1,2,3]
//数组求最大值
Math.max(...arr)//3
Math.min(...arr)//1
//对象解构 这种情况也可以使用Object.assign代替
let defaultParams={
    pageSize:1,
    sort:1
}
//goods1
let reqParams={
    ...defaultParams,
    sort:2
}
//goods2
Object.assign( defaultParams, {sort:2} )

11. Comparison returns

Using comparison in the return statement can reduce the code from 5 lines to 1 line.

// Bad
let test
const checkReturn = () => {
    if (test !== undefined) {
        return test;
    } else {
        return callMe(&#39;test&#39;);
}
}
// Good
const checkReturn = () => {
return test || callMe(&#39;test&#39;);
}

12. Short function call

We can use the ternary operator to implement this type of function.

const test1 =() => {
  console.log(&#39;test1&#39;);
}
const test2 =() => {
  console.log(&#39;test2&#39;);
}
const test3 = 1;
if (test3 == 1) {
  test1()
} else {
  test2()
}
// Good
test3 === 1? test1():test2()

13.switch code block (ifelse code block) abbreviation

We can save the condition in the key-value object, and then Use according to conditions.

// Bad
switch (data) {
  case 1:
    test1();
  break;
  case 2:
    test2();
  break;
  case 3:
    test();
  break;
  // And so on...
}
// Good
const data = {
  1: test1,
  2: test2,
  3: test
}
data[anything] && data[anything]()
// Bad
if (type === &#39;test1&#39;) {
  test1();
}
else if (type === &#39;test2&#39;) {
  test2();
}
else if (type === &#39;test3&#39;) {
  test3();
}
else if (type === &#39;test4&#39;) {
  test4();
} else {
  throw new Error(&#39;Invalid value &#39; + type);
}
// Good
const types = {
  test1: test1,
  test2: test2,
  test3: test3,
  test4: test4
};
const func = types[type];
(!func) && throw new Error(&#39;Invalid value &#39; + type); func();

14. Multi-line string abbreviation

When we process multi-line strings in code, we can do this:

// Bad
const data = &#39;abc abc abc abc abc abc\n\t&#39;
+ &#39;test test,test test test test\n\t&#39;
// Good
const data = `abc abc abc abc abc abc
         test test,test test test test`

15. Object.entries() Object.values() Object.keys()

Object.entries() This feature can Object is converted into an array of objects.

Object.values() can get the object value

Object.keys() can get the object key value

const data = { test1: &#39;abc&#39;, test2: &#39;cde&#39; }
const arr1 = Object.entries(data)
const arr2 = Object.values(data)
const arr3 = Object.keys(data)
/** arr1 Output:
[ 
    [ &#39;test1&#39;, &#39;abc&#39; ],
    [ &#39;test2&#39;, &#39;cde&#39; ],
]
**/
/** arr2 Output:
[&#39;abc&#39;, &#39;cde&#39;]
**/
/** arr3 Output:
[&#39;test1&#39;, &#39;test2&#39;]
**/

16. More Repeat a string

In order to repeat the same character multiple times, we can use a for loop and add them to the same loop. How to abbreviate it?

//Bad 
let test = &#39;&#39;; 
for(let i = 0; i < 5; i ++) { 
  test += &#39;test,&#39;; 
} 
console.log(str);// test,test,test,test,test,
//good 
console.log(&#39;test,&#39;.repeat(5))

17. The abbreviation of power

The good of mathematical exponential power function is as follows:

//Bad 
Math.pow(2,3)// 8
//good 
2**3 // 8

18. Number separators

#You can now easily separate numbers by just using _. This will make it easier to handle large amounts of data.

//old syntax
let number = 98234567
//new syntax
let number = 98_234_567

If you want to use the latest features of the latest version of JavaScript (ES2021/ES12), please check the following:

  • 1.replaceAll(): Returns a new string in which all matching patterns are replaced by new replacement words.

  • 2.Promise.any(): An iterable Promise object is required. When a Promise is completed, a Promise with a value is returned.

  • 3.weakref: This object holds a weak reference to another object and does not prevent the object from being garbage collected.

  • 4.FinalizationRegistry: Allows you to request a callback when the object is garbage collected.

  • 5. Private methods: Modifiers for methods and accessors: Private methods can be declared with #.

  • 6. Logical operators: && and || operators.

  • 7.Intl.ListFormat: This object enables language-sensitive list formatting.

  • 8.Intl.DateTimeFormat: This object enables language-sensitive date and time formatting.

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of 18 JavaScript Optimization Tips You Need to Know. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

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 vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

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.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

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 in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

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.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

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 the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

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 vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

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 vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

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.

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

MantisBT

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.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools