Tips on if statement optimization and some syntax sugar in JavaScript

Time:2022-5-30

preface

  • In the daily front-end development process, if else judgment statements should be used more frequently. In some complex scenarios, many judgments may be used. When a code block uses a lot of if else, the code will appear redundant and not clear enough to read.
  • In addition to if else, the logical operators & & |, and the Miki operator?, are often used in the development process: Etc.

If else basic use

let name = "zhangsan";
if (name === "zhangsan") {
    console.log("zhangsan"); // zhangsan
} else {
    console.log("lisi");
}

Simplify if judgment and optimize code

Single line if else

if (name === "zhangsan") console.log("zhangsan");
else console.log("lisi");
        

Use & & 𞓜 optimize

let userInfo = {
    name: "zhangsan",
};
if (userInfo.name === "zhangsan") {
    console.log("zhangsan");
}
if (!userInfo.age) {
    //Userinfo Age--> false age attribute does not exist
    Console Log ("age attribute does not exist");
}
userInfo.name === "zhangsan" && console.log("zhangsan");
userInfo.age || Console Log ("age attribute does not exist"); // 年龄属性不存在

Optimize with ternary operators

let name = "zhangsan";
name === "zhangsan" ? console.log("zhangsan") : console.log("lisi");

Merge if


let userObj = { name: "zhangsan", children: { name: "lisi" } };
if (userObj.children) {
  if (userObj.children.name == "lisi") {
    console.log(userObj.children.name);
  }
}
if (userObj.children && userObj.children.name == "lisi")
  console.log(userObj.children.name);

Use includes or indexof


let age = "22";
if (age == "22" || age == "24" || age == "25") {
  console.log(age);
}
let ageArray = ["22", "24", "25"];
if (ageArray.includes(age)) {
  console.log(age);
}
if (ageArray.indexOf(age) > -1) {
  console.log(age);
}

Optimize multiple if else using the switch process

let val = "lisi";
switch (val) {
  case "zhangsan":
    console.log(val);
    break;
  case "lisi":
    console.log(val);
    break;
  case "xiaoming":
    console.log(val);
    break;
  case "xiaowang":
    console.log(val);
    break;
  default:
    console.log(val);
}

Optimize multiple if statements with object key value

let userArray = [
  { name: "zhangsan" },
  { name: "lisi" },
  { name: "xiaoming" },
  { name: "xiaowang" },
];

//Multiple if else
if (userArray.name === "zhangsan") {
  console.log(userArray.name);
} else if (userArray.name === "lisi") {
  console.log(userArray.name);
} else if (userArray.name === "xiaoming") {
  console.log(userArray.name);
} else if (userArray.name === "xiaowang") {
  console.log(userArray.name);
} else {
  Console Log ("other users");
}

function getUser(username) {
  return userArray.filter((item) => item.name == username)[0];
}
console.log(getUser("zhangsan"));

Use map

let filterUser = function (username) {
  Return ` the name is ${username} `;
};
let userMap = new Map([
  ["zhangsan", filterUser("zhangsan")],
  ["lisi", filterUser("lisi")],
  ["xiaoming", filterUser("xiaoming")],
  ["xiaowang", filterUser("xiaowang")],
]);
Console Log (usermap.get ("Zhangsan"))// Name is Zhangsan

Recommend some common JavaScript syntax sugar

Arrow function

/**
 *Arrow function
 *
 * */
function userInfo(name, age) {
  Return ` Name: ${name}, age: ${age}`;
}
Let userinfo = (name, age) = > ` Name: ${name}, age: ${age}`;
console.log(userInfo("zhangsan", "23"));

Ternary operator handler

function log1() {
  console.log(1);
}
function log2() {
  console.log(2);
}
let num = 2;
if (num === 1) {
  log1();
} else {
  log2();
}
num === 1 ? log1() : log2();

Function default parameter handling

let getUser = (name = "zhangsan", age = 23) =>
      `Name: ${name}, age: ${age}`;

Console Log ("default parameter", getuser());
Console Log ("pass parameter", getuser ("Lisi", 29));

Data type conversion

let num1 = +"123";
console.log(num1);

Null, undefined Boolean value and other special value processing, using the combination of |!

/**
 *
 *Null, undefined Boolean value and other special value processing, using the combination of |!
 *
 * */
let name1 = undefined;
let name2 = null;
let name3 = true;
let name4 = false;
let name5 = "lisi";
Console Log (name1 | "others")// someone else
Console Log (Name2 | "others")// someone else
Console Log (name3 | "others")// True
Console Log (! Name3 𞓜 "others")// someone else
Console Log (name4 | "others")// someone else
Console Log (name5 | "others")// Lisi
Console Log (! Name5 | "others")// someone else

Chain judgement operator

During the operation of the operator, it will be executed from left to right first. Whether the object on the left is null or undefined. If yes, the operation will no longer be performed to the right, but will return undefined

For more chain judgment operators, please refer to

Chain judgement operator

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Optional_chaining


let user = {
  name: "zhangsan",
  children: { name: "lisi", children: { name: "xiaoming" } },
};
let name1 = user?.name;
let name2 = user?.children?.name;
let name3 = user?.children?.children?.name;
console.log(name1);
console.log(name2);
console.log(name3);

Null value merge operator??

concept

  • Null merge operator (?) Is a logical operator. When the left operand is null or undefined, it returns the right operand. Otherwise, it returns the left operand.
  • Unlike the logical or operator (||), the logical or operator returns the right operand when the left operand is false.
  • If you use 𞓜 to set default values for some variables, you may encounter unexpected behavior. For example, when it is a false value (for example, ” or 0).

const foo = null ?? "default string";
const test = undefined ?? "default string";
const test1 = 123 ?? "default string";
console.log(test); // "default string"
console.log(foo); // "default string"
console.log(test1); // 123
const baz = 0 ?? 42;
console.log(baz); // 0
const str = "" ?? 42;
const str1 = "" || 42;
console.log(str); // ""
console.log(str1); // 42

Summary

  • The above are some suggestions for if code optimization. Sometimes, if else is relatively cumbersome, but it is also a relatively direct judgment statement
  • Whether to optimize if statements or to do so according to specific business scenarios requires personal judgment
  • In the daily development process of JavaScript syntax sugar, some tedious judgments or semantics can be eliminated
  • ECMA syntax of ES6 or higher version has been updated a lot. For some syntax extensions, it still provides a lot of help in the development process.

Source address

Blog address:Tips on if statement optimization and some syntax sugar in JavaScript

Welcome to the official account: programmer boo, who updates some front-end introductory articles from time to time

Creation is not easy, please indicate the source and author for reprint.