kaede
: hey nagisa, should we tell him?๐ค
nagisa
: hmmm, about what?๐
kaede
: About real practice
๐, how should we really learn with just theoris?
nagisa
: ahaaa๐, Yep, I'm agree, do you want me to tell him?
kaede
: No, I'll tell him my-self. Sensei
, when do we start the practical tests? I think with just theories we can't be real assassins๐
Korosensei
: You are right kaede
, We will parcrice today alot...๐ specially about some intersting questions which you are faceing at interviews
๐.
but, before that, you should know some crucial conepts, Now everyone lets begin, are you ready???
Class
: Yessssss
korosensei
: So everyone, put your guns down and listen very well. Anyne knows exact definition of Hoisting
?
nagisa
: is'nt it about:
Hoisting is JavaScript's default behavior of
moving all declarations to the top of the current scope
(to the top of the current script or the current function).W3schools e.g. `Variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behavior is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code.Mozilla
var x = 10;
//----this 1-line is converting to these two:-----
var x;
x = 10;
korosensei
: that's right nagisa๐, but this is not in fact what happens. Hoisting was thought up as a general way of thinking about how execution contexts (specifically the creation and execution phases
) works in JavaScript
. So, behind the scene what is happening is, the variable and function declarations are put into memory during the compile phase, but stay exactly where you typed them in your code. but we consider them as what you said.hoisting-glossary
korosesei
: So, tell me, my assassins, is this even usefull to hoist
the declarations
?
karma
: yes sensei, One of the advantages of JavaScript
putting function declarations
into memory before it executes any code segment, is that it allows us to use a function before you declare it in your code.
korosensei
: Ahsant karma๐
, lets see some examples:
// normal code
function catName(name) {
console.log("My cat's name is " + name);
}
catName("Tiger");
//output: My cat's name is Tiger
The above snippet was a normal code, now lets see this:
catName("Tiger");
function catName(name) {
console.log("My cat's name is " + name);
}
//output: My cat's name is Tiger
Note that, Even though we call the function in our code first(before the function is written
), the code still works. This is because of how context execution works in JavaScript
which is the hoist
behavior.
nagisa
: Sensei, I wonder, what does declaration
means exactly?
koorosensei
: ahhh, that's a good question nagisa
,Actually
Creating a variable in JavaScript is called declaring a variable.W3Schools , And I should say, We can use var, let, const, function, function*, class to create a variable in the memory.Mozila
kaede
: I heard about initialization
and assignment
, can you explain these?
korosensei
: I was going to explain them๐, Please look at this variable life-cycle
:Sitepoint
Declaration
: The variable is registered using a given name within the corresponding scope (explained below โ e.g. inside a function).Initialization
:Auto-Initialize
: When you declare a variable it is automatically initialized, which means memory is allocated for the variable by the JavaScript engine.First Assignment
: It's important to point out that the hoisting will affect the variable declaration, but not its value's initialization. The value will be indeed assigned when the assignment statement is reached Mozilla
Assignment
: This is when a specific value is assigned to the variable.(atexecution time
)
var
life-cyle in action: YDKJS
var x = 1; // In fact, Engine sees two distinct statements:
// one that Compiler will handle during compilation,
// and one that Engine will handle during execution
Korosensei
: Now see these 2 examples to understand better:
Example 1(click to see)
//e1
var x = 1;
//e2
var x = 1;
var x; //`var` can be redeclared multiple time at the same scope-level, but the only first will be used and others will be ignored
//e3
x = 1;
var x;
//-------------------------------------------------------
//-------these 3 examples are equal to the below code--->
//-------------------------------------------------------
var x; // declaration and auto-initialization phase
x = 1; // assignment phase
Example 2(click to see)
//e4
var x = 1;
var x = 2;
var y = 5;
//------- above example is equal to the below code--->
var x; // declaration and auto-initialization phase
var y; // declaration and auto-initialization phase
x = 1; // assignment phase
x = 2; // assignment phase
y = 5;
koro sensei
: let see some interview level
quizzes, I'll explain the first one, and the others are yours:
//q1
console.log(num); // line 1
var num; // Declaration and Auto-Initialization with undefined
num = 6; // First Assignment (or initialize with 6)
line 1
Returns undefined
, as only declaration by var
was hoisted with auto-initialize
to undefined
, and no initialization
has happened at line 1
or before that by assignment
. So its equal to this:
var num; // Declaration and Auto-Initialization with undefined
console.log(num); // line 1
num = 6; // First Assignment (or initialize with 6)
Note: JavaScript only hoists Declarations
, not Initializations, Assignments
.
korosensei
: Now it's your turn, anyone know what will happen and why?๐
//q2
console.log(num);
num = 6;
developer
: sensei ,It will hoist the num
, so the answer is undefined
. easy peasy๐
koro-sensei
: ahsant developer
, but that's not correct๐. karma
can you explain?
karma
: sensei, as you told us before, decalration will happen when we use var,let,const,function, function*, class
, which there is'nt any here in this quiz
, and it has only the initialization(assignment
), so i think it throws ReferenceError exception
, because at the line 1, it wants to access num
in the memory, but there is no num
in there yet.
let me show you plz:
koro-sensei
: barikala karma
๐๐๐๐, let see another example, and developer
, as what you learned, explain this to the class:
// q3
x = 1;
console.log(x + " " + y);
var y = 2;
developer
: ok, sensei, I'll try it:
See the answer after thinking about it atleast 2min
var y; // Declare y (Only y is hoisted)
x = 1; // Initialize x, and if not already declared, declare it
// but no hoisting for `x` as there is no var in the statement.
console.log(x + " " + y); // '1 undefined'
// This prints value of y as undefined as JavaScript only hoists declarations
y = 2; // Initialize y
koro-sensei
: Wow, i'm really happy๐, how about this?developer
:
foo();
function foo() {
console.log("hi");
}
developer
: hmm sensei๐, r you kidding me?
See the answer after thinking about it atleast 2min
//first hoist the declaration
function foo() {
console.log("hi");
}
// then run it at execution time
foo();
// hi
korosensei
: hmmm, got full of yourself?๐ try this:
foo();
var foo = function () {
console.log("hi");
};
/* or this
foo()
var foo = function foo() { console.log('hi'); }
*/
developer
: ahmmm, let me think about it a little more๐ค...
I hope this is the answer:
See the answer after thinking about it atleast 2min
var foo; // first hoist `foo` declaration at creation time
foo(); // the run it at execution time, which should get an error because we are going to "undefined()"?
foo = function () {
// here is assignment
console.log("hi");
};
korosensei
: Yes, yes, afarin developer
๐๐๐๐๐๐๐. in this example we are facing with Function expression instead of a function declaration. So, it just a simple assignment which assigns a function to the foo after assignemnt, therefor until execution
of assignement
, foo remains undefined
.
var foo;
foo = function foo() {
console.log("hi");
};
korosensei
: Now kaede
,it's your turn, tell us:
foo();
function foo() {
console.log("1");
}
foo();
function foo() {
console.log("2");
}
var foo;
foo();
kaede
: sensei, first we will do the hoist operations at creation time, then execute them at execution time
See the answer after thinking about it atleast 2min
// first this will be declared
function foo() {
console.log("1");
}
// second this will be declared, so the previous `foo` will be updated by this new declaration
function foo() {
console.log("2");
}
var foo; // this will be ignored, because `foo` has been declared in the same scope.
foo(); //2
foo(); //2
foo(); //2
korosensei
: tell me about this kaede
// q4
function foo() {
console.log(a, b);
}
a = "Cran"; // Initialize a
b = "berry"; // Initialize b
console.log(a + "" + b); // 'Cranberry'
foo();
kaede
:sensei, No hoisting
for a,b
happens here except foo
, but since initialization also causes declaration (if not already declared), variables a,b
are available everywhere after assignments. but I'm not sure what happens about foo
, but i think it will print Cran berry
without error
, because foo
access them after their declaration and initialization
.
korosensei
: nice answer, beutiful kaede
, you are right, and thats because of something which we refer to as scope
. which I strongly recommend to read it here --ReadMore-Scope--
Now nagisa
, it's your turn, explain this:
var myvar = 1;
(function () {
console.log(myvar);
var myvar = 2;
})();
nagisa
: Well, it's just an IIFE-Immediately Invoked Function Expression, which we can rewrite this as below:
See the answer after thinking about it atleast 2min
var myvar;
myvar = 1;
(function () {
var myvar;
console.log(myvar);
var myvar = 2;
})();
// so the output should be `undefined`
Korosensei
: Well done nagisa
, now let the karma
answer this last quiz๐:
(function () {
var a = (b = 3);
})();
console.log(b);
console.log(a);
Karma:
See the answer after thinking about it atleast 2min
For this, first we declared a
then we defined b
without var , so it will be a global
variable and will be acessible outside of IIFE
function, then we set the value of b
into a
, then the IIFE
function has been finished, so after that, the only variable which has been declared and defined is b
and there is no a
, so we will get Uncaught ReferenceError: a is not defined
(function () {
var a;
b = 3;
a = b;
})();
console.log(b); // 3
console.log(a); // Uncaught ReferenceError: a is not defined
karma
: Sensei, you didnt mentioned let and const
in the examples!!!!!!
korosensei
: hmmm, you are right, We will see them in episode5
(which is about temporal dead zone
and other stuffs), but let us see a quick quiz/answer:
// Example with let:
a = 1; // initialization.
let a; // Throws ReferenceError: Cannot access 'a' before initialization
var z = 1;
let z; //Identifier โzโ has already been declared
console.log(z);
// Example with const:
a = 1; // initialization.
const a; // Throws SyntaxError: Missing initializer in const declaration
Korosensei
: Congratulions๐๐๐. Now you should be able to answer all of these quizzes in this article.
Class
: Horrayyyyyyyyy๐๐๐๐๐๐๐๐`
- Your first contribution can be as simple as clicking the
star
button at the top-right corner of the page. - I would greatly appreciate any
bug fixes
ortype/grammatical errors fixes
. - The mini-series will be in English, but any translation in other languages is very welcomed.
- We plan to make mini-series videos in
Persian
, but any help to make theEnglish
version, will be greatly appreciated and welcomed.