2

What I know : If variables are initialized without declaration,then it is automatically initialized.

Hoisting in JavaScript only raises the declaration to the top and not the initialization.

What I tried on Google Chrome Console:

console.log(num);

Result:

Uncaught ReferenceError: num is not defined
    at <anonymous>:1:13

Cause: Since hum isn't declared or initialized

num = 9; console.log(num);

Result: 9

Cause: Due to initialization, it is also declared and num gets its value ie 9

console.log(hum); hum = 8;

Result:

VM519:1 Uncaught ReferenceError: hum is not defined
    at <anonymous>:1:13

What I am not able to understand:

since I have initialized hum to 8,it will also get declared and by hoisting in JS,the declaration of hum is hoisted and I should be getting undifined as result. Why isn't it happening?

Savannah Madison
  • 575
  • 3
  • 8
  • 17

2 Answers2

1

JavaScript variables start with the value of undefined if they are not given a value when they are declared (or initialized) using var, let, or const.

console.log(hum); hum = 8; console.log(typeOf(hum));

this will give you undefined as its intialized but not declared.

console.log(hum); var hum = 8; will be hoisted.

For more info,

https://medium.com/coding-at-dawn/how-to-check-for-undefined-in-javascript-bcedd62c8ad

Carrot
  • 376
  • 5
  • 9
-1
line 1: console.log(num);
line 2: num = 8;  

Even if the first line starts to execute num will allocate undefined (keyword) in memory.

when it completes the first line of execution it prints undefined from memory.

after line two completes execution undefined is replaced with 8 in memory.

This process is knows as hoisting.

In this scenario,


line 1: num = 8; 
line 2: console.log(num);

Even if the first line starts to execute num will allocate undefined in memory.

when it completes the first line of execution it stores 8 in memory.

after line two completes execution it prints 8 in console.

Sen Kanna
  • 9
  • 5
  • Hi, try to clarify your answer with the help of formatting and examples – Greedo Oct 18 '22 at 15:29
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Greedo Oct 18 '22 at 15:29