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)