11 + JavaScript features you may never use (summary)

Time:2020-9-26

important

Most of the features described in this article have been suspended (or even not recommended). They are still common in many books, so they are worth learning.

1、 Comma operator

Is the operator used to separate expressions and return the last expression in the chain.


let oo = (1, 2, 3)
console.log(oo) // 3

There are three main expressions 1, 2, and 3. All of these expressions are evaluated, and the last one is assigned to OO.

We see this in the for loop:


for(let i = 0, ii = 1; i< 10; i++, ii--) { ... }

This is useful when writing short lambda functions:


const lb = (a, b, arr) => (arr.push(a*b), a*b)

Here are two statements. The first pushes the multiplication result into array arr, and the second pushes multipliers A and B into the array. The second result is the content returned to the caller.

It is also useful for ternary operators because, like the short lambda syntax, it only accepts expressions rather than statements.

2、 In

In is the keyword used to check whether a property exists in an object. We used it in the for.. in loop, but didn’t realize that in is also a keyword:)
If an attribute exists on the object, in returns true, otherwise it returns false.


const o = {
  prop: 1
}
console.log("prop" in o) // true

See, in can be used independently, not in for.. in.

It checks whether “prop” can be used as an attribute in an O object. It returns true because we defined the “prop” attribute in o.

If we check for undefined properties:


const o = {
  prop: 1
}
console.log("prop1" in o) // false

It returns false because “PROP1” is not defined in o.

3、 Array constructor

Did you know that we can define arrays without using traditional methods?


const arr = [1, 2, 3]

What about?

We can also use array:


const arr = new Array(1, 2, 3)

The arrangement of the parameters passed to the array constructor forms the basis of its index.

1 is the first parameter with index 0; 2 is the second parameter with index 1; 3 is the third parameter with index 2.


arr[0] // 1
arr[1] // 2
arr[2] // 3

So,


const arr = new Array(1, 2, 3)

and


const arr = [1, 2, 3]

It expresses a meaning.

However, there is a problem with using new array(), such as:

var a = new Array(10, 20);
A [0] // returns 10
a. Length // returns 2

But:

var a = new Array(10);
A [0] // returns undefined
a. Length // returns 10

This happens when you only give the array constructor an integer (an integer greater than or equal to 0, otherwise an error will be reported). Why is that?

In fact, the new array constructor is extracting ideas from programming languages where you need to specify memory for arrays so that there is no arrayindexoutofbounds exception.


int *a = (int *) malloc( 10*sizeof(int) ); // ya ol' c
int *a = new int[10]; // c++
int[] a = new int[10]; // java

Yes, it’s actually creating an array of length 10. We don’t have a sizeof function in JavaScript, but toString is enough to prove that.

a. Tostring() // returns ",,,,,,,", which is equivalent to [,,,,,,]
a // [empty × 10]

Therefore, when a parameter is passed to the new array of, it will cause the JS engine to allocate space for the array of passed parameter sizes.

And this is also in the ECMAScript specification:

Look, it’s not contradictory. There are all descriptions in the specifications. We should always read the norms of any language before drawing any conclusions.

4、 Function constructor

Did you know that we can use function constructors to define functions.

You don’t understand, do you? Let me know more. In JavaScript, we define the following functions:

const mul = (a, b) => a * b

//Or
function mul(a, b) {
  return a * b
}

//Or
const mul = function(a, b) {
  return a * b
}

We can also do this to achieve the same function:


const mul = new Function("a", "b", "return a * b")

The parameters passed to the function form the parameters and body of the function. The variable mul becomes the function name.

Moreover, the last parameter will be the body of the function, and the parameter before the last parameter will become the parameter of the function.

In mul. “A” and “B” are the parameters that the function will receive, and “return a * B” is the body of the function. It multiplies “a” and “B” and returns the result.

We use mul (…) Call the function and pass in the parameter:


const mul = new Function("a", "b", "return a * b")

console.log(mul(7, 8)) // 56

According to MDN:

The function constructor creates a new function object. Calling this constructor directly can create functions dynamically, but it will encounter security problems and relatively small performance problems from eval. Unlike Eval, however, the function constructor runs only in the global scope.

5、 Array deconstruction

We can decompose elements in an array by using their index numbers.


const arr = [1, 2, 3]

The indexes of elements 1, 2 and 3 are 0, 1 and 2, respectively


arr[0] // 1

In daily development, we often use object deconstruction

let o = {
  prop: 1
}
o["prop"] // 1

//Deconstruction
const {prop} = o
prop // 1

Therefore, we will use Deconstruction on arrays:


const arr = [1, 2, 3]
const { 0: firstA, 1: secA, 2: thirdA } = arr

firstA // 1
secA // 2
thirdA // 3

So we can use index numbers to extract elements. An index is an attribute that defines the position of an element in an array.


const arr = [1, 2, 3]

amount to:


const arr = {
  0: 1,
  1: 2,
  2: 3,
  length: 3
}

