18
loading...
This website collects cookies to deliver better user experience
undefined
is given as a placeholder. For functions, the entire code is copied into memory.var x = 2
function double(n) {
return n * n
}
double(x) // 4
var
declaration which has behavioral changes compared to more modern let
and const
keywords.var
, it is initialized with value undefined
during hoisting.var x
x = 10
y = 10
var y
var z = 10
x
, y
, and z
are hoisted with value undefined.let
and const
, the variables are hoisted just like var
but they're not initialized with a default value.let x = 10
const y
y = 20
let z = 30
var
— let
and const
will throw an error because they do not have a value.console.log(x) //undefined
var x = 10
x
using var
. So during hoisting, x
will be given the value undefined
which is logged in the console. Then x
is initialized with value 10.console.log(x) // ReferenceError
let x = 10
let
. Although the variable is hoisted, no value is initialized. The same applies to const
.let
and const
instead of var
. Because if we happen to have a code like above where the variable is declared and initialized after the function, it will throw an error.undefined
as value means there will be no error and you'll be on your own to figure out what went wrong.sayHello() // "Hello"
function sayHello() {
console.log("Hello")
}
sayHello() // ReferenceError
const sayHello = function () {
console.log("Hello")
}
class
declarations are also hoisted. However, unlike function delcarations, values for classes are not initialized hence giving reference error.const p = new Rectangle() //ReferenceError
class Rectangle {
constructor(height, width) {
this.height = height
this.width = width
}
}
let
and const
instead of var