The term hoistingin JavaScript refers to the emmediate assignment of value to a vavriable at the point of mention.
sound confusing?

Take for instance we changed our code in the app.js to look something like this:


		var a = "I was hoisted";

		function b() {
			console.log('you just called function b')

Lets try this by writing some code in the file app.js. save and rerun the code in your browser window.

Copy and paste the folling code into app.js:

What this does:

console.log() will print undefined in the console; this is for console.log(a).

It will print 'you just called function b', for b()

So why do we get undefined for console.log(a) ?

Execution context is created in two phases, in creation phase we get the global oject which is set up within the memory, we then have 'this' which is set up in the memory.

There is also an outer execution environment that is created as the parser runs through your code to set up what you have written in order to translate it.

The parser sees where you have your variable and functions and it therefore sets up a memory space for all of that. That all set up process in the creation phase is what has been called hoisting. 😁

All it means is that before the your code is executed line by line, the engine has already gone a head and created memory space for all the variables and functions.

All the variables and functions now exist in the memory.
When the code finally begines to execute line by line it can access them, however, it still doesnt know what the value of the variable is until it gets to your actual assignment, that is why it uses the placeholder undefined. all variables in JavaScript are initially set to this value, undefined

so when talking about hoisting just imagine this scenario.

in JavaScript It is easy to confuse the term undefined with the error log not defined

undefined means that the variable in not set up yet, the JavaScript Engine assigns all the variables this value before they have been asigned a value.

not defined reffers to amissing variable. For example, if you removed the line var a = "we learn hoisting"; save and run the code, you see the error in the console.

Back to Topics πŸ‘ˆπŸ»

Next Lesson: Comming upClick hereπŸ‘‰πŸ½

Take one minute to let us know what you want us to cover here Here .

Connect on twitter Twitter. share