Research Hoisting - mikehov/Dating-app GitHub Wiki
Hoisting Research
Mike Hovenier | Tech-4
What is Hoisting
In JavaScript a variable can be declared after it has been used. So a variable can be used before it has been declared. But if it's not defined yet, it will not work. So basically your declarations will almost always be read first, but if your call isn't defined yet, it will not work. This method is called hoisting.
Declareration: let nameDeclareation; Definition: name = 'I'm defined!' Calling: console.log(nameDeclareation);
Even if you combine them to one rule of code, the declaration will be red but the definition not yet. So if you change the value of your variable, for example, it will have the value of what happened before the call, not after the call. Functions for example will be hoisted to the top, so you can call a function before you define it. But this does not work will all functions, this doesn't work with an anonymous function. There is a difference between an anonymous function and a named function. This is function that doesn't have a name, that's what they call an anonymous function, so, for example, an anonymous function:
var anonymousFunction = function() {
var a = 10;
return a;
}
console.log(anonymousFunction()); // 10
This code above will work, but let's say you put the console.log(anonymousFunction());
above the anonymous function this will not work and you will get an error. For a named function, this will still work.
function namedFunction() {
var b = 20;
return b;
}
console.log(nameFunction()); // 20
A good structure is important to make your code accessible and reusable, also it can make your code slower if things aren't at the right place set. So in conclusion, the best way to structure your code is to set the declarations at the top of your page or above your call. Definitions also need to be at the top of your page in one rule with your declarations. If you can't do so, put your definitions at least above your call.
How can I use Hoisting in my project?
For my project, I used hoisting to define a structure, put the declarations at the top of the page, and the definitions above their calls.
I need to keep in mind if I want to use an anonymous function or a named function. Named functions are more global, but anonymous function creates more structure. So for my project, I will try to be as structured as possible, but its oki for some elements to be global, so I can use them everywhere I want to.
Source
freeCodeCamp.org. (2017, February 16). Hoisting - Beau teaches JavaScript [Video file]. In YouTube. Retrieved from https://www.youtube.com/watch?v=C1PZh_ea-7I
mmtuts. (2018, June 4). 18: Hoisting in JavaScript Explained | What is Hoisting in JavaScript | JavaScript Tutorial [Video file]. YouTube. Retrieved from https://www.youtube.com/watch?v=ppMlvGMT2qE
w3schools. (n.d.). JavaScript Hoisting. Retrieved May 28, 2020, from https://www.w3schools.com/js/js_hoisting.asp