Skip to content

Latest commit

ย 

History

History
518 lines (369 loc) ยท 18.2 KB

File metadata and controls

518 lines (369 loc) ยท 18.2 KB

Episode 2

JavaScript Base Concepts(Hoist)

Javascript Hoist the right way assasin level

nagisa

kaede: hey nagisa, should we tell him?๐Ÿค”

nagisa

nagisa: hmmm, about what?๐Ÿ˜…

nagisa

kaede: About real practice๐Ÿ™„, how should we really learn with just theoris?

nagisa

nagisa: ahaaa๐Ÿ˜‚, Yep, I'm agree, do you want me to tell him?

nagisa

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๐Ÿ˜”

koro-sensei or JS master

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???

nagisanagisakarmadeveloper he/she

Class: Yessssss

Javascript Hoist the right way assasin level

koro-sensei or JS master

korosensei: So everyone, put your guns down and listen very well. Anyne knows exact definition of Hoisting?

nagisa

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;

koro-sensei or JS master

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

koro-sensei or JS master

korosesei: So, tell me, my assassins, is this even usefull to hoist the declarations?

karma

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.

koro-sensei or JS master

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

nagisa: Sensei, I wonder, what does declaration means exactly?

koro-sensei or JS master

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

nagisa

kaede: I heard about initialization and assignment, can you explain these?

koro-sensei or JS master

korosensei: I was going to explain them๐Ÿ˜Š, Please look at this variable life-cycle:Sitepoint

Javascript Hoist the right way assasin level
  • 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.(at execution 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
Javascript Hoist the right way assasin level

koro-sensei or JS master

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 or JS master

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.

koro-sensei or JS master

korosensei: Now it's your turn, anyone know what will happen and why?๐Ÿ˜ˆ

//q2
console.log(num);
num = 6;

developer he/she

developer: sensei ,It will hoist the num, so the answer is undefined. easy peasy๐Ÿ˜Ž

koro-sensei or JS master

koro-sensei: ahsant developer, but that's not correct๐Ÿ˜‚. karma can you explain?

karma

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:

Javascript Hoist the right way assasin level

koro-sensei or JS master

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 he/she

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 or JS master

koro-sensei: Wow, i'm really happy๐Ÿ˜, how about this?developer:

foo();
function foo() {
  console.log("hi");
}

developer he/she

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

koro-sensei or JS master

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 he/she

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");
};

koro-sensei or JS master

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");
};

koro-sensei or JS master

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

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

koro-sensei or JS master

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

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.

koro-sensei or JS master

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

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`

koro-sensei or JS master

Korosensei: Well done nagisa, now let the karma answer this last quiz๐Ÿ˜ˆ:

(function () {
  var a = (b = 3);
})();

console.log(b);
console.log(a);

karma

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

karma: Sensei, you didnt mentioned let and const in the examples!!!!!!

koro-sensei or JS master

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

koro-sensei or JS master

Korosensei: Congratulions๐ŸŽ‰๐ŸŽ‰๐ŸŽ‰. Now you should be able to answer all of these quizzes in this article.

nagisanagisakarmadeveloper he/she

Class: Horrayyyyyyyyy๐Ÿ˜๐Ÿ˜๐ŸŽ‰๐ŸŽ‰๐Ÿ‘๐Ÿ‘๐Ÿ‘๐Ÿ‘`

Contribute

  • 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 or type/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 the English version, will be greatly appreciated and welcomed.

Some of Current used resources: