Useful Javascript ES6 nuggets:
Started learning ES6 from freecodecamp, some useful points I Summarized:
:> Global scope of var vs local scope of let:
var printNumTwo;
for (var i = 0; i < 3; i++) {
if (i === 2) {
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
Here, printNumTwo() prints 3 and not 2. This is because the value assigned to i was updated and the printNumTwo() returns the global i and not the value i had when the function was created in the for loop. The let keyword does not follow this behavior:
let printNumTwo;
for (let i = 0; i < 3; i++) {
if (i === 2) {
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
console.log(i);
Here the console will display the value 2, and an error that i is not defined, because let's scope is limited to the block, function or statement in which you declare it.
*I noticed that we need to change javascript to strict mode by writing "use strict" at the beginning of the code for the solution of 'let' keyword to work.
:> Const declaration alone doesn't really protect your data from mutation, like adding/changing elements or properties in arrays or objects respectively. To ensure your data doesn't change, JavaScript provides a freeze function to prevent data mutation. Syntax: Object.freeze(arr)
:> Syntax of inline function without name:
const myFunc = function(argument) {
const myVar = "value";
return myVar;
}
OR
const myFunc = (argument) => {
const myVar = "value";
return myVar;
}
:> Default parameters in function kick in when the argument is not specified (it is undefined). Ex:
const greeting = (name = "Anonymous") => "Hello " + name;
console.log(greeting("John"));
console.log(greeting());
:> Rest parameter (...args) helps create functions that take a variable number of arguments, eg:
function howMany(...args) {
return "You have passed " + args.length + " arguments.";
}
console.log(howMany(0, 1, 2));
console.log(howMany("string", null, [1, 2, 3], { }));
:> Spread operator allows us to expand arrays and other expressions, eg:
const arr = [6, 89, 3, 45];
const maximus = Math.max(...arr);
*can also use Math.max.apply(null,arr)
:> Spread operator only works in-place, like in an argument to a function or in an array literal, i.e. the following code will not work:
const spreaded = ...arr; // use [...arr]
:> Equivalent for
const name = user.name;
const age = user.age;
is
const { name, age } = user;
OR
const { name: userName, age: userAge } = user;
*new variable names are userName and userAge
Top comments (0)