Monday, December 5, 2016

JavaScript Evolution ECMAScript 6 - Using let and const

Prior executing code, JavaScript moves var declarations all the way up to the top of the scope. This is known as a hoist. Example:
function loadProfile(usernames) {
  if(usernames.lenght > 3) {
    var loadingMessage = "This will take a while";
  }
}
JavaScript runtime transform to
function loadProfile(usernames) {
  var loadingMessage;
  if(usernames.lenght > 3) {
    loadingMessage = "This will take a while";
  }
}
This explained developer can access the variable outside the block. Example:
function loadProfile(usernames){
  if(usernames.length > 3) {
    var loadingMessage = "This will take a while";
  }
  consolo.log (loadingMessage );
  // Output is unexpected - can be "This will take a while" or undefined.
}
var variable can be accessed in entitled function which might cause unexpected behaviour. One way you can avoid this by introducing a new variable declaration let.

let variables are scoped to the nested block and are Not hoisted. Block is any code section within curly braces like if, else, while, etc. Example:
function loadProfile(usernames) {
  if (usernames.length > 3) {
    let loadingMessage ="This might take a while";
  }
  consolo.log(loadingMessage);
  // Output is ReferencesError: loadingMessage is not defined.
}
Variables declared with let can be reassigned, but cannot be redeclared within the same scope.
let loadingMessage = "Hello";
loadingMessage = "Goodbye"; // Reassigning is allowed.
let loadingMessage = "Hello";
let loadingMessage = "Goodbye";
// Re declaring is not allowed.
// TypeError: Identified 'loadingMessage' has already been declared.
Second type of new variable is const. const keyword created read-only named constant. Example
const MAX_USERS = 3;
Constant cannot be reassigned. Example:
const MAX_USERS = 3;
MAX_USERS = 10; // Error
Constant must be assigned an initial value. Example:
const MAX_USERS = 3; // No error.
const MAX_USERS;
MAX_USERS = 3; // Error
Constant are scoped to the nearest block, same to let.

No comments:

Post a Comment