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

Analysis of different MySQL table sorting rules error

The following error is reported when MySQL joins ...

Common usage of regular expressions in Mysql

Common usage of Regexp in Mysql Fuzzy matching, c...

How to limit the value range of object keys in TypeScript

When we use TypeScript, we want to use the type s...

Specific method of viewing user authorization information in mysql

Specific method: 1. Open Command Prompt 2. Enter ...

Linux uses suid vim.basic file to achieve privilege escalation

Reproduce on Kali First set suid permissions for ...

How to use cursor triggers in MySQL

cursor The set of rows returned by the select que...

Basic usage and examples of yum (recommended)

yum command Yum (full name Yellow dog Updater, Mo...

How to completely uninstall node and npm on mac

npm uninstall sudo npm uninstall npm -g If you en...

JavaScript Basics Objects

Table of contents 1. Object 1.1 What is an object...

Use of hasOwnProperty method of js attribute object

Object's hasOwnProperty() method returns a Bo...

Turn off the AutoComplete function in the input box

Now we can use an attribute of input called autoco...

Tkinter uses js canvas to achieve gradient color

Table of contents 1. Use RGB to represent color 2...

MySQL foreign key constraint (FOREIGN KEY) case explanation

MySQL foreign key constraint (FOREIGN KEY) is a s...