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
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

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 Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools