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.

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) ? 'greater 100' : (x < 50) ? 'less 50' : 'between 50 and 100'; 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 !== '') {
let second = first;
}
// Good 短路写法
let second = first|| '';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 || 'default' 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('Hello', name);
}
setTimeout(function() {
console.log('Loaded')
}, 2000)
list.forEach(function(item) {
console.log(item)
})
// Good
const sayHello = name => console.log('Hello', name)
setTimeout(() => console.log('Loaded'), 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 } = form9. 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('test');
}
}
// Good
const checkReturn = () => {
return test || callMe('test');
}12. Short function call
We can use the ternary operator to implement this type of function.
const test1 =() => {
console.log('test1');
}
const test2 =() => {
console.log('test2');
}
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 === 'test1') {
test1();
}
else if (type === 'test2') {
test2();
}
else if (type === 'test3') {
test3();
}
else if (type === 'test4') {
test4();
} else {
throw new Error('Invalid value ' + type);
}
// Good
const types = {
test1: test1,
test2: test2,
test3: test3,
test4: test4
};
const func = types[type];
(!func) && throw new Error('Invalid value ' + type); func();14. Multi-line string abbreviation
When we process multi-line strings in code, we can do this:
// Bad
const data = 'abc abc abc abc abc abc\n\t'
+ 'test test,test test test test\n\t'
// 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: 'abc', test2: 'cde' }
const arr1 = Object.entries(data)
const arr2 = Object.values(data)
const arr3 = Object.keys(data)
/** arr1 Output:
[
[ 'test1', 'abc' ],
[ 'test2', 'cde' ],
]
**/
/** arr2 Output:
['abc', 'cde']
**/
/** arr3 Output:
['test1', 'test2']
**/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 = '';
for(let i = 0; i < 5; i ++) {
test += 'test,';
}
console.log(str);// test,test,test,test,test,
//good
console.log('test,'.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!
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython 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 ResourcesApr 15, 2025 am 12:16 AMPython 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.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AMThis article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base
JavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AMJavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

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

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development 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.






