This is the fourth day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021

A minor “bug” about value storage in JavaScript. Today we will continue to learn about the magic phenomenon in JavaScript.

JavaScript isn’t perfect, but that doesn’t stop it from running and being widely used in browsers.

Take a look at some of the magic in JavaScript:

The magic of JavaScript fans

Arrow function + expression

| MDN arrow function:

Arrow function expressions have a much cleaner syntax than function expressions and don’t have their own this, arguments, super, or new.target. The arrow function expression is more useful where anonymous functions are needed, and it cannot be used as a constructor.

What is the output of the following code?

((name) = > [ name ])(Oh, my God.) /// [' xiao Tian ']

((name) = > { name })(Oh, my God.) 
Copy the code

According to the first line, the arrow function returns an array of the passed arguments: name. So we assume that the second line should return an object (where the attribute and the value of the attribute are the same, and the abbreviation name is omitted): {name: ‘Xiao Artian’}

What does Chrome Console really return? Check out the answer!

The second line returns undefined because the code inside curly braces ({}) is parsed into a series of statements,

The name in the second line is considered a label, not part of the object literal.

Remember that the simple syntax of params => {object:literal} for returning object literals does not work.

As in the second line above, if you want to return an object, enclose it with () :

// return an object literal expression using a bracketed function body:

params => ({name: Oh, my God.})
Copy the code
((name) = > ({ name }))(Oh, my God.)  /// {name: 'xiao Tian'}
Copy the code

That will do.

The arrow function recurses

const arrRec = (x) = > ( x == 0 ?  1 : x * arrRec(x - 1));

console.log(arrRec(5)); / / 120
Copy the code