Sunday, October 29, 2017

Day 3: Fat arrows, backticks, let and const



I spent my Saturday getting a grip, finally, on the fundamentals of ES6.  JavaScript has been around since 1996, in various forms, with next-number versions every couple of years introducing new features and functionalities. JS was kind of stuck on ES5 (version 5) for a long time, though -- after it was introduced in 2009, the entity in charge of updating the JS standard did not give us ES6 until 2015. Most JS devs learned ES5, and it seems like many if not most of the online academies are even now, in 2017, still teaching the previous version of the language. I've not made a huge point of fact checking this, but the main "learn ES6!" online resources I've looked at, while figuring out the best way to finally learn it myself, are aimed at teaching people who already know JS the new features of ES6.

And now I am finally one of them.  I focused on four ES6 entities:


  • Template literal syntax, which is pretty sweet. Basically, you surround a string with backticks instead of quote marks (single or double both work, but JS convention leaned toward single). Using backticks means not having to escape special characters or use newline breaks for multiline strings. Thus, 
var ironButterfly = 'Innagadadavida, honey\n\don\’\t you know that know that I\’\m lovin you?’;  becomes
var ironButterfly = `Innagadadavida, honey, Don’t you know that I’m lovin you?`


  • Arrow functions, aka the fat arrow => which replaces the 'function' keyword and lexically binds the function's 'this' to the specific block where it appears (designated by two curly braces {}). In ES5, this can mutate whenever you create a closure, which can lead to unforeseen code behavior and much cursing. ES6 brings us the fat arrow function syntax -- => -- where ‘this’ will always retain function context. SO much typing saved! SO much callback hell avoided! No moar need for ‘that=this’ or .bind(this) or other such tedious yet necessary statements!  We go from:



var _this = this$('.btn').click(function(event){  _this.sendData()})
To the more economical -- and lexically stable --

$('.btn').click((event) =>{
 this.sendData()})
  • Const and Let: Like var, these are used for variable assignment, but let and const both come bearing functional semantic significance. They both are lexically binding, meaning that they are bound to the context of the code block where they are declared. (And, conversely, are thus not subject to variable hoisting). Const creates a read-only reference to a value, meaning that a const cannot be assigned to a new value. Let is re-assignable.
That, friends, is the quick run-down. I wrote a tutorial for The New Stack, complete with code samples, and will link to it as soon as it is up.

No comments:

Post a Comment