Let's take a look at some powerful operators in JavaScript

Let's take a look at some powerful operators in JavaScript

Preface

When you are reading other people's code, have you ever encountered some strange writing methods that made your train of thought stuck instantly? When you come to your senses, you suddenly realize that a certain hero has been here before.

Today, let's take stock of some powerful operators in JavaScript~~~

1. Null coalescing operator

If you see two question marks when you first encounter it, you probably have more question marks in your mind (kids, do you have a lot of question marks~~~)

The two question marks are called the null coalescing operator. If the first argument is not null/undefined, it will return the first argument, otherwise it will return the second argument.

console.log(1 ?? "www.shanzhzonglei.com"); // 1
console.log(false ?? "www.shanzhzonglei.com"); // false
console.log(null ?? "www.shanzhzonglei.com"); // www.shanzhzonglei.com
console.log(undefined ?? "www.shanzhzonglei.com"); // // www.shanzhzonglei.com

Therefore, the second parameter is returned only when the first parameter is null/undefined.

Note that although undefined, null object, value 0, NaN, Boolean false, and empty string '' in JS are all false values, the ?? non-null operator only processes null/undefined.

It is different from the logical OR operator (||), which returns the right-hand operand if the left-hand operand is false. For example, when it is a false value ('' or 0).

console.log(1 || 2); // 1
console.log("" || 2); // 2

2. ??= empty assignment operator

Oh, now there are more than two question marks, there is also an equal sign. Are the questions getting more difficult?

??= Empty assignment operator, this assignment operator will assign a value only when the value is null or undefined.

const student = { age: 20 };
student.age??= 18;
console.log(student.age); // 20

student.name ??= "shanguagua";
console.log(student.name); // 'shanguagua'

It is related to the ?? null coalescing operator above: x ??= y is equivalent to x ?? (x = y), and x = y will only be executed if x is null or undefined.

let x = null;
x ??= 20;
console.log(x); // 20

let y = 5;
y ??= 10;
console.log(y); // 5

3. ?. Optional Chaining Operator

The optional chaining operator ?. allows reading the value of a property that is deep in a chain of connected objects without having to explicitly verify that each reference in the chain is valid. The operator implicitly checks whether the object's property is null or undefined, making the code more elegant and concise.

const obj = {
  name: "山呱呱",
  foo: {
    bar: {
      baz: 18,
      fun: () => {},
    },
  },
  school:
    students:
      {
        name: "shanguagua",
      },
    ],
  },
  say() {
    return "www.shanzhonglei.com";
  },
};

console.log(obj?.foo?.bar?.baz); // 18
console.log(obj?.school?.students?.[0]["name"]); // shanguagua
console.log(obj?.say?.()); // www.shanzhonglei.com

4. ?: Ternary Operator

It is also called ternary operator. Well, this is very commonly used.

For the conditional expression b ? x : y, first calculate condition b and then make a judgment. If the value of b is true, calculate the value of x and the result is the value of x; otherwise, calculate the value of y and the result is the value of y.

console.log(false ? 1 : 2); // 2
console.log(true ? 1 : 2); // 1

5. Logical AND (&&) and Logical OR (||)

Let’s review first:

Logical AND (&&): When the first operand is true, the second operand will not be evaluated, because no matter what the second operand is, the final calculation result must be true.

In actual development, the following operations can be achieved by using this feature:

1. If a value is true, run a function

function say() {
  console.log("www.shanzhonglei.com");
}
let type = true;
type && say(); // www.shanzhonglei.com

2. Determine a value

// Only if age is greater than 10 and less than 20 will it be executed if (age > 10 && age < 20) {
  console.log(age);
}

Logical OR (||): When the first operand is false (that is, the false value of js), the second operand will not be evaluated, because at this time no matter what the second operand is, the final calculation result must be false.

In actual development, the following operations can be achieved by using this feature:

1. Set an initial value for a variable

let student = {
  name: "shanguagua",
};

console.log(student.age || "www.shanzhonglei.com"); // www.shanzhonglei.com

2. Determine a value

