Last active
August 3, 2017 16:44
-
-
Save paulrouget/5262478 to your computer and use it in GitHub Desktop.
Defining JavaScript functions, the ES6 way
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset=utf-8 /> | |
<title>Defining JavaScript functions, the ES6 way</title> | |
<h1>Defining JavaScript functions, the ES6 way</h1> | |
<em>Use Firefox 22 (Firefox Nightly)</em> | |
<script> | |
// old school | |
var square = function(x) { | |
return x * x; | |
} | |
console.log(square(3)); | |
// Expression closures | |
// doc: http://mzl.la/10TNpzc | |
// *Edit:* I've been told that Expression Closures are not part of ES6. Still cool. | |
var square = function(x) x * x; | |
console.log(square(3)); | |
// Arrow functions | |
// spec: http://bit.ly/KN3z1c | |
var square = x => { return x * x; }; | |
console.log(square(3)); | |
// Arrow function + expression closure | |
var square = x => x * x; | |
console.log(square(3)); | |
// Destructuring assignment | |
// doc: http://mzl.la/Xed4Ua | |
var squareAndCube = x => [x*x, x*x*x]; | |
var [s,c] = squareAndCube(3); | |
console.log(s + ", " + c); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@boban984: I was curious about your statements so I went and checked (Chrome v52). Let's see:
I'm not sure why it acts like this, I thought
this
would always bewindow
in an arrow function.You don't need those, because you have classes now. I'm not sure everyone was fond of prototypal inheritance (though personally I liked it).
Moreover, you can always use traditional functional notation when you want the way it behaves. This new fat arrow notation makes Javascript more productive for functional programming (and brings it closer to languages like Haskell, while also having OOP features), and anyone who thinks it's not readable might want to stick to mantaining WordPress blog-sites and using drag-and-drop GUIs with big buttons.