Arrays are also objects, which is why we need to decompose them. However, there is a special syntax for array decomposition


const [first, second, third] = arr

first // 1
second // 2
third // 3

Note: try to avoid knowing the specific position information (what is the start and end index) in the array.

6、 Use the length property to reduce the contents of the array

The length attribute in the array represents the number of elements in the array.


const arr = [1, 2, 3]
arr.length // 3

Reducing the value of the length property will cause the JS engine to reduce the number of array elements to be equal to the value of the length property.


const arr = [1, 2, 3]
arr.length // 3
arr.length = 1
arr // [1]

The length attribute value of arr is changed to 1, so arr reduces the number of elements to equal the length attribute value.

If you increase the length attribute, the JS engine will add elements (undefined elements) so that the number of elements in the array reaches the value of the length attribute.


const arr = [1, 2, 3]
arr.length // 3
arr.length = 1
arr // [1]

arr.length = 5
arr // [1, empty × 4]

There is only one element in arr, and then we increase the length to 5, so we increase the length by four more elements to make the number of elements reach 5.

7、 Arguments

We can use the arguments object to get the parameters passed to the function without defining the arguments variable explicitly in the function:


function myFunc() {
  console.log(arguments[0]) // 34
  console.log(arguments[1]) // 89
}

myFunc(34,89)

The arguments object is array indexed. That is, properties are numbers, so they can be accessed through key references.

The arguments object is instantiated from the arguments class, which has some cool properties.

arguments.callee.name The name of the function that is currently being called.


function myFunc() {
  console.log(arguments.callee.name) // myFunc
}

myFunc(34, 89)

arguments.callee.caller . name is the name of the function that calls the currently executing function.


function myFunc() {
  console.log(arguments.callee.name) // myFunc
  console.log(arguments.callee.caller.name) // myFuncCallee
}

(function myFuncCallee() {
  myFunc(34, 89)
})()

This is particularly useful in variable parameter functions.

8、 Skip ()

Did you know that you can skip brackets () when instantiating objects?

For example:

class D {
  logger() {
    console.log("D")
  }
}

//In general, we do this:
(new D()).logger(); // D

//In fact, we can skip ():
(new D).logger(); // D
//And it works

Even in built-in classes, parentheses are optional:


(new Date).getDay();
(new Date).getMonth();
(new Date).getYear();

9、 Void

Void is a keyword in JS that evaluates statements and returns undefined.

For example:


class D {
  logger() {
    return 89
  }
}

const d = new D

console.log(void d.logger()) // undefined

The logger method should return 89, but the void keyword will invalidate it and return undefined.

I’ve read that before undefined, you might be given another value, which would falsify its semantics. Therefore, using the void operator ensures that you get a real undefined. It is also used for minimization purposes.

10、 Through__ proto__ inherit

A kind of proto_ Is a method to inherit properties from objects in JavaScript__ proto__ Yes Object.prototype , which exposes the [[prototype]] of the access object.

This__ proto__ Set all properties of the object set in its [[prototype]] as the target object.

Let’s take an example:


const l = console.log
const obj = {
  method: function() {
    l("method in obj")
  }
}
const obj2 = {}
obj2.__proto__ = obj
obj2.method() // method in obj

We have two object constants: Obj and ob92. Obj has a method attribute. Obj2 is an empty object constant, that is, it has no properties.

We visited obj 2’s__ proto__ And set it to obj. This will pass Object.prototype All attributes of obj that can be accessed are copied to obj2. That’s why we can call methods on ob92 without getting errors without defining them.

Obj2 inherits the properties of obj, so the method method property will be available in its properties.

Prototypes can be used for objects such as object constants, objects, arrays, functions, dates, regex, numbers, Boolean values, strings.

11、 Unary operator+

The unary + operator converts its operands to numeric types.


+"23" // 23
+{} // NaN
+null // 0
+undefined // NaN
+{ valueOf: () => 67 } // 67
+"nnamdi45" // NaN

This is convenient when we want to quickly convert variables to number.

12、 Unary operator-

Unary operator – converts its operands to type number and negates it.

This operator negates the result of the unary + operator. First, it converts the operand to its number value, and then reverses that value.


-"23" // -23

What happens here is that the string “23” is converted to its numeric type, resulting in 23. The positive number is then converted to its negative form – 23.


-{} // NaN
-null // -0
-undefined // NaN
-{ valueOf: () => 67 } // -67
-"nnamdi45" // NaN

If the result of the conversion to a number is Nan, negation is not applied.

Take negative + 0 to produce – 0, take negative – 0 to produce + 0.


- +0 // -0
- -0 // 0

13、 Exponential operator**

This operator specifies the exponent of a number.

In mathematics, 2 ^ 3 ^ means multiplying 2 by three times:


2 * 2 * 2

We can use the * * operator to do the same thing in JS:


2 ** 3 // 8
9 ** 3 // 729

summary

This article is translated from 11 + JavaScript features you’ve probably never used

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.