// If age is equal to 10 or equal to 20 or equal to 30, execute if (age === 10 || age === 20 || age === 30) {
  console.log(age);
}

6. Bitwise operators & and |

Bitwise operators operate on bits, such as & (and) and | (or). When using bitwise operators, decimal places will be discarded. We can use |0 to round the number. You can also use &1 to determine odd or even numbers.

In actual development, the following operations can be achieved by using this feature:

1. Rounding

1.3 |
  (0 - // print out 1
    1.9) |
  0; // print out -1

2. Determine odd and even numbers

let num = 5;
!!(num & 1); // true
!!(num % 2); // true

7. Double bit operator~~

You can use the bitwise operator instead of Math.floor() for positive numbers and Math.ceil() for negative numbers.

The advantage of the double negation bitwise operator is that it performs the same operation faster; for positive numbers ~~ gives the same result as Math.floor() and for negative numbers it gives the same result as Math.ceil().

Math.floor(5.2) === 5; // true
~~3.2 === 3; // true
Math.ceil(-6.6) === -6; // true
~~-4.5 === -6; // true

7. Logical operators!

!, can convert the variable to boolean type, null, undefined and empty string '' are all negated to true, and the rest are false. Generally speaking, there are several usages: !, !!, !=, !==.

7.1 Using ! to negate

let cat = false;
console.log(!cat); // true

7.2 Using !! to make type judgments

This method can only be executed if the variable a is not equal to null, undefined, or ''.

var a;
if (a != null && typeof a != undefined && a != "") {
  //code that will only be executed if a has content}

is equivalent to:

if (!!a) {
  //aCode that is executed only if there is content...
}

7.3 Are two values ​​equal?

Generally speaking, all are not equal to !==, because if you use not equal to !=, 0 != "" returns false. The reason is that in JS, 0 and '' are both false when converted to Boolean type. Therefore, it is recommended to use all are not equal to !==.

let a = 0;
let b = 0;
let c = "0";
let d = '';
a != b //false
a != c // false number and string's 0 are considered equala != d // false 0 and empty string are considered equala !== b // false
a !== c // true
a !== d // true

Summarize

This concludes this article about some powerful operators in JavaScript. For more information about powerful JavaScript operators, please search previous articles on 123WORDPRESS.COM or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • js and or operator || && magic use
  • Detailed explanation of || and && operators in js
  • JavaScript ternary operator usage examples
  • Usage of javascript typeof and introduction of typeof operator [detailed]
  • Javascript bitwise negation operator (~)
  • Understanding and analysis of JS bitwise non (~) operator and ~~ operator
  • Analysis and examples of the difference between ternary operator and if else in JS
  • Detailed explanation of the usage and function of the JS operator single vertical bar "|" and "||"
  • Teach you the operators of exponentiation, square root and variable format conversion in JS
  • Introduction to Javascript bitwise left shift operator (<<)

<<:  A simple LED digital clock implementation method in CSS3

>>:  Solution to the problem of automatic restoration after modifying server.xml and content.xml in Tomcat

Recommend

Detailed explanation of 8 ways to pass parameters in Vue routing components

When we develop a single-page application, someti...

Use of Linux ls command

1. Introduction The ls command is used to display...

Solution to the problem that MySQL commands cannot be entered in Chinese

Find the problem Recently, when I connected to th...

Five ways to traverse JavaScript arrays

Table of contents 1. for loop: basic and simple 2...

Detailed tutorial on installing centos8 on VMware

CentOS official website address https://www.cento...

Detailed explanation of the use of router-view components in Vue

When developing a Vue project, you often need to ...

Introduction to building a DNS server under centos7

Table of contents 1. Project environment: 2: DNS ...

Detailed explanation of the use of MySQL DML statements

Preface: In the previous article, we mainly intro...

MySQL transaction details

Table of contents Introduction Four characteristi...

Use CSS variables to achieve cool and amazing floating effects

Recently, I found a fun hover animation from the ...

Vue implements the magnifying glass effect of tab switching

This article example shares the specific code of ...

How to deploy gitlab using Docker-compose

Docker-compose deploys gitlab 1. Install Docker I...