DEV Community

Hoist Your Vars! (Variable Hoisting in JavaScript)

Emmy | Pixi on February 20, 2020

At its core, hoisting is an "order of operations" issue. JavaScript code goes through two phases: compilation and execution. Declarations (var, ...
Collapse
 
tunaxor profile image
Angel Daniel Munoz Gonzalez • Edited

I like to use this in try/catch statements as well as some if cases

some times you just want to go const all the way but when you meet these cases using let doesn't feel attractive and in the end, you still need to declare the let variable.
Example:

let result;
try {
  result = "abc" // await getResult();
} catch (err) {
  result = "catch"
}
console.log(result)
// or return result
try {
  var result = "abc" // await getResult()
  // throw new Error('I failed you u.u')
} catch (err) {
  result = "catch"
}
console.log(result)

As with anything in code, as long as you and your team agree to do certain things it's okay. If you don't feel is right or your team doesn't want to go that road you can keep it for yourself

Collapse
 
moyarich profile image
Moya Richards

I am curious, why is your variable being mutated in the catch block? that block is for errors

Collapse
 
beardedhen profile image
Ryan Schumacher

A good example of when you might want to do this is if it’s a known exception and you are going to hand wave it away.

(async () => {
let result
try {
  // catch network issues
  const response = await fetch('https://example.com')
  // catch non-json data
  const data = await response.json()
  // catch inaccessible object
  result = data.messages
} catch(e) {
  result = { messages: [] }
}
})().then().catch()
Collapse
 
tunaxor profile image
Angel Daniel Munoz Gonzalez

the times I need to do this is to show a default for something
or just ensure there is a valid value returned from the function, most of the time this is used on places where failure is not critical or it's a "top level" UI element function call

I'd say it's kind of fail behind scenes keep the good face up

Collapse
 
mitri45 profile image
Dmitrii Bludov

Thanks for Hoist explanation, but as a newbie I'm a little confused about your statement of "NEVER use var".
Since now, I thought that main differences between var and let/const lay in the scope field and they visibility in current execution context.
What havoc exactly var statement could wreak? In case of hoisting - is it better not to avoid var, but to avoid havoc in code by assuming that JS is single thread execution scripting language?

And another question that I have after reading - the words "compilation phase". Do we really have compilation process in scripting language?

Collapse
 
moyarich profile image
Moya Richards

Your questions are addressing too many things. You are talking about scope, execution context, thread, compilation. These are things that you must understand fully. I think that you would benefit from watching this video. please pay for the full course, it will greatly improve your JavaScript skills. Tony teaches about all these things.

youtube.com/watch?v=Bv_5Zv5c-Ts

Collapse
 
nerdharder615 profile image
Matt

While it is important to understand hoisting in JavaScript, it is also a bad practice to use it in general. I suggest that you treat JavaScript just like any other programming language and don't use hoisting.

I have a template that I follow for any script that write:
// Declare variables:

// Declare functions:

// Start of coding:

Having those three sections makes it much easier for me to keep track of what is in my script.

Collapse
 
thecodepixi profile image
Emmy | Pixi

That is excellent advice and very true!

Collapse
 
moyarich profile image
Moya Richards

so many people are confused about what hoisting is. Let me start off by bursting the bubble with one statement

All declarations are hoisted (var, let, const, function, class)

Collapse
 
thecodepixi profile image
Emmy | Pixi

You're absolutely right and that's a point I didn't make clearly enough in the article. Might merit an edit.

Collapse
 
al_daro profile image
Alex Daro

Super helpful! No more vars for me :P

Collapse
 
yechielk profile image
Yechiel Kalmenson

Wow! Great summary and explanation of a complex and esoteric topic!