This article is basic, an article to fill in the gaps. Let’s test the waters for gold

Cut the gossip and get to work!

== Note == This article is run on a browser console.


basis

Basic operations such as addition, subtraction, multiplication and division

Here are some basic operators.

+(addition), – (subtraction), * (multiplication), / (division), % (modular), ++ (increment), — (subtraction), ** (power).

1+2 / / 3
2 - 1 / / 1
1 * 3 / / 3
4 / 2 / / 2
5 % 2 / / 1

/ / the other
0 / 0 // NaN
1 / 0 // Infinity
1 / -0 // -Infinity
-1 / 0 // -Infinity
-1 / -0 // Infinity

// Increment and decrement require the use of variables
let a = 1;
a++ / / 1
a / / 2
++a / / 3
a / / 3
let b = 1;
b-- / / 1
b / / 0
--b / / 1
b / / 1

/ / power operation
2六四屠杀3 / / 8;
Copy the code

When you read this, you might think, wow, you’re talking about real water. Don’t worry, after reading this article you will be more firm in your ideas (ha ha, just kidding, slowly from shallow to deep, this meaning you understand 🤓)

  • aboutMath

Math has constants and apis for computation, such as. Constants such as Math.ln2 (the natural log of 2), math.ln10 (the natural log of 10), math.pi (the famous PI).

Arithmetic apis such as math.abs (x) (absolute value), math.ceil (x) (rounded up), math.floor (x) (rounded down), Math.h pow (x, y) (power), Math. SQRT (x) (root), Math. Max ([x, y [[,…]]]) (maximum), Math, min ([x, y [[,…]]]) (minimum), etc., and some are cosine, cotangent, I’m not going to do logarithms because they’re not very common.

Math.abs(-1) / / 1
Math.ceil(1.2) / / 2
Math.floor(1.2) / / 1
Math.pow(2.3) / / 8
Math.sqrt(4) / / 2
Math.max(4.2) / / 4
Math.max(-4.2) / / 2
Copy the code

Most of these operations can be done with operators

In addition, when + encounters a string, it will have the function of concatenation.

'hello '+ 'word'; // hello word
Copy the code

It can also be used as a unary operator, which has a type conversion function, as does subtraction

// parseInt and parseFloat
+'1' - +'2' // 1-2 = -1
Copy the code

A few days ago colleagues recommended a set of questions, very interesting, can be jabber here ⇲ to self-test a wave, there is such a question in the middle (and many similar questions) :

What would you like to choose?

The analysis results sum up most of the weird grammar I’ve covered in this quiz. Let’s break it down piece by piece:

-""; / / - > 0
+"1"; / / - > 1
Number(null); / / - > 0
Number([and]);/ / - > 0
// Add them together:
-0 + 1 * 0 - 0; / / - > 0
Copy the code

There are also some tricks involved in type conversion.

For type conversions, it is recommended

  • Relearn JS- what an interesting type conversion (1) ⇲

Syntax sugar (=, +=, -=, *=, /=, %=)

There are also syntaxes that combine the = assignment operator with sugar =, which is used in many programs (almost all of them) to assign values from the right to the left without further explanation.

// => is an equivalent symbol
a += b= > a = a + b
a -= b= > a = a - b
a *= b= > a = a * b
a /= b= > a = a / b
a %= b= > a = a % b
Copy the code

Comparison and relational operators

💎 To compare is to judge equality

Contains ==, ===,! =,! = =

Loose equality and strict equality, loose inequality and strict inequality

Strict judgment is much more type judgment than loose judgment

'6'= =6 //true
1= =true //true
undefined= =null //true

'6'= = =6 //false
1= = =true //false
undefined= = =null //false
Copy the code

💎 a relationship is a comparison of size

Contains >, <, >=, <=, very simple.

1 > 2 //false
1 < 2 //true
1> =1 //true
1< =1 //true
Copy the code

Is feeling intelligence quotient insulted 🤡? Hahaha ~~

Logical operator

Mainly contains && (false), and false, | | (or, is really true, all false take tail),! You can use it as a judgment, or you can use it as a backstop

/ / | | 'and 0 for false value
false || 1 / / 1
false || 0 / / 0
9 || false / / 9

1 && 0 / / 0
0 && 1 / / 0
false && '1' //false
'2' && '3' / / "3"

!0 //true
!null //true
!undefined //true
!true //false! -1 //false
Copy the code

The trinary operator (a? b:c)

This is simple, but the rule is to treat the empty string ” and 0 as false

a = a ? a : b;
Copy the code

Comma operator (,)

The comma operator evaluates each of its operands (left to right) and returns the value of the last operand

var a = 1,b = 2;
a = (1.2.4.9);
a / / 9
a = (3,b = 5.8);
a / / 8
b / / 5
a = (2, b=6);
a / / 6
b / / 6
Copy the code

It’s actually quite common, and you’ve used it to define variables

let a = 1, b = 2, c = 3;
Copy the code

Void operator.

I don’t know much about this, but there are some useful ones.

The void operator evaluates the given expression and returns undefined.

Feel the void used less, the following function is to go to the net some net. A little for the new words strong sorrow feeling

  • Defining an empty connection
<a href="javascript:void(0);">If void() is removed, the entire page is replaced by a single character 0.</a>
Copy the code
  • Execute function immediately

This function, um ,,,, how to say, ah ~~~

function iife() { console.log('foo') }()       // Error because the JS engine recognizes IIFE as a function declaration
void function iife() { console.log('foo') }()  // Normal call
~function iife() { console.log('foo') }()      // A bitwise operator can also be used
(function iife() { console.log('foo') })()     // Or simply use parentheses to represent the whole expression
Copy the code
  • Avoid leaks in arrow functions

Be careful not to leak the return value of doSomething to the caller of the arrow function, which feels a bit silly

button.onclick = () = > void doSomething();
Copy the code

The advanced

Numeric separator (_)

ES2021 introduces the numeric separator _, which provides separation between numeric groups and improves the numeric reading experience

var num =  30 _0000_0000 / / 3 billion
num / / 3000000000
Copy the code

An operator

That’s actually why I’m writing this article, so let’s just review what I’ve written.

= =Pay attention to= =

  • Bitwise operators can only be used for integers
  • Not suitable for large values

Bit operators involve binary operations, simple syntax, great power.

A little bit of a review of binary operations? Hexadecimal conversion reference Number. The prototype. The toString () ⇲

Binary operation

Binary numbers are zero, one machine code numbers. We usually see numbers in decimal. So 143, if we go from low to high, 3,4,1, then 143 is equal to

3 times 10 to the zero plus 4 times 10 to the first plus 1 times 10 to the second

Formula for

3 * 10六四屠杀0 + 4 * 10六四屠杀1 + 1 * 10六四屠杀2 / / 143
Copy the code

Binary 1011 is equal to

1 * 2六四屠杀0 + 1 * 2六四屠杀1 + 0 * 2六四屠杀2 + 1 * 2六四屠杀3 // Represents the decimal number 11
Copy the code

A little too basic, hahaha

(15).toString(2) // Get level 2 "1111"
Copy the code

Binary operation has many operation references – MDN⇲ :

💎&, by bit and (all 1s are 1s) In the bit representation of a and b, 1 is returned if each corresponding bit is 1, otherwise 0 is returned.

15 & 9 / / 9
// 1111&1001 => 1001
Copy the code

💎 |, bitwise or (1 to 1) in a, b a said, each of the corresponding position, as long as there is a 1 is returned 1, otherwise it returns 0.

15 | 9 / / 15
/ / 1111 | 1001 = 1111
Copy the code

💎 ^, by bit or (if the difference is 1) in the bit representation of a and B, 1 is returned if the two bits are different, and 0 is returned if the two bits are identical.

15 ^ 9 // 1111 ^ 1001 = 0110
Copy the code

💎~, the bit of the operand that is not reversed by bit.

~15 / / ~ 00000000... 00001111 = 11111111... = 11110000-16
Copy the code

Note that the bitwise operator “not” inverts all 32 bits, and that the highest bit (the leftmost bit) of the value is 1, indicating a negative number (2-complement notation)

💎<<, left shift moves the binary string of A to the left by b bits and to the right by 0.

15 << 1 // 30 is the same thing as multiplying by 2
// 1111 << 1 = 11110
Copy the code

💎>>, arithmetic right shift moves the binary representation of A b bits to the right, discarding any bits removed.

15 >> 1 // 7 is the same thing as dividing by 2 and rounding down.
// 1111 >> 1 = 111
Copy the code

💎 >>>, the unsigned right shift moves the binary representation of A to the right by b bits, discarding all the bits removed, and filling the left bits with zeros. For non-negative values, the zeroing right shift produces the same result as the signed right shift.

Negative numbers are represented by the complement of positive numbers, and the original code is added to the complement (+1). For example, 1 becomes -1 0000 0001 => 1111 1110 => 11111111 note that 11111111 is -1 if regarded as a signed number (highest bit, 0 +1 + negative), and unsigned is 255

15 >>> 1 // 7 is the same thing as dividing by 2 and rounding down.
// 1111 >>> 1 = 111
Copy the code

Usage scenarios for bitwise operators

  • Judge parity
// Perform the &1 operation, resulting in 1 being odd and 0 being even
5 & 1 / / 1
4 & 1 / / 0
Copy the code
  • Take down the whole
~ ~4.1 / / 4~ ~4.7 / / 4~ ~ -4.5 / / - 4

4.5 >> 0 / / 4
4.8 >> 0 / / 4
-4.1 >> 0 / / - 4
-4.1 << 0 / / - 4
4.8 << 0 / / 4
// >>> Negative numbers cannot be rounded
4.8 >>> 0 / / 4
-4.8 >>> 0 / / 4294967292
Copy the code
  • Exchange of values of type Number
[a,b] = [b,a]
let a = 2, b=3;
a ^= b A :1 b:3
b ^= a A :1 b:2
a ^= bA :3 b:2
Copy the code
  • RGB and hexadecimal color value conversion
/** * Hexadecimal color value to RGB *@param  {String} Hex Hexadecimal color string *@return {String}     RGB color string */
  function hexToRGB(hex) {
    var hexx = hex.replace(The '#'.'0x')
    var r = hexx >> 16
    var g = hexx >> 8 & 0xff
    var b = hexx & 0xff
    return `rgb(${r}.${g}.${b}) `
}

/** * RGB color to hexadecimal color *@param  {String} RGB RGB color string *@return {String}     Hexadecimal color string */
function RGBToHex(rgb) {
    var rgbArr = rgb.split(/[^\d]+/)
    var color = rgbArr[1] < <16 | rgbArr[2] < <8 | rgbArr[3]
    return The '#'+ color.toString(16)
}
hexToRGB('#ff00ff')   / / 'RGB (255,0,255)'
RGBToHex('RGB (0255255).)  // '#00ffff'
Copy the code
  • Take a score of two in quicksort
9 >> 1 / / 4
6 >> 1 / / 3
Copy the code
  • Determine whether the values are equal
// Equal equals 0, no equals non-0
10 ^ 9 / / 3
9 ^ 9 / / 0
Copy the code
  • Checks if an array item is found

Returns truthy for any value other than -1 with the inverse (~) operator. Do it nonoperatively, directly! ~

// Includes is more convenient than this.!!!!! (~arr.indexof(item))// Find is true!!!!! ~0 //true! ~ -1 //true!!!!! ~1 //true
Copy the code

Also note:

supplement

  • Integer accuracy (without the use of decimal points or exponents) is up to 15 bits. The maximum number of digits for decimal accuracy is 17, but floating-point arithmetic is not always 100% accurate.
  • Bit operation directly to the binary bit calculation, bit operation directly processing each bit bit, is a very low-level operation, the advantage is very fast, the disadvantage is very not intuitive, many occasions can not be used.
  • The bit operation only works on integers. If an operand is not an integer, it is automatically converted to an integer before running.
  • Inside JavaScript, values are stored as 64-bit floating-point numbers, but bitwise operations are performed as 32-bit signed integers and the return value is a 32-bit signed integer

Summary: The speed brought by bitwise operators is not visible to the naked eye, but the cost of understanding will increase, == use == sparingly.

The null merge operator (??)

This is in order to improve the | | operator (), some problems mentioned in front of the | | ‘and 0 for false value See the code, the falsy leaves null, and undefined, false

// If all values are true, the first value should be taken
1 || 2 / / 1

0 || 2 / / 2
' ' || 2 / / 2

0 ?? 2 / / 0
' ' ?? 2 / / ""
Copy the code

Optional link operator (? .)

Without it you might need to write:

obj && obj.prop && obj.prop.a
Copy the code

Now we just need to

obj?? .prop?? .aCopy the code

Very sweet. Do a metaphor with you, than mosquito coil incense also sweet 😁

extension

There are also some fancy operators that browsers slowly implement as standards, which are also nice.

Logical empty allocation (?? =)

Of course, you might think that x? Lambda is equal to y is shorthand for the following

x = x ?? y
Copy the code

If x is falsy(null, undefined, false), y is assigned to x. Code check

var a = false ?? 'Assignment successful! ' / / a is false
var a = true ?? 'Assignment successful! ' / / a is true
Copy the code

Why is this, because merge operator? It operates from left to right, which means that if the assignment on the left succeeds (a = false/true), the assignment on the right will not be executed. How can an assignment fail

x ?? So this is equal to y

x ?? (x = y)
Copy the code

Note, only equivalent to, of course, some special cases!! !

  • Left-hand value (x) only when nulllish (null.undefined) will be executed!!
function test(val){ vara= val; a ?? ='Assignment successful! '; return a  }
test() //" Assignment successful!"
test(1) / / 1
test(null) //" Assignment successful!"
test(false) //false
Copy the code

It is estimated that it is designed to assign values to variables that are not assigned (null is also considered unassigned)

Logic or distribution (| | =)

Understand the above?? = it’s understandable, that a | | = b is equal to all

a || (a = b)
Copy the code

Beyond the code demo, I have no FA to say 🙃

function test(val){ var a= val;  a ||= 'Assignment successful! '; return a  }
test() //" Assignment successful!"
test(0) //" Assignment successful!"
test(false) //" Assignment successful!"
test(null) // "Assignment successful!"
test(undefined) //" Assignment successful!"
test(' ') //" Assignment successful!"
Copy the code

Scenario: If a has a default value, save it, if it does not, assign a new value.

Logic and Distribution (&& =)

Understand the above?? Phi is equal to phi, and that makes sense, a and phi is equal to b

a || (a = b)
Copy the code

Beyond the code demo, I have no FA to say 🙃

function test(val){ var a= val;  a &&= 'Assignment successful! '; return a  }
test(1) // "Assignment successful!"
test(0) / / 0
test(false) // false
test() // undefined
test(null) // null
test(' ') / / ""
test(NaN) // NaN
Copy the code

Scenario: Update an existing value

Operator priority

Operator type Individual Operators (descending)
member [].
call / create instance () new
negation/increment ! ~ – + ++ — typeof void delete
multiply/divide * / %
addition/subtraction + –
bitwise shift << >> >>>
relational < <= > >= in instanceof
equality = =! = = = =! = =
bitwise-and &
bitwise-xor ^
bitwise-or
logical-and &&
logical-or
conditional ? :
assignment = += -= *= /= %= <<= >>= >>= &= ^=
comma .

reference

You can see farther if you stand on someone else’s shoulders. Thank you 💖💖💖

  • 🔗 | Expression and operator – MDN
  • 🔗 | Void operator -mdn
  • 🔗 | Understand Javascript’s various operators at once
  • 🔗 | Bit operators in JS clever use
  • 🔗 | There are a few powerful JS operators you’ve never heard of
  • 🔗 | 25 JavaScript Shorthand Tips (Part 2)