Hoisting and Scope
We need to talk about one of the more...interesting parts of JavaScript.It has to do with scope...so, let's take a look at how that works with functions.
Scope
- Variable availability
var,letandconst- Also functions
This is going to require a good understanding of how variables work, so if you want a great, fun explanation, make sure you watch this video in my course called JavaScript as a Second Language.
Most of the time Scope refers to where a variable is available once it's been declared and I'm talking about the how variable declarations can be done with var, let and const. Watch the video from JavaScript as a Second language, but basically...never use var.
As we'll see soon, functions also have scope.
Var Global Scope
var medicine;
function doExperiment() {
medicine = "cough syrup";
console.log(medicine); // cough syrup
}
Although I said that you shouldn't be using var, you're probably going to run into some code that uses it. Also, if you don't use Let or Const, this is the way JavaScript will declare variables by default.
Var Function Scope
function doExperiment() {
var medicine = "cough syrup";
console.log(medicine); // cough syrup
}
Variables declared with the var keyword will also have function scope if they are declared inside a function.
Block Scope
let medicine = "aspirin"
function doExperiment() {
let medicine = "cough syrup";
if (medicine != 'aspirin') {
const medicine = 'not aspirin'
console.log(medicine) // not aspirin
}
console.log(medicine); // cough syrup
}
doExperiment();
console.log(medicine); // aspirin
Variables declared with the let or const keyword have block scope, so their value holds within the curly braces. That's both inside functions and also inside if, switch, or and while statements.
not aspirin
cough syrup
aspirin
Hoisting
var temp = 86
tempC()
console.log(temp) // 86
function tempC() {
var temp;
console.log(temp) // undefined
var temp = 50
temp = (temp - 32) / 1.8
console.log(temp) // 10
}
JavaScript is a compiled language, so there's an extra step that happens when you run your code. It gets analyzed and rewritten by a compiler. One of the byproducts of that is called hoisting.
Variable and function declarations are moved to the top of their scope.
This is something you have to see to believe, so lets go to codespaces and give it a try.
Hoisting and Scope are two things you need to be aware of, specially if you're working on some legacy code.