Sitemap
codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

JavaScript — Learn & Understand Arrow Functions

6 min readOct 12, 2017

--

Preface

function add2(num) {
return num + 2;
}
add2(2);
// 4
const add2 = num => num + 2add2(2);
// 4

Syntax

(parameters) => { statements }
() => { statements }** is equivalent to **function example(){
// do something...
}
parameter => { statements }** is equivalent to **function example(parameter){
// do something...
}
parameter => expression** is equivalent to **function example(parameter){
return expression;
}

Example Arrow Function

const add2 = num => num + 2
add2(6);
// 8
add2(10);
// 12

No binding of this

function Counter() {
this.num = 0;
}
var a = new Counter();
console.log(a.num)
// 0
function Counter() {
this.num = 0;
this.timer = setInterval(function add() {
this.num++;
console.log(this.num);
}, 1000);
}
var b = new Counter();
// NaN
// NaN
// NaN
// ...
clearInterval(b.timer);
function Counter() {
this.num = 0;
this.timer = setInterval(function add() {
console.log(this);
}, 1000);
}
var c = new Counter();
// Window {}..
// Window {}..
// Window {}..
// ...
clearInterval(c.timer);
function Counter() {
this.num = 0;
this.timer = setInterval(() => {
this.num++;
console.log(this.num);
}, 1000);
}
var d = new Counter();
// 1
// 2
// 3
// ...
clearInterval(d.timer);
function Counter() {
var that = this;
this.timer = setInterval(() => {
console.log(this === that);
}, 1000);
}
var e = new Counter();
// true
// true
// ...
clearInterval(e.timer);

Key Takeaways

Closing Notes:

If this post was helpful, please click the clap 👏button below a few times to show your support! ⬇⬇

--

--

codeburst
codeburst

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Brandon Morelli
Brandon Morelli

Written by Brandon Morelli

Creator of @codeburstio — Frequently posting web development tutorials & articles. Follow me on Twitter too: @BrandonMorelli

Responses (5)