0

Recently I have come across the concept of Hoisting in which Js arrange all the variables and functions at the top of the program before executing it. But there is a problem I came across a lot like if I execute a variable before declaring it. It causes the error of undefined or you can say it is the initial value of that given by the hoisting to that variable. But after assigning it a value still giving the same error.

console.log(aVar); // undefined
console.log(aLet); // causes ReferenceError: aLet is not defined
var aVar = 1;
let aLet = 2;

Is there something I am missing or Not Know like what is the point of Hoisting here. I want to know what is the correct way to use hoisting without get the undefined value.

  • 1
    I hope you understand that *declaration* is **not** the same as *initialization*. – PM 77-1 Jul 15 '21 at 16:15
  • Does this answer your question? [Is variable initialization also hoisted in JavaScript](https://stackoverflow.com/questions/59814075/is-variable-initialization-also-hoisted-in-javascript) – PM 77-1 Jul 15 '21 at 16:17
  • Does this answer your question? [What's the difference between using "let" and "var"?](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var) – Tushar Shahi Jul 15 '21 at 16:25
  • @PM 77-1 yes like declaration is something like declaring the type of that var and initialize mean provide it a value i guess but my question is how i m going to deal with this undefined error. If i am wrong please correct me to – Yogesh tiwari Jul 15 '21 at 16:37
  • Have you read through the link I provided? – PM 77-1 Jul 15 '21 at 16:51

1 Answers1

0

what is the point of Hoisting here?

To give you an error message instead of silently failing on uninitialised variables.

In general, hoisting lets you declare functions that reference the hoisted variables.

How to deal with undefined error?

Fix the mistake in your code, putting the log statement after the creation of the value you want to log:

let aLet = 2;
console.log(aLet); // 2

Or if you want to get undefined, move the declaration up before the use:

let aLet; // or: let aLet = undefined;
console.log(aLet); // undefined
aLet = 2;
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • so with mean my understanding is completely wrong i was thinking that hoisting is there to rearrange the code and put off some load from declaring it on the top of code . But now i am clear it a type of error help us to look that the positioning of our declaration is wrong. Thank you so much – Yogesh tiwari Jul 15 '21 at 16:41