Hoisting in JavaScript
pharia-le
Posted on October 17, 2020
What is Hoisting?
In JavaScript, hoisting is the terminology used to describe how a variable or function can be used before it has been declared.
Example:
console.log(name) // => undefined
var name = 'Pharia'
Conceptually we can imagine that the binding name is hoisted to the top of the code.
var name // declaration is moved to the top
console.log(name) // => undefined because all variables in JS are initially set to undefined
name = 'Pharia' // assignment is not moved
How is this possible?
In JavaScript, before code is executed line by line, the JS Engine will set aside memory space for the variables that you've created in that entire code you've built and all the functions you created as well. This is considered the compilation phase which will be followed by the execution phase.
- for variables, only variables declared with the keyword var can be hoisted
- for functions, a functions name identifier and body are all hoisted
Examples
var - CAN hoist
console.log(name) // undefined
var name = "Pharia"
const - CANNOT hoist
console.log(name) // // ReferenceError: Cannot access 'name' before initialization
const name = "Pharia"
let - CANNOT hoist
console.log(name) // ReferenceError: Cannot access 'name' before initialization
let name
variable declared with no keyword - CANNOT hoist
console.log(name) // ReferenceError: name is not defined
name = "Pharia"
function - CAN hoist
logName() // => "Pharia"
function logName() {
return "Pharia"
}
Conclusion
Although hoisting is possible in Javascript, is it better practice to declare all your functions and variables at the top of their scope to avoid bugs &/or errors.
& Remember... Happy coding, friends! =)
Sources
Posted on October 17, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024
November 30, 2024