SlideShare a Scribd company logo
11_Functions_Introduction.pptx javascript notes
FUNCTIONS IN JAVASCRIPT
What Is A
Function ?
A function is a block of reusable code written to perform a
specific task. We can think of a function as a sub-program within
the main program.
.
A function consists of a set of statements but
executes as a single unit.
What Is A
Function ?
Functions are one of the fundamental concepts in programming.
They let us write modular, reusable,
and maintainable code
Examples Of Functions ?
JavaScript provides many built-in functions such as parseInt(),
parseFloat(), alert(), prompt(), confirm() etc
.
They all are predefined functions but now we will learn
how to develop user defined functions in JavaScript.
Types Of Functions ?
There are 3 popular types of functions we can develop in
JavaScript :
.
1. Named Function
2. Anonymous Function
3. Arrow Function
Steps Needed For Function ?
In JavaScript the function based programming approach requires
2 steps:
1. Defining the function
2. Calling the function
Syntax Of Defining A Function
Functions can be defined in both <head> and <body> section
but generally are placed in the head section.
<script>
function functionName( arg 1,arg 2. . .)
{
// some code
}
</script>
Syntax Of Calling A Function
<script>
functionName(arg 1,arg 2. . .);
</script>
Points To Remember
A function with no parameters must include a parenthesis after
it’s
name
*
The word “function” must be written in lowercase.
*
Using arguments Array
Whenever a function is invoked it gets an object called
“arguments” which acts like an array and holds the arguments
sent to that function.
This feature is very helpful if we don’t know how many arguments
might be passed to the function.
PROGRAM
Write a JavaScript function called “average( )” which
should accept some integers as argument and
calculates and displays their sum and average.
Calling Functions Via Button
A function can be called directly on a button click.
For this we need to assign the function call to the onclick event
attribute of the button tag.
Syntax:
<input type=“button” value=“some text”
onclick=“funcName();” >
Variable Scope
Variables declared outside a function, become GLOBAL, and all
scripts and functions on the web page can access it.
A variable declared (using var) within a JavaScript function
becomes LOCAL and can only be accessed from within that
function. (the variable has local scope).
If we assign a value to variable that has not yet been declared, the
variable will automatically be declared as a GLOBAL variable.
Returning Values
function functionName(var 1,var 2. . .)
{
// some code
return (variable or value);
}
To return a value from a function we use the keyword “return” .
The keyword return can only be used in a function.
A Very Important Point !!
In JavaScript functions are first-class citizens.
This means that we can:
1. store functions in variables
2. pass them as argument to other functions
3. return them from other functions.
In simple words, we can treat functions like values.
Anonymous Functions
Anonymous function is a function that does not have any name
associated with it.
Normally we use the function keyword before the function name to
define a function in JavaScript.
However, in anonymous functions in JavaScript, we use only the
function keyword without the function name.
Anonymous Functions
A function definition can be directly assigned to a variable .
This variable is like any other variable except that it’s value is a
function definition and can be used as a reference to that function.
Syntax:
var variablename = function(Argument List)
{
//Function Body
};
Calling Anonymous Functions
We can call an anonymous function using it’s variable name
Syntax:
variableName(arguments);
Some Important Built-In Functions
1. setInterval(function_name,time_period)
Accepts the name of a function and a time period in ms and calls
the function after the given ms , repeatedly. It also returns a
number representing the ID value of the timer that is set which can
be used with the clearInterval() method to cancel the timer
2. clearInterval(ID)
Clears the timer ,of the given ID ,set with the setInterval() method.
Some Important Built-In Functions
3. setTimeout(function_name,time_period)
Accepts the name of a function and a time period in ms and calls the
function after the given ms, only once. It also returns a number
representing the ID value of the timer that is set which can be used
with the clearTimeout() method to cancel the timer
4. clearTimeout(ID)
Clears the timer ,of the given ID , set with the setTimeout() method.
var v/s let
Now that we have learnt concept of functions , we must discuss
the difference between var and let keywords.
They differ in four ways:
1. Scope
2. Redeclaration
3. Window object
4. Using before declaring
Scope
Scope essentially means where these variables are available for
use.
var declarations are globally scoped or function/locally scoped ,
while let declarations are block scoped.
This means that a variable declared with var inside a function
anywhere is available through out that function while a let
variable declared inside a block is available only till the block
terminates
Scope
Example:
for (var i = 1; i <= 3; i++)
{
console.log(i);
}
console.log(i);
Output:
1
2
3
4
Example:
for (let i = 1; i <= 3; i++) {
console.log(i);
}
console.log(i);
Output:
1
2
3
Uncaught
ReferenceError: i is not
defined
Redeclaration
The var keyword allows us to redeclare a variable without any
issue.
var counter = 10;
var counter = 20;
console.log(counter); // 20
If we redeclare a variable with the let keyword, we will get an error:
let counter = 10;
let counter = 20; // error: x is already defined
The window Object
We know that a variable declared globally with var becomes a
property of window object but it is not true for variable declared
with let.
Example:
var x=10;
let y=20;
console.log(window.x);
console.log(window.y);
Output:
10
undefined
Using Before Declaring
We can use a variable created using var even before declaring it.
Example:
console.log(x);
var x=10;
console.log(x);
Output:
undefined
10
Using Before Declaring
However , let does not allow us to do this and so if we write the
previous code using let then JS will throw error:
Example:
console.log(x);
let x=10;
console.log(x);
Output:
Uncaught ReferenceError: Cannot access ‘x' before initialization.
Ad

More Related Content

Similar to 11_Functions_Introduction.pptx javascript notes (20)

Ch4 functions
Ch4 functionsCh4 functions
Ch4 functions
Hattori Sidek
 
Learn more about the concepts Functions of Python
Learn more about the concepts Functions of PythonLearn more about the concepts Functions of Python
Learn more about the concepts Functions of Python
PrathamKandari
 
Function in C++
Function in C++Function in C++
Function in C++
Prof Ansari
 
[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++
Muhammad Hammad Waseem
 
Java script function
Java script functionJava script function
Java script function
suresh raj sharma
 
FUNCTIONS.pptx
FUNCTIONS.pptxFUNCTIONS.pptx
FUNCTIONS.pptx
KalashJain27
 
What is storage class
What is storage classWhat is storage class
What is storage class
Isha Aggarwal
 
Functions in c
Functions in cFunctions in c
Functions in c
SunithaVesalpu
 
Functions
FunctionsFunctions
Functions
Septi Ratnasari
 
use of Functions to write python program.pptx
use of Functions to write python program.pptxuse of Functions to write python program.pptx
use of Functions to write python program.pptx
rahulsinghsikarwar2
 
functions new.pptx
functions new.pptxfunctions new.pptx
functions new.pptx
bhuvanalakshmik2
 
functions notes.pdf python functions and opp
functions notes.pdf python functions and oppfunctions notes.pdf python functions and opp
functions notes.pdf python functions and opp
KirtiGarg71
 
Storage Classes and Functions
Storage Classes and FunctionsStorage Classes and Functions
Storage Classes and Functions
Jake Bond
 
Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)
nirajmandaliya
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programming
nirajmandaliya
 
Books
BooksBooks
Books
Steven Foster Murray
 
Chapter 13.1.6
Chapter 13.1.6Chapter 13.1.6
Chapter 13.1.6
patcha535
 
Operator Overloading and Scope of Variable
Operator Overloading and Scope of VariableOperator Overloading and Scope of Variable
Operator Overloading and Scope of Variable
MOHIT DADU
 
Handout # 4 functions + scopes
Handout # 4   functions + scopes Handout # 4   functions + scopes
Handout # 4 functions + scopes
NUST Stuff
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1
YOGESH SINGH
 
Learn more about the concepts Functions of Python
Learn more about the concepts Functions of PythonLearn more about the concepts Functions of Python
Learn more about the concepts Functions of Python
PrathamKandari
 
What is storage class
What is storage classWhat is storage class
What is storage class
Isha Aggarwal
 
use of Functions to write python program.pptx
use of Functions to write python program.pptxuse of Functions to write python program.pptx
use of Functions to write python program.pptx
rahulsinghsikarwar2
 
functions notes.pdf python functions and opp
functions notes.pdf python functions and oppfunctions notes.pdf python functions and opp
functions notes.pdf python functions and opp
KirtiGarg71
 
Storage Classes and Functions
Storage Classes and FunctionsStorage Classes and Functions
Storage Classes and Functions
Jake Bond
 
Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)
nirajmandaliya
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programming
nirajmandaliya
 
Chapter 13.1.6
Chapter 13.1.6Chapter 13.1.6
Chapter 13.1.6
patcha535
 
Operator Overloading and Scope of Variable
Operator Overloading and Scope of VariableOperator Overloading and Scope of Variable
Operator Overloading and Scope of Variable
MOHIT DADU
 
Handout # 4 functions + scopes
Handout # 4   functions + scopes Handout # 4   functions + scopes
Handout # 4 functions + scopes
NUST Stuff
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1
YOGESH SINGH
 

Recently uploaded (20)

Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...
parmarjuli1412
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)
Mohamed Rizk Khodair
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Association for Project Management
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 
Module 1: Foundations of Research
Module 1: Foundations of ResearchModule 1: Foundations of Research
Module 1: Foundations of Research
drroxannekemp
 
Cultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptxCultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptx
UmeshTimilsina1
 
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
parmarjuli1412
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptxTERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
PoojaSen20
 
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Leonel Morgado
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...
parmarjuli1412
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)
Mohamed Rizk Khodair
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Association for Project Management
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 
Module 1: Foundations of Research
Module 1: Foundations of ResearchModule 1: Foundations of Research
Module 1: Foundations of Research
drroxannekemp
 
Cultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptxCultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptx
UmeshTimilsina1
 
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
parmarjuli1412
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptxTERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
PoojaSen20
 
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Leonel Morgado
 
Ad

11_Functions_Introduction.pptx javascript notes

  • 3. What Is A Function ? A function is a block of reusable code written to perform a specific task. We can think of a function as a sub-program within the main program. . A function consists of a set of statements but executes as a single unit.
  • 4. What Is A Function ? Functions are one of the fundamental concepts in programming. They let us write modular, reusable, and maintainable code
  • 5. Examples Of Functions ? JavaScript provides many built-in functions such as parseInt(), parseFloat(), alert(), prompt(), confirm() etc . They all are predefined functions but now we will learn how to develop user defined functions in JavaScript.
  • 6. Types Of Functions ? There are 3 popular types of functions we can develop in JavaScript : . 1. Named Function 2. Anonymous Function 3. Arrow Function
  • 7. Steps Needed For Function ? In JavaScript the function based programming approach requires 2 steps: 1. Defining the function 2. Calling the function
  • 8. Syntax Of Defining A Function Functions can be defined in both <head> and <body> section but generally are placed in the head section. <script> function functionName( arg 1,arg 2. . .) { // some code } </script>
  • 9. Syntax Of Calling A Function <script> functionName(arg 1,arg 2. . .); </script>
  • 10. Points To Remember A function with no parameters must include a parenthesis after it’s name * The word “function” must be written in lowercase. *
  • 11. Using arguments Array Whenever a function is invoked it gets an object called “arguments” which acts like an array and holds the arguments sent to that function. This feature is very helpful if we don’t know how many arguments might be passed to the function.
  • 12. PROGRAM Write a JavaScript function called “average( )” which should accept some integers as argument and calculates and displays their sum and average.
  • 13. Calling Functions Via Button A function can be called directly on a button click. For this we need to assign the function call to the onclick event attribute of the button tag. Syntax: <input type=“button” value=“some text” onclick=“funcName();” >
  • 14. Variable Scope Variables declared outside a function, become GLOBAL, and all scripts and functions on the web page can access it. A variable declared (using var) within a JavaScript function becomes LOCAL and can only be accessed from within that function. (the variable has local scope). If we assign a value to variable that has not yet been declared, the variable will automatically be declared as a GLOBAL variable.
  • 15. Returning Values function functionName(var 1,var 2. . .) { // some code return (variable or value); } To return a value from a function we use the keyword “return” . The keyword return can only be used in a function.
  • 16. A Very Important Point !! In JavaScript functions are first-class citizens. This means that we can: 1. store functions in variables 2. pass them as argument to other functions 3. return them from other functions. In simple words, we can treat functions like values.
  • 17. Anonymous Functions Anonymous function is a function that does not have any name associated with it. Normally we use the function keyword before the function name to define a function in JavaScript. However, in anonymous functions in JavaScript, we use only the function keyword without the function name.
  • 18. Anonymous Functions A function definition can be directly assigned to a variable . This variable is like any other variable except that it’s value is a function definition and can be used as a reference to that function. Syntax: var variablename = function(Argument List) { //Function Body };
  • 19. Calling Anonymous Functions We can call an anonymous function using it’s variable name Syntax: variableName(arguments);
  • 20. Some Important Built-In Functions 1. setInterval(function_name,time_period) Accepts the name of a function and a time period in ms and calls the function after the given ms , repeatedly. It also returns a number representing the ID value of the timer that is set which can be used with the clearInterval() method to cancel the timer 2. clearInterval(ID) Clears the timer ,of the given ID ,set with the setInterval() method.
  • 21. Some Important Built-In Functions 3. setTimeout(function_name,time_period) Accepts the name of a function and a time period in ms and calls the function after the given ms, only once. It also returns a number representing the ID value of the timer that is set which can be used with the clearTimeout() method to cancel the timer 4. clearTimeout(ID) Clears the timer ,of the given ID , set with the setTimeout() method.
  • 22. var v/s let Now that we have learnt concept of functions , we must discuss the difference between var and let keywords. They differ in four ways: 1. Scope 2. Redeclaration 3. Window object 4. Using before declaring
  • 23. Scope Scope essentially means where these variables are available for use. var declarations are globally scoped or function/locally scoped , while let declarations are block scoped. This means that a variable declared with var inside a function anywhere is available through out that function while a let variable declared inside a block is available only till the block terminates
  • 24. Scope Example: for (var i = 1; i <= 3; i++) { console.log(i); } console.log(i); Output: 1 2 3 4 Example: for (let i = 1; i <= 3; i++) { console.log(i); } console.log(i); Output: 1 2 3 Uncaught ReferenceError: i is not defined
  • 25. Redeclaration The var keyword allows us to redeclare a variable without any issue. var counter = 10; var counter = 20; console.log(counter); // 20 If we redeclare a variable with the let keyword, we will get an error: let counter = 10; let counter = 20; // error: x is already defined
  • 26. The window Object We know that a variable declared globally with var becomes a property of window object but it is not true for variable declared with let. Example: var x=10; let y=20; console.log(window.x); console.log(window.y); Output: 10 undefined
  • 27. Using Before Declaring We can use a variable created using var even before declaring it. Example: console.log(x); var x=10; console.log(x); Output: undefined 10
  • 28. Using Before Declaring However , let does not allow us to do this and so if we write the previous code using let then JS will throw error: Example: console.log(x); let x=10; console.log(x); Output: Uncaught ReferenceError: Cannot access ‘x' before initialization.
  翻译: