Deep understanding of the arrow functions in JavaScript basics

Source: Internet
Author: User

From the beginning, the arrows are part of the JavaScript, and in the first JavaScript it is recommended that you wrap the inline script code in an HTML annotation, which prevents browsers that do not support JavaScript from incorrectly dropping your code into plaintext. You may have written the following code:

<script language= "JavaScript" >
<!--
  Document.bgcolor = "Brown";//Red
//-->
</ script>
 
<script language= "JavaScript" >
<!--
  Document.bgcolor = "Brown";//Red
//-->
</script>

The old browser will see two unsupported tags and a comment, and only a new browser that supports JavaScript will parse it into JavaScript code.

To support this quirky feature, the browser's JavaScript engine takes the <!--as the start of a single-line annotation, which is not a joke, it has always been part of the language and is still available, not just in the first line of the <script> tag, but in Any part of the JavaScript code is available, and it can even be used in Node.

Coincidentally, this style of annotation was standardized for the first time in ES6. But that's not the arrow we're going to talk about.

--> also represents a single-line annotation, which differs from HTML in that the,--> part of the HTML is the annotation content, whereas in JavaScript the line after--> is the annotation.

It is only when--> appears at the beginning of a line that the arrow is a comment, because in other cases,--> is an operator (goes to).

function countdown (n) {while
 (n-->0)//"N Goes to Zero"
  alert (n);
 Blastoff ();
}
 
function countdown (n) {while
 (n-->0)//"N Goes to Zero"
  alert (n);
 Blastoff ();
}

The code above is true to run. The loop runs until N is 0, which is not a new feature of ES6, but it is highly misleading with the familiar features. Can you figure out how the code works? You can find a solution on the Stack Overflow.

And of course there's an arrow, which is less than or equal to the operator <=, and maybe you can still find where to use the arrow, but we still stop and look at an arrow we've never seen before:

    • <!--single-line Comment
    • --> goes to operator
    • <= is less than or equal to operator
    • =>???

So what does,=> mean? This is the topic that this article will discuss.

First, let's talk about functions.
the ubiquitous function expression

One interesting feature of JavaScript is that anytime you need a function, you can easily create them.

For example, to bind a point to a button to hit an event:

$ ("#confetti-btn"). Click (
 
$ ("#confetti-btn"). Click (

JQuery's. Click () method requires a function as a parameter, we can easily create a function in place:

$ ("#confetti-btn"). Click (Function (event) {
 playtrumpet ();
 Fireconfetticannon ();
});

 
$ ("#confetti-btn"). Click (Function (event) {
 playtrumpet ();
 Fireconfetticannon ();
});

Now it's natural for us to write code like this. But until JavaScript is popular, this style of code still looks strange because it doesn't have that feature in other languages. In the 1958, Lisp had function expressions, also called Lambda functions, that were not in C + +, Python, C #, and Java for years.

Now all four languages have lambda expressions, and a lambda expression is generally built into the newly emerging language. JavaScript also supports this feature today, thanks to the developers of libraries that are heavily dependent on lambda expressions, which drives this feature to be widely accepted.

JavaScript syntax is slightly verbose compared to several other languages:

A very simple function in six languages.
function (a) {return a > 0;}/JS
[] (int a) {return a > 0;}//C + +
(lambda (a) (> a 0));;  Lisp
Lambda a:a > 0 # Python
a => a > 0//C #
a-> a > 0//Java
 
//a very simple function In six languages.
function (a) {return a > 0;}/JS
[] (int a) {return a > 0;}//C + +
(lambda (a) (> a 0));; Lisp
Lambda a:a > 0 # Python
a => a > 0//C #
a-> a > 0//Java

Arrow function

ES6 introduces a new syntax for writing functions:

ES5
var selected = Alljobs.filter (function (Job) {return
 job.isselected ();
});

ES6
var selected = alljobs.filter (Job => job.isselected ());

 
ES5
var selected = Alljobs.filter (function (Job) {return
 job.isselected ();
});
 
ES6
var selected = alljobs.filter (Job => job.isselected ());

When you need a function with only one parameter, the syntax of the arrow function can be simplified to Identifier => Expression, the function and return keyword are omitted directly, and the parentheses and the trailing semicolon are omitted.

To write a function that has multiple (or no parameters, or Rest and parameter defaults, or destructor parameters), you need to enclose the arguments in parentheses:

ES5
var total = values.reduce (function (A, b) {return
 a + b;
}, 0);

ES6
var total = Values.reduce ((A, B) => A + B, 0);
 
ES5
var total = values.reduce (function (A, b) {return
 a + b;
}, 0);
 
ES6
var total = Values.reduce ((A, B) => A + B, 0);

The arrow functions can also be used perfectly with some tool libraries, such as underscore.js and immutable, in fact, all of the examples in immutable documentation are written using ES6, many of which have been used to the arrow functions.

function body In addition to using an expression, the arrow function can also contain a block of statements, recall the previous example we mentioned:

ES5
$ ("#confetti-btn"). Click (Function (event) {
 playtrumpet ();
 Fireconfetticannon ();
});
 
ES5
$ ("#confetti-btn"). Click (Function (event) {
 playtrumpet ();
 Fireconfetticannon ();
});

Here's how to use the arrow function:

ES6
$ ("#confetti-btn"). Click (Event => {
 playtrumpet ();
 Fireconfetticannon ();
});
 
ES6
$ ("#confetti-btn"). Click (Event => {
 playtrumpet ();
 Fireconfetticannon ();
});

It is important to note that the arrow function that uses the statement block does not automatically return a value, and you must explicitly return a value using returns.

There is also a caveat that when you use the arrow function to return an object, always enclose the returned object with parentheses:

Create a new empty object for each puppy to play with
var chewtoys = puppies.map (puppy => {});  bug!
var chewtoys = puppies.map (Puppy => ({})); OK

 
//Create a new empty object for each puppy to play with
var chewtoys = puppies.map (puppy => {});  bug!
var chewtoys = puppies.map (Puppy => ({})); Ok

Because the empty object {} looks exactly the same as the empty statement block {}, ES6 always treats {immediately after => as the beginning of the statement block, not the beginning of an object, then puppy => {} is resolved to an arrow function with no function body, and the return value is undefined 。

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.