Closed Brymon closed 2 years ago
https://www.w3schools.com/js/js_hoisting.asp
Hoisting is JavaScript's default behaviour of moving var
declarations to the top of the current scope when your code is run. What this means is that whatever line your write a var
declaration on e.g. var x;
, when your code is run it will automatically be lifted and read as if it were written on the top lines of your current scope (to the top of the current script or the current function).
This means that you can use var
's higher up in the code before the line you've declared them on. So this example:
x = "hello";
console.log(x) // logs 'hello'
var x; // declaring `x` which is hoisted as if it were written at the top on compilation
Is read by the computer like this:
var x; // declaring `x` which has been hoisted to the top line on compilation
x = "hello";
console.log(x) // logs 'hello'
var
declarations not let
or const
declarations.x
is logged it is undefined
and doesn't have the value of 'hello'
yet.
var x; // this line is declaring `x` which happens to already be at the top
console.log(x) // logs 'undefined'
x = "hello";
Other words to define:
var
,const
,let
var x;
<- this consists of saying what declaration you are using var
/const
/let
and then giving that variable a name, in this case you are calling your variable x
. Once you have done this the variable x has been declared. Declarations are different to initialisations e.g. var x = 1;
, see separate definition for intialisations. var x = 1;
.@Brymon - if you are happy with the definition that has been added please close this issue 😊
Thanks for adding this one @Brymon 👍