Recommend a practical interview question bank for everyone
1. Front-end interview question bank ( necessary for interview) recommendation: ★★★★★
Address: front-end interview question bank
In today's article, I will share with you 20 JavaScript techniques that I have collected and used. I hope that the content in today's article can help you and make your work more efficient! Easier! Let's get started now.
1. Multi-conditional if statement
Put multiple values into an array, then call the array's include method.
less
复制代码
less
复制代码
// bad
if (x === "abc" || x === "def" || x === "ghi" || x === "jkl") {
//logic
}
// better
if (["abc", "def", "ghi", "jkl"].includes(x)) {
//logic
}
2. Simplify if true...else conditional expression
// bad
let test: boolean;
if (x > 100) {
test = true;
} else {
test = false;
}
// better
let test = x > 10 ? true : false;
//or let test = x > 10;
console.log(test);
3. False value (undefined, null, 0, false, NaN, empty string) check
When we create a new variable, sometimes we want to check whether the referenced variable is a false value, such as null or undefined or an empty string. JavaScript does provide a nice shortcut for this kind of check - the logical OR operator (||)
|| Only if the left side is empty or NaN or null or undefined or false, the right side operand will be returned if the left side operand is false, and the logical OR operator ( || ) will return the value on the right side.
// bad
if (test1 !== null || test1 !== undefined || test1 !== "") {
let test2 = test1;
}
//
better
let test2 = test1 || "";
// bad
if (test1 === true) or if (test1 !== "") or if (test1 !== null)
// better
if (test1){
// do some
}else{
// do other
}
//Note: If test1 has a value, the logic after if will be executed. //This operator is mainly used for null, undefined, and empty string checks.
4. Null/undefined checks and default assignments
//null checking and default assignment
let test1 = null;
let test2 = test1 ?? "";
console.log("null check", test2); // output empty string ""
//undefined checking and default assignment
const test = undefined ?? "default";
console.log(test);// expected output: "default"
5. Get the last item in the list
In other languages, this functionality is made into a method or function that can be called on the array, but in JavaScript, you have to do some work yourself.
6. Return after comparison
7. Use the optional chaining operator -?.
? Also known as a chain judgment operation, it allows developers to read property values deeply nested in object chains without validating each reference. When the reference is empty, the expression stops evaluating and returns undefined.
const travelPlans = {
destination: "DC",
monday: {
location: "National Mall",
budget: 200, },
};
// bad
const res = travelPlans && travelPlans.tuesday && travelPlans.tuesday.location && travelPlans.tuesday.location.href;
console.log(res); // Result: undefined
// better
const res1 = travelPlans?.tuesday?.location?.href;
console.log(res1); // Result: undefined
8. The && operator for multiple conditions
To call a function only when a variable is true, use the && operator.
This is useful for short-circuiting with (&&) when you want to conditionally render components in React. For example:
9. Switch Simplification
We can store conditions in key-value objects and call them based on conditions.
switch (data) {
case 1:
test1();
break;
case 2:
test2();
break;
case 3:
test();
break; // And so on...
}
// better
var data = {
1: test1,
2: test2,
3: test,
};
// If type exists in data, execute the corresponding function
data[type] && data[type]();
10. Default parameter values
function add(test1, test2) {
if (test1 === undefined)
test1 = 1;
if (test2 === undefined)
test2 = 2;
return test1 + test2;}
// better
add = (test1 = 1, test2 = 2) => test1 + test2;add(); //output: 3
11. Simplified conditional search
If we wanted to call different methods based on different types, we could use multiple else if statements or switches, but is there a better simplification trick than this? In fact, it is the same as the previous switch simplification.
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);
}
// better
var types = { test1, test2, test3, test4,};types[type] && types[type]();
12. Object property assignment
ini
复制代码
ini
复制代码
let test1 = "a";let test2 = "b";
// bad
let obj = { test1: test1, test2: test2 };
// better
let obj = { test1, test2 };
13. Destructuring assignment
// bad
const test1 = this.data.test1;
const test2 = this.data.test2;
const test3 = this.data.test3;
// better
const { test1, test2, test3 } = this.data;
14. Template strings
If you're tired of using + to concatenate multiple variables into one string, this simplification trick will give you a headache.
// bad
const welcome = "Hi " + test1 + " " + test2 + ".";
// better
const welcome = `Hi ${test1} ${test2}`;
15. Spanning strings
// bad
const data =
"hello maxwell this is a test\n\t" + "test test,test test test test\n\t";
// better
const data = `hello maxwell this is a test
test test,test test test test`;
16. Bitwise reduction of indexOf
When looking up a value in an array, we can use the indexOf() method. But there is a better way, let's look at this example.
// bad
if (arr.indexOf(item) > -1) {
// item found
}
if (arr.indexOf(item) === -1) {
// item not found
}
// better
if (~arr.indexOf(item)) {
// item found
}
if (!~arr.indexOf(item)) {
// item not found
}
//The bitwise (~) operator will return true (except for -1), //the reverse operation only requires !~. Alternatively, the includes() function can be used.
if (arr.includes(item)) {
// true if the item found
}
17. Convert string to number
There are built-in methods such as parseInt and parseFloat for converting strings to numbers. We can also do this simply by providing the unary operator (+) in front of the string.
// bad
let total = parseInt("583");
let average = parseFloat("32.5");
// better
let total = +"583";
let average = +"32.5";
18. Sequential fulfillment of Promises
What if you have a bunch of async or normal functions that all return Promises that require you to fulfill them one by one?
async function getData() {
const promises = [fetch("url1"), fetch("url2"), fetch("url3"), fetch("url4")];
for (const item of promises) {
// Print out the promise
console.log(item);
}
// better
for await (const item of promises) {
// Print out the results of the request
console.log(item);
}
}
Wait for all Promiae to complete.
The Promise.allSettled() method takes a set of Promise instances as parameters and wraps them into a new Promise instance. The wrapper instance will not end until all of these parameter instances have returned a result (completed or rejected).
Sometimes, we don't care about the results of asynchronous requests, we only care about whether all requests are over. At this time, the Promise.allSettled() method is very useful.
const promises = [fetch("index.html"), fetch("https://does-not-exist/")];
const results = await Promise.allSettled(promises);
// Filter out successful requests
const successfulPromises = results.filter((p) => p.status === "fulfilled");
// Filter out failed requests and output the reason
const errors = results.filter((p) => p.status === "rejected").map((p) => p.reason);
19. Swap the position of array elements
const swapWay = (arr, i, j) => { const newArr = [...arr];
let temp = newArr[i];
newArr[i] = list[j]; newArr[j] = temp;
return newArr;};
//Since ES6, swapping values from different locations in an array has become much easier
// better
const swapWay = (arr, i, j) => { const newArr = [...arr];
const [newArr[j],newArr[i]] = [newArr[i],newArr[j]];
return newArr;};
20. Random number generator with range
Sometimes you need to generate random numbers, but you want the numbers to be within a certain range, you can use this tool.
function randomNumber(max = 1, min = 0) {
if (min >= max) {
return max;
}
return Math.floor(Math.random() * (max - min) + min);
}
generate random colors
function getRandomColor() {
const colorAngle = Math.floor(Math.random() * 360);
return `hsla(${colorAngle},100%,50%,1)`;
}
Recommend a practical interview question bank for everyone
1. Front-end interview question bank ( necessary for interview) recommendation: ★★★★★
Address: front-end interview question bank