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

Summary of the differences and usage of plugins and components in Vue

The operating environment of this tutorial: Windo...

Several practical scenarios for implementing the replace function in MySQL

REPLACE Syntax REPLACE(String,from_str,to_str) Th...

Various methods to implement the prompt function of text box in html

You can use the attribute in HTML5 <input="...

Web Design: Web Music Implementation Techniques

<br />When inserting music into a web page, ...

Analysis and solution of data loss during Vue component value transfer

Preface In the previous article Two data types in...

The forgotten button tag

Note: This article has been translated by someone ...

OpenSSL implements two-way authentication tutorial (with server and client code)

1. Background 1.1 Problems A recent product testi...

MySQL 5.6.33 installation and configuration tutorial under Linux

This tutorial shares the installation and configu...

Detailed explanation of the background-position percentage principle

When I was helping someone adjust the code today,...

Introduction to installing JDK under Linux, including uninstalling OpenJDK

1. View openjdk rpm -qa|grep jdk 2. Delete openjd...

Native JS to implement real-time clock

Share a real-time clock effect implemented with n...

How to create Apache image using Dockerfile

Table of contents 1. Docker Image 2. Create an in...

Ubuntu compiles kernel modules, and the content is reflected in the system log

Table of contents 1.Linux login interface 2. Writ...