Basics of ES6
17 Dec 2016Variables
- Try to use
let
instead ofvar
to avoid issues like “undefined” variables. - When you use
var
, JS does hoisting - moves all the variable declaration to the top. - So if there is any
var
which is declared somewhere in the code and you try to access it before its declaration, it will be set to undefined. - For the same case, if you use
let
, its scope is defined within that context. Referencinglet
variables elsewhere will result in error.
let
variables cannot be redeclaredconst
are read-only constants & must be assigned an initial value.
Destructuring
- Allows you to assign variables in bulk or interchange values.
Function Defaults
-
You can use default values for parameters inside the function signature which can prevent from putting in null checks.
-
The default parameters would only be set when those parameters are not at all sent.
Options Object
- Useful when passing in an object parameter.
- options parameter can be initialized to empty object within the function definition.
Using Named parameters
- Can be used as a replacement for
options
object.
Arguments object
- Built in array-like object used for parameters.
- Used when there are varying number of parameters which can be passed on to the function.
Rest parameters
- Denoted by 3 dots and signifies as a pure arguments array.
- Wont break the function if a new parameter is explicitly added to the function signature.
- Must always be the last parameter.
- If the value is not sent, it will be an empty array.
Spread Operator
- Split an array arguments into individual elements.
- Syntax is same as Rest parameter except the context where its applied.
Template literals
- Useful for concatinating strings.
Class
- Earlier we had to create objects and use prototypes to define certain methods.
- Now we can define classes and create constructors within it.
Converting functions to objects
- For encapsulation, reusability and testability.
- Can be used in combination with arrow function.
- Arrow function helps a great deal in tackling with scoping issues in callback.
Iterators
For of
- Used to loop over values and not keys like for in
Arrow functions
- Converting a simple function to arrow functions
See the Pen vKdOzg by Ranjith (@ranjithnair) on CodePen.