21
loading...
This website collects cookies to deliver better user experience
counter
variable and set its value to 1. However we are trying to console.log
it before its declaration.console.log(counter); // undefined
var counter = 1;
undefined
. This is because JavaScript only hoists declarations
. undefined
. Therefore, the code looks something like this in the execution phase.var counter;
console.log(counter); // undefined
counter = 1;
let
or const
keywords, JavaScript hoists the declarations to the top but it will not be initialized
.console.log(counter);
let counter = 1;
counter
before initializing it, we will get ReferenceErrorReferenceError: Cannot access 'counter' before initialization
const
keyword.let x = 5, y = 10;
let result = add(x,y);
console.log(result); // 15
function add(a, b){
return a + b;
}
add()
function before defining it.function add(a, b){
return a + b;
}
let x = 5, y = 10;
let result = add(x,y);
console.log(result); // 15
add
from a regular function to an anonymous function.let x = 5, y = 10;
let result = add(x,y);
console.log(result); // 15
var add = function(x,y) {
return a + b;
}
add
variable it initializes it as undefined
. Therefore, we get an error like thisTypeError: add is not a function
let
instead of var
.let x = 5, y = 10;
let result = add(x,y);
console.log(result); // 15
let add = function(x,y) {
return a + b;
}
add
but it will not be initialized.Uncaught ReferenceError: greet is not defined
let
than var
.