Summary of uncommon js operation operators

Summary of uncommon js operation operators

1. Introduction

There are many operators in js, which have been mentioned in previous articles. For example:

js integer operations:

Using |0 and ~~ can convert floating points into integers, and the efficiency is faster than similar parseInt and Math.round . It is very useful when processing pixel and animation displacement effects. See here for performance comparison.

var foo = (12.4 / 4.13) | 0; // the result is 3
var bar = ~~(12.4 / 4.13); //The result is 3


There is another little trick, that is !!2 exclamation marks can quickly convert a value into a Boolean value. You can test it!

var eee="eee";
alert(!!eee)


These are some operators. For details, please see 49 JavaScript tips and tricks. The js operator single vertical bar "|"

A few more to add today:

2. Comma operator

let x = 1;
x = (x++, x);
console.log(x);
// expected output: 2
x = (2, 3);
console.log(x);
// expected output: 3

The comma operator evaluates the argument on the left before the argument on the right. The value of the rightmost argument is then returned.

var a = 10, b = 20;

function CommaTest(){
    return a++, b++, 10;
}

var c = CommaTest();

alert(a); // returns 11
alert(b); // returns 21
alert(c); // returns 10

Now that we know the call function operators, let's take an example to illustrate how to handle their conflicts.

alert(2*5, 2*4); // Output 10

The code above outputs 10, but if interpreted according to the principle of the comma operator, it should output 8. Why?

Since the comma operator has the lowest precedence in JavaScript , this is very useful to remember. So the function call operator will run before the comma operator. As a result, the alert function outputs the value of the first parameter. Modify the above code as shown below.

alert((2*5, 2*4)); // returns 8

3. JavaScript Null Coalescing Operator (??)

The null coalescing operator (??) is a logical operator that returns the right operand only when the left operand is null or undefined , otherwise undefined returns the left operand.

This is different from the logical OR operator (||), which returns the right-hand operand if the left-hand operand is false. That is, if you use || to set default values ​​for certain variables, you may encounter unexpected behavior. For example, when it is false (for example, '' or 0). See example below.

let str = null||undefined
let result = str??'haorooms blog'
console.log(result)//haorooms blog const nullValue = null;
const emptyText = ""; // Empty string, a false value, Boolean("") === false
const someNumber = 42;

const valA = nullValue ?? "the default value of valA";
const valB = emptyText ?? "The default value of valB";
const valC = someNumber ?? 0;

console.log(valA); // "default value of valA"
console.log(valB); // "" (Empty string is false, but not null or undefined)
console.log(valC); // 42

4. javascript 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 functions similarly to the . chaining operator, except that it does not cause an error if the reference is nullish (null or undefined), and the expression short-circuits the return value.

Using the optional chaining operator ( ?. ) the browser will not complain!

const demo = {
    name: 'haorooms',
    cat: {
        name: 'haorooms cat'
    }
};
console.log(demo.dog?.name); 
// expected output: undefined
console.log(demo.what?.());
// expected output: undefined


Function call:

let result = someOne.customMethod?.();

If you want to allow someOne to be null or undefined , you need to write someOne?.customMethod?.() like this:

Optional chaining with expressions:

let nestedProp = obj?.['prop' + 'Name'];

Optional chaining to access arrays:

let arrayItem = arr?.[42];

Short circuit calculation:

let potentiallyNullObj = null;
let x = 0;
let prop = potentiallyNullObj?.[x++];

 
console.log(x); // x will not be incremented, and will still output 0

//When using optional chaining in an expression, if the left operand is null or undefined, the expression will not be evaluated let customer = {
  name: "haorooms",
  details: { age: 82 }
};

let customerCity = customer?.city ?? "中国";
console.log(customerCity); // "China"

This is the end of this article about the summary of uncommon js operation operators. For more relevant js operation operator content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JavaScript operators explained in detail never before
  • JavaScript Basics Operators
  • Summary of uncommon operators and operators in js
  • Summary of some efficient magic operators in JS
  • Stop using absolute equality operators everywhere in JS
  • Let's take a look at the same old JS operator explanation

<<:  Detailed process of using Vscode combined with docker for development

>>:  CSS implements a pop-up window effect with a mask layer that can be closed

Recommend

How to automatically back up the mysql database regularly

We all know that data is priceless. If we don’t b...

Summary of commonly used tool functions in Vue projects

Table of contents Preface 1. Custom focus command...

Using Nginx to implement grayscale release

Grayscale release refers to a release method that...

Two ways to remove the 30-second ad code from Youku video

I believe everyone has had this feeling: watching ...

MySQL Learning: Three Paradigms for Beginners

Table of contents 1. Paradigm foundation 1.1 The ...

MySQL high availability cluster deployment and failover implementation

Table of contents 1. MHA 1. Concept 2. Compositio...

Pure JavaScript to implement the number guessing game

Develop a number guessing game that randomly sele...

Nginx+FastDFS to build an image server

Installation Environment Centos Environment Depen...

Implementation of dynamic rem for mobile layout

Dynamic rem 1. First, let’s introduce the current...

Detailed explanation of Vue3's responsive principle

Table of contents Review of Vue2 responsive princ...

Complete Tutorial on Deploying Java Web Project on Linux Server

Most of this article refers to other tutorials on...

Basic ideas for finding errors in Web front-end development

WEB development mainly consists of two interactio...