DEV Community

Cover image for Hoisting in JavaScript
pharia-le
pharia-le

Posted on

Hoisting in JavaScript

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'

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

const - CANNOT hoist

console.log(name) // // ReferenceError: Cannot access 'name' before initialization
const name = "Pharia"
Enter fullscreen mode Exit fullscreen mode

let - CANNOT hoist

console.log(name) // ReferenceError: Cannot access 'name' before initialization
let name
Enter fullscreen mode Exit fullscreen mode

variable declared with no keyword - CANNOT hoist

console.log(name) // ReferenceError: name is not defined
name = "Pharia"
Enter fullscreen mode Exit fullscreen mode

function - CAN hoist

logName() // => "Pharia"
function logName() {
  return "Pharia"
}
Enter fullscreen mode Exit fullscreen mode

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

Latest comments (1)

Collapse
 
ljcdev profile image
ljc-dev

Clear and concise 😀👌.