- read

6 Code Optimization Tips Every Front-End Should Master

Xiuer Old 39

6 Code Optimization Tips Every Front-End Should Master

Xiuer Old
JavaScript in Plain English
4 min read3 days ago

--

This article will introduce 6 JavaScript optimization techniques that can help you write better, concise and elegant code.

1. Automatic matching of strings ( Array.includes)

When writing code, we often encounter such a need. We need to check whether a certain string is one of the strings that meets our requirements. The most common method is to use || and === to judge matching. However, if this judgment method is used extensively, our code will definitely become very bloated and very tiring to write. In fact, we can use it Array.includes to help us automatically match.

example:

// Writing method before optimization
const isConform = (letter) => {
if (
letter === "a" ||
letter === "b" ||
letter === "c" ||
letter === "d" ||
letter === "e"
) {
return true;
}
return false;
};
//Optimized writing method
const isConform = (letter) =>
["a", "b", "c", "d", "e"].includes(letter);

2. for-of And for-inautomatic traversal

for-of and for-in, can help us automatically traverse Array each object element in the sum, without requiring us to manually change the index to traverse the elements.

Note: We prefer object to use traversal for objects () for-in and traversal Arrayfor arrays () for-of

for-of

const arr = ['a',' b', 'c'];
// Writing method before optimization
for (let i = 0; i < arr.length; i++) {
const element = arr[i];
console.log(element);
}
//Optimized writing method
for (const element of arr) {
console.log(element);
}
// expected output: "a"
// expected output: "b"
// expected output: "c"

for-in

const obj = {
a: 1,
b: 2,
c: 3,
};
// Writing method before optimization
const keys = Object.keys(obj);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const value = obj[key];
// ...
}
//Optimized writing method
for (const key in obj) {
const value = obj[key];
// ...
}

3.false judgment