The Basics
Todo on the basic types and history of ECMAScript etc. incl. let const and var and functions incl. arrow functions
let and const
These two keywords provide Block Scope variables (and constants) in JavaScript. Before ES6, JavaScript had only two types of scope: Global Scope and Function Scope.
Variables declared with the let
keyword can have Block Scope. However variables declared inside a block can not be accessed from outside the block.
{
var x = 2;
}
// x CAN be used here
{
let y = 2;
}
// y can NOT be used here
Declaring a variable with const
is similar to let
when it comes to Block Scope. JavaScript const
variables must be assigned a value when they are declared. However, The keyword const
is a little misleading. You can't change constant primitive values, but you can change the properties of a constant objects.
// You can create a const object:
const car = {type:"Fiat", model:"500", color:"white"};
// You can change a property:
car.color = "red";
// You can add a property:
car.owner = "Johnson";
// You CAN'T reassign a constant object:
car = {type:"Volvo", model:"EX60", color:"red"}; // ERROR
Arrow functions
Arrow functions are a different way of creating functions in JavaScript. Besides a shorter syntax, they offer advantages when it comes to keeping the scope of the this
keyword.
function callMe(name) {
console.log(name);
}
// Or
const callMe = function(name) {
console.log(name);
}
// Becomes
const callMe = (name) => {
console.log(name);
}