Difference between revisions of "JavaScript/C3/Variable-Keywords-and-Hoisting-in-JS/English"

From Script | Spoken-Tutorial
Jump to: navigation, search
(Created page with "Title of the script: Variable Keywords and Hoisting Author: Jayesh Katta Ramalingaiah Domain Reviewer: Novice Reviewer: Keywords: JavaScript, HTML, hoisting, var, let...")
 
 
(2 intermediate revisions by 2 users not shown)
Line 3: Line 3:
 
Author: Jayesh Katta Ramalingaiah
 
Author: Jayesh Katta Ramalingaiah
  
Domain Reviewer:  
+
Domain Reviewer: Ankita Maske
  
Novice Reviewer:  
+
Novice Reviewer: Praveeen S.
  
 
Keywords: JavaScript, HTML, hoisting, var, let
 
Keywords: JavaScript, HTML, hoisting, var, let
Line 24: Line 24:
 
Learning Objectives
 
Learning Objectives
 
|| In this tutorial, we will learn about:
 
|| In this tutorial, we will learn about:
 
 
 
* '''Variable Keywords '''
 
* '''Variable Keywords '''
 
* '''Scopes''' and
 
* '''Scopes''' and
 
* '''Hoisting'''
 
* '''Hoisting'''
 
 
  
 
|-
 
|-
 
|| Slide: System Specifications
 
|| Slide: System Specifications
 
|| This tutorial is recorded using:
 
|| This tutorial is recorded using:
 
 
 
* '''Ubuntu Linux''' OS version 18.04
 
* '''Ubuntu Linux''' OS version 18.04
 
* '''Visual Studio Code''' version 1.51.0 ('''code editor''')
 
* '''Visual Studio Code''' version 1.51.0 ('''code editor''')
Line 46: Line 40:
 
|| Slide : Pre-requisites
 
|| Slide : Pre-requisites
 
|| To practice this tutorial,
 
|| To practice this tutorial,
 
 
 
* You should be familiar with writing and executing''' JS''' files'''.'''
 
* You should be familiar with writing and executing''' JS''' files'''.'''
 
* If not, please go through the prerequisite tutorials on this website.
 
* If not, please go through the prerequisite tutorials on this website.
 
 
  
 
|-
 
|-
Line 57: Line 47:
 
||  
 
||  
 
* The files used in this tutorial are available in the''' Code files''' link on this tutorial page.
 
* The files used in this tutorial are available in the''' Code files''' link on this tutorial page.
* Pls download and extract the file.
+
* Pls download and extract the files.
 
* Make a copy and then use them for practising.
 
* Make a copy and then use them for practising.
 
 
  
 
|-
 
|-
 
|| Only Narration
 
|| Only Narration
 
||  
 
||  
* So, far we have learnt about '''keyword var '''and used it to declare variables.
+
* So, far we have learnt about '''keyword var '''and used it to '''declare variables'''.
* Now, we will learn 2 more '''keywords '''to declare '''variables '''and the advantages of using them.
+
* Now, we will learn 2 more '''keywords '''to '''declare variables '''and the advantages of using them.
 
+
 
+
  
 
|-
 
|-
Line 74: Line 60:
 
||  
 
||  
 
* '''let keyword''' is used for smaller '''scopes''' technically called '''block scope'''
 
* '''let keyword''' is used for smaller '''scopes''' technically called '''block scope'''
* '''const keyword '''is used for declaring '''constants''' like '''Pi value'''
+
* '''const keyword '''is used for '''declaring constants''' like '''Pi value'''
  
 
(whose value would not change elsewhere in the program)
 
(whose value would not change elsewhere in the program)
Line 83: Line 69:
 
* The '''scope '''of '''var keyword''' is '''functional scope''', that means,
 
* The '''scope '''of '''var keyword''' is '''functional scope''', that means,
 
* The '''variable declared''' inside a '''function '''using '''var''', cannot be accessed outside the '''function'''.
 
* The '''variable declared''' inside a '''function '''using '''var''', cannot be accessed outside the '''function'''.
 
 
  
 
|-
 
|-
Line 93: Line 77:
 
** '''const'''  
 
** '''const'''  
 
* They both have '''block scope'''
 
* They both have '''block scope'''
 
 
  
 
|-
 
|-
Line 101: Line 83:
 
* A '''variable declared''' with '''let '''or '''const''' inside a '''loop''', '''if/else condition''' or '''switch case'''
 
* A '''variable declared''' with '''let '''or '''const''' inside a '''loop''', '''if/else condition''' or '''switch case'''
 
* Cannot be accessed outside the '''block scope'''.
 
* Cannot be accessed outside the '''block scope'''.
 
 
  
 
|-
 
|-
 
|| Only Narration
 
|| Only Narration
|| Now, let us take an example and understand these better.
+
|| Let us take an example and understand these better.
  
 
|-
 
|-
Line 114: Line 94:
 
|-
 
|-
 
|| <nowiki>[Editor] </nowiki>
 
|| <nowiki>[Editor] </nowiki>
 
  
 
Welcome Page -> Open Folder -> '''Practice-JS'''
 
Welcome Page -> Open Folder -> '''Practice-JS'''
 
|| In the '''editor, '''browse and open the folder “'''Practice-JS''' ”.
 
|| In the '''editor, '''browse and open the folder “'''Practice-JS''' ”.
 
 
 
  
 
|-
 
|-
 
|| <nowiki>[Editor] </nowiki>Click on  
 
|| <nowiki>[Editor] </nowiki>Click on  
 
  
 
'''Explorer '''pane -> '''Practice-JS''' -> '''index.html'''
 
'''Explorer '''pane -> '''Practice-JS''' -> '''index.html'''
Line 258: Line 233:
  
  
Anything you write between,''' {}''' technically is a '''block.'''
+
Anything you write between braces, technically, is a '''block.'''
  
  
Here, I have declared '''variable b '''using '''let keyword.'''
+
Here, I have '''declared variable b '''using '''let keyword.'''
  
  
To verify this, I’m using a '''log statement''' to display the text value''' '''- '''‘Inside block’.'''
+
To verify this, I’m using a '''log statement''' to display the text value - '''‘Inside block’.'''
  
 
|-
 
|-
Line 291: Line 266:
  
 
'''Inside Function: 10'''
 
'''Inside Function: 10'''
|| As expected, when I make a '''function call '''the value 10 gets '''logged'''.
+
|| As expected, when I make a '''function call, '''the value 10 gets '''logged'''.
  
 
|-
 
|-
Line 304: Line 279:
  
 
It displays 30, because of the '''log statement''' written inside the '''block'''.
 
It displays 30, because of the '''log statement''' written inside the '''block'''.
 
 
 
  
 
|-
 
|-
Line 318: Line 290:
  
  
The console displays, '''Uncaught ReferenceError: a is not defined'''
+
The '''console''' displays, '''Uncaught ReferenceError: a is not defined'''
  
  
Line 361: Line 333:
  
  
Hence the '''keyword let '''has '''block''' '''scope'''.
+
Hence the '''keyword let '''has '''block scope'''.
  
 
|-
 
|-
Line 377: Line 349:
 
const pi = 3.14;
 
const pi = 3.14;
  
pi = 3.142857;
+
pi = 3.141592;
 
|| In the '''main.js '''file, replace the '''code''' as shown.
 
|| In the '''main.js '''file, replace the '''code''' as shown.
  
Line 394: Line 366:
  
  
pi = 3.142857;
+
pi = 3.141592;
|| Here, I’m trying to reassign the '''variable pi''' to '''3.142857.'''
+
|| Here, I’m trying to reassign the '''variable pi''' to '''3.141592.'''
  
 
|-
 
|-
Line 453: Line 425:
  
 
};
 
};
|| Here, I have declared a '''variable '''with the name '''student.'''
+
|| Here, I have '''declared''' a '''variable '''with the name '''student.'''
  
  
Line 459: Line 431:
  
  
The '''object '''contains a '''property name '''with the value '''jayesh.'''
+
The '''object '''contains a '''property name''' with the value '''jayesh.'''
  
 
|-
 
|-
Line 472: Line 444:
  
 
console.log(student);
 
console.log(student);
|| To verify what happens, I’m logging the ‘'''student’ variable'''.
+
|| To verify what happens, I’m '''logging''' the ‘'''student’ variable'''.
  
 
|-
 
|-
Line 489: Line 461:
  
 
'''Object { name: "Praveen" }'''
 
'''Object { name: "Praveen" }'''
|| Notice here, we have the value of '''name''' '''property '''changed from '''jayesh '''to '''praveen'''.
+
|| Notice here, we have the value of '''name property '''changed from '''jayesh '''to '''praveen'''.
  
 
|-
 
|-
 
|| Only Narration
 
|| Only Narration
|| By this we conclude that for '''non-primitive data types''' '''const '''acts differently.
+
|| By this we conclude that for '''non-primitive data types const '''acts differently.
  
  
Line 510: Line 482:
 
* '''Variables '''which are '''declared''' outside the '''function '''or a '''block '''
 
* '''Variables '''which are '''declared''' outside the '''function '''or a '''block '''
 
* are available inside the '''function '''or a '''block'''.
 
* are available inside the '''function '''or a '''block'''.
 
 
  
 
|-
 
|-
Line 654: Line 624:
  
  
This is because '''variables declared''' using '''var keyword''' are '''hoisted'''.
+
This is because '''variables declared''' using '''var keyword''' is '''hoisted'''.
  
  
Line 696: Line 666:
 
|| Slide''': '''Summary''' '''
 
|| Slide''': '''Summary''' '''
 
|| In this tutorial, we have learnt:
 
|| In this tutorial, we have learnt:
 
 
 
* '''Variable Keywords'''
 
* '''Variable Keywords'''
 
* '''Scopes '''and
 
* '''Scopes '''and
* '''Hoisting'''
+
* '''Hoisting''' in '''JS'''
 
+
 
+
  
 
|-
 
|-
Line 710: Line 676:
 
* Open the file '''assignment.js'''
 
* Open the file '''assignment.js'''
 
* Clear the existing code
 
* Clear the existing code
* Log the '''value''' '''x''' in console first before declaring '''x''' value
+
* '''Log''' the value '''x''' in '''console''' first before '''declaring x''' value
* Declare a '''variable x''' using '''const below '''the '''log statement'''
+
* '''Declare''' a '''variable x''' using '''const below '''the '''log statement'''
* Open the file '''MyPage.html '''in a '''web''' '''browser'''.
+
* Open the file '''MyPage.html '''in a '''web browser'''.
 
* Observe the output in the '''browser’s console'''
 
* Observe the output in the '''browser’s console'''
 
* An '''error '''is observed
 
* An '''error '''is observed
 
* Reason: Recall that the '''variables declared''' with '''const '''will not be '''hoisted'''
 
* Reason: Recall that the '''variables declared''' with '''const '''will not be '''hoisted'''
 
 
  
 
|-
 
|-
Line 724: Line 688:
 
* The video at the following link summarises the Spoken Tutorial project.
 
* The video at the following link summarises the Spoken Tutorial project.
 
* Please download and watch it
 
* Please download and watch it
 
 
  
 
|-
 
|-
Line 732: Line 694:
 
* We conduct workshops using spoken tutorials and give certificates.
 
* We conduct workshops using spoken tutorials and give certificates.
 
* For more details, please write to us.
 
* For more details, please write to us.
 
 
  
 
|-
 
|-

Latest revision as of 11:09, 21 June 2021

Title of the script: Variable Keywords and Hoisting

Author: Jayesh Katta Ramalingaiah

Domain Reviewer: Ankita Maske

Novice Reviewer: Praveeen S.

Keywords: JavaScript, HTML, hoisting, var, let


Visual Cue
Narration
Slide: Title Hello and Welcome to the spoken tutorial on “Variable Keywords, Scopes and Hoisting in JS”.
Slide:

Learning Objectives

In this tutorial, we will learn about:
  • Variable Keywords
  • Scopes and
  • Hoisting
Slide: System Specifications This tutorial is recorded using:
  • Ubuntu Linux OS version 18.04
  • Visual Studio Code version 1.51.0 (code editor)
  • Firefox web browser

However you may use any other browser of your choice.

Slide : Pre-requisites To practice this tutorial,
  • You should be familiar with writing and executing JS files.
  • If not, please go through the prerequisite tutorials on this website.
Slide: Code files
  • The files used in this tutorial are available in the Code files link on this tutorial page.
  • Pls download and extract the files.
  • Make a copy and then use them for practising.
Only Narration
  • So, far we have learnt about keyword var and used it to declare variables.
  • Now, we will learn 2 more keywords to declare variables and the advantages of using them.
Slide: Variable Keywords
  • let keyword is used for smaller scopes technically called block scope
  • const keyword is used for declaring constants like Pi value

(whose value would not change elsewhere in the program)

Slide: Scope
  • The scope of var keyword is functional scope, that means,
  • The variable declared inside a function using var, cannot be accessed outside the function.
Slide: Scope
  • To declare variables, ES6 has introduced two new keywords:
    • let and
    • const
  • They both have block scope
Slide: Scope
  • A variable declared with let or const inside a loop, if/else condition or switch case
  • Cannot be accessed outside the block scope.
Only Narration Let us take an example and understand these better.
Show VS editor Open Visual Studio Code editor
[Editor]

Welcome Page -> Open Folder -> Practice-JS

In the editor, browse and open the folder “Practice-JS ”.
[Editor] Click on

Explorer pane -> Practice-JS -> index.html

Under Practice-JS folder, open the file named index.html


The same is available in the Code files link for practice.

[Editor] Type:


<!DOCTYPE html>

<html lang="en">

<head>

<title> Variable Keywords and Hoisting </title>

</head>

<body>

<script src = "main.js" > </script>

</body>

</html>

In the index.html file, update the code as shown.


In this code we have written a small HTML code and linked the JS file.

Press: Ctrl + S Save the file.
Press: Alt + L and Alt + O Start the Live server.
Show firefox The default browser will open automatically and a new tab opens.
[Firefox] Press Ctrl + Shift + I


Point to the browser developer tools


Click on the Console tab

Now open the Browser developer tools panel and go to the console tab
Switch to Editor Switch back to the editor.
[Editor] Click on


Explorer pane -> Practice-JS -> main.js

Under Practice-JS folder, open the file named main.js
[Editor] Type:


function display() {

var a = 10;

console.log("Inside Function: ", a);

}


display();

{

let b = 30;

console.log("Inside block: ", b);

}


console.log("Outside Function: ", a);

In the main.js file, update the code as shown.
[Editor] Highlight:


function display() {

var a = 10;

console.log("Inside Function: ", a);

}

Here, I have declared a function named display.


Inside the function, I have declared a variable using var keyword and assigned 10 as a value to it.


To verify this, I’m using a log statement to display the text value - ‘Inside Function’.

[Editor] Highlight:


display();

Here, I’m making a function call to execute the declared function.
[Editor] Highlight:


{

let b = 30;

console.log("Inside block: ", b);

}

Here, I have created a block.


Anything you write between braces, technically, is a block.


Here, I have declared variable b using let keyword.


To verify this, I’m using a log statement to display the text value - ‘Inside block’.

[Editor] Highlight:


console.log("Outside Function: ", a);

Here, I’m using a log statement to display the value ‘a’ outside the function.


This is to verify whether we can access the value outside the function or not.

Press: Ctrl + S Save the file.
Switch to Browser Switch back to the browser.
[Browser] [Console Tab]:

Highlight:


Inside Function: 10

As expected, when I make a function call, the value 10 gets logged.
[Browser] [Console Tab]:

Highlight:


Inside block: 30

Similarly the block also gets executed after the function call.


It displays 30, because of the log statement written inside the block.

[Browser] [Console Tab]:

Highlight:


Uncaught ReferenceError: a is not defined

Now, as we are trying to display the value of ‘a’ outside the function, we got an error.


The console displays, Uncaught ReferenceError: a is not defined


By this we conclude that the variable which is declared using var has a functional scope.

Switch to Editor Switch back to the editor.
[Editor] Type:


console.log("Outside block: ", b);

In the main.js file, replace the last console log statement with the code as shown.


Here, we’ll test whether the variable declared inside the block is available outside or not.

Press: Ctrl + S Save the file.
Switch to Browser Switch back to the browser.
[Browser] [Console Tab]:

Highlight:


Uncaught ReferenceError: b is not defined

Now, we get an error for the outside block log statement.


Uncaught ReferenceError: b is not defined


By this we conclude that the variable declared inside the block is not accessible outside.


Hence the keyword let has block scope.

Only Narration Now lets learn about the const keyword.
Switch to Editor Switch back to the editor.
[Editor] Type:


const pi = 3.14;

pi = 3.141592;

In the main.js file, replace the code as shown.
[Editor] Highlight:


const pi = 3.14;

Here, I have declared a variable pi and assigned 3.14 to it.


Note that the data type here is primitive (number).

[Editor] Highlight:


pi = 3.141592;

Here, I’m trying to reassign the variable pi to 3.141592.
Press: Ctrl + S Save the file.
Switch to Browser Switch back to the browser.
[Browser] [Console Tab]:

Highlight:


Uncaught TypeError: invalid assignment to const 'pi'

Notice we get an error- “Uncaught TypeError: invalid assignment to const 'pi' “.


Hence, we conclude that the value for a const variable cannot be changed.

Only Narration Note again, we have tested only for primitive data type.


Now, let's check for non-primitive data types.

Switch to Editor Switch back to the editor.
[Editor] Type:


const student = {

name: "Jayesh",

};

student.name = "Praveen";


console.log(student);

In the main.js file, replace the code as shown.
[Editor] Highlight:


const student = {

name: "Jayesh",

};

Here, I have declared a variable with the name student.


Then I have assigned an object (non -primitive data type) to it.


The object contains a property name with the value jayesh.

[Editor] Highlight:


student.name = "Praveen";

Now here, I try to change the property value from jayesh to praveen.
[Editor] Highlight:

console.log(student);

To verify what happens, I’m logging the ‘student’ variable.
Press: Ctrl + S Save the file.
Switch to Browser Switch back to the browser.
[Browser] [Console Tab]:

Highlight:


Object { name: "Praveen" }

Notice here, we have the value of name property changed from jayesh to praveen.
Only Narration By this we conclude that for non-primitive data types const acts differently.


It does not modify the object data type.


We can add properties and change the property values.


Similarly for arrays, we can add and remove values in an array.

Slide: Lexical Scope In JavaScript,
  • Variables which are declared outside the function or a block
  • are available inside the function or a block.
Only Narration Now, let us take an example and understand this better.
Switch to Editor Switch back to the editor.
[Editor] Type:


let a = 10;


function display() {

console.log("Value of a is ", a);

}


display();

In the main.js file, replace the code as shown.
[Editor] Highlight: let a = 10; Here, I have declared a variable ‘a’ with let keyword and assigned 10 to it.
[Editor] Highlight:


function display() {

console.log("Value of a is ", a);

}

Then, I have created a function display and I’m trying to log the value of a.
[Editor] Highlight:


display();

Here, I make a function call to execute the function.
Press: Ctrl + S Save the file.
Switch to Browser Switch back to the browser.
[Browser] [Console Tab]:

Highlight:


Value of a is 10

The value a which is declared outside the function is available inside the function too.


That's the reason 10 is displayed.


This mechanism is called the lexical scope in JS.

Only Narration Now, let’s go to the next topic.
Slide: Hoisting Hoisting is JavaScript’s default behavior of moving declarations to the top of the Scope before execution.
Only Narration Now, let us take an example and understand this better.
Switch to Editor Switch back to the editor.
[Editor] Type:


console.log("The value of a is ", a);

console.log("The value of b is ", b);


var a = 10;

let b = 20;

In the main.js file, replace the code as shown.
[Editor] Highlight:


console.log("The value of a is ", a);

console.log("The value of b is ", b);

Here, I’m trying to log the a and b values which are not declared yet.
[Editor] Highlight:


var a = 10;

Below the log statements, I have declared a variablea’ using the var keyword and assigned 10 to it.
[Editor] Highlight:

let b = 20;

Here, I have declared a variable ‘b’ using the let keyword and assigned 20 to it.


Now, let’s see what happens.

Press: Ctrl + S Save the file.
Switch to Browser Switch back to the browser.
[Browser] [Console Tab]: Highlight:


The value of a is undefined

Notice here, we got the value of a as undefined.


This is because variables declared using var keyword is hoisted.


The declarations will be pushed to the top of the scope.


And, the value is undefined because it’s a default value.

[Browser] [Console Tab]:

Highlight:


Uncaught ReferenceError: can't access lexical declaration 'b' before initialization

Uncaught ReferenceError: can't access lexical declaration 'b' before initialization


This happens for b because hoisting does not happen for let and const.


Only after declaration, the values can be used.

Only Narration So we conclude that hoisting happens for variables declared with var, and not for let and const.


Even functions can be hoisted.

That is the reason we can execute a function before declaration.

Only Narration With this we have come to the end of this tutorial.


Let’s summarize.

Slide: Summary In this tutorial, we have learnt:
  • Variable Keywords
  • Scopes and
  • Hoisting in JS
Slide: Assignment As an assignment,
  • Open the file assignment.js
  • Clear the existing code
  • Log the value x in console first before declaring x value
  • Declare a variable x using const below the log statement
  • Open the file MyPage.html in a web browser.
  • Observe the output in the browser’s console
  • An error is observed
  • Reason: Recall that the variables declared with const will not be hoisted
Slide: About Spoken Tutorial Project
  • The video at the following link summarises the Spoken Tutorial project.
  • Please download and watch it
Slide: Spoken tutorial workshops
  • We conduct workshops using spoken tutorials and give certificates.
  • For more details, please write to us.
Slide: Forum questions Pls post your timed queries in this forum.
Slide: Acknowledgement Spoken Tutorial Project is funded by Ministry of Education (MoE), Government of India
Slide: Thanks The script for this tutorial is contributed by Jayesh.

And this is Praveen from IIT Bombay signing off.

Thank you for joining.

Contributors and Content Editors

Kr.jayesh, Nancyvarkey, Pravin1389