aweber-banner

Advance Javascript

What will be output:

const object = {
  message: 'Hello, World!',

  getMessage() {
    const message = 'Hello, Earth!';
    return this.message;
  }
};

console.log(object.getMessage());


Output:


'Hello, World!'


What will be the output of the code below and why?

console.log(a);
var a="Hello";
console.log(b);
let b=10;


The first console will give undefined and another one will give Reference Error: Cannot access ‘b’ before initialisation. The reason behind this is how JavaScript executes the code. There are two phases of execution:creation phase and execution phase. In creation phase JavaScript allocates memory to its variables and functions and for variables declared with var, JavaScript initialises them with undefined and that’s why when we log “a” before its initialisation, its value is undefined. In case of let and const declared variables, they are initialised at a different memory location and are not accessible to us before their initialisation, this is called “temporal dead zone”. And that’s why JavaScript gives us a reference error in this case.