DEV Community

Kaziu
Kaziu

Posted on

Hoisting in javascript. Magic of declare order

What is hoisting ??

a variable can be used before it has been declared because it stores in memory

for example

πŸ’Ž function

b();

function b(){
  console.log('foo');
}

// "foo" 
// βœ… thanks to hoisting, function has stored in memory before declaring
Enter fullscreen mode Exit fullscreen mode

β–Ό But arrow function isn't like that

arrFn();

const arrFn = () => {
  console.log('arrow!!');
}

// πŸ”₯ Uncaught ReferenceError: Cannot access 'arrFn' before initialization
Enter fullscreen mode Exit fullscreen mode

πŸ’Ž variable

console.log(b)
var b  = 10;

// "undefined"
// βœ… default initialization of the var is undefined.
// ❗ initial value = undefined
Enter fullscreen mode Exit fullscreen mode

the case of const and let

console.log(NAME) // πŸ”₯ Throws ReferenceError exception as the variable value is uninitialized
const NAME = 'kaziu'
Enter fullscreen mode Exit fullscreen mode
console.log(count) // πŸ”₯ Throws ReferenceError exception as the variable value is uninitialized
let count = 2
Enter fullscreen mode Exit fullscreen mode

Top comments (0)