ES6
let
, var
, const
let
, var
, const
Variables declared using the var
keyword are scoped to the function in which they are created, or if created outside of any function, to the global object.
let
and const
are block scoped, ie. they are only accessible within the nearest set of curly braces (function, if-else block, or for-loop).
Function constructors
Example of each:
For simple constructors, they look pretty similar.
The main difference in the constructor comes when using inheritance. If we want to create a Student
class that subclasses Person
and add a studentId
field, this is what we have to do in addition to the above.
It's much more verbose to use inheritance in ES5 and the ES6 version is easier to understand and remember.
References
Arrow functions
Simplify the syntax needed to create functions, without a need for the function
keyword.
The this
within arrow functions is also bound to the enclosing scope which is different compared to regular functions where the this
is determined by the object calling it. Lexically-scoped this
is useful when invoking callbacks especially in React components.
Advantage of using the arrow syntax for methods in a constructor
The value of this
gets set at the time of the function creation and can't change after that. So, when the constructor is used to create a new object, this
will always refer to that object.
Example: we have a Person
constructor that takes a first name as an argument has two methods to console.log
that name, one as a regular function and one as an arrow function:
this
can be changed for a normal function, but the context always stays the same for an arrow function.
Even if you are passing around your arrow function to different parts of your application, you wouldn't have to worry about the context changing.
References
Destructuring
Extract values of Objects or Arrays and place them into distinct variables.
Array destructuring
Object destructuring
References
Very useful when coding in a functional paradigm as we can easily create copies of arrays or objects without resorting to Object.create
, slice
, or a library function. This language feature is used often in Redux and rx.js projects.
ES6's rest syntax offers a shorthand for including an arbitrary number of arguments to be passed to a function. It is like an inverse of the spread syntax, taking data and stuffing it into an array rather than unpacking an array of data, and it works in function arguments, as well as in array and object destructuring assignments.
References
Template literals
Last updated