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

Causes and solutions for slow MySQL queries

There are many reasons for slow query speed, the ...

Details on using JS array methods some, every and find

Table of contents 1. some 2. every 3. find 1. som...

Docker+nextcloud to build a personal cloud storage system

1. Docker installation and startup yum install ep...

HTML&CSS&JS compatibility tree (IE, Firefox, Chrome)

What is a tree in web design? Simply put, clicking...

Html Select option How to make the default selection

Adding the attribute selected = "selected&quo...

Detailed explanation of HTML document types

Mine is: <!DOCTYPE html> Blog Garden: <!...

Practical tutorial on modifying MySQL character set

Preface: In MySQL, the system supports many chara...

JS+AJAX realizes the linkage of province, city and district drop-down lists

This article shares the specific code of JS+AJAX ...

How MLSQL Stack makes stream debugging easier

Preface A classmate is investigating MLSQL Stack&...

Detailed explanation of docker nginx container startup and mounting to local

First, the structure inside the nginx container: ...

Docker generates images through containers and submits DockerCommit in detail

Table of contents After creating a container loca...

How to understand SELinux under Linux

Table of contents 1. Introduction to SELinux 2. B...

4 Ways to Quickly Teach Yourself Linux Commands

If you want to become a Linux master, then master...

The connection between JavaScript constructors and prototypes

Table of contents 1. Constructors and prototypes ...

Web page CSS priority is explained in detail for you

Before talking about CSS priority, we need to und...