SlideShare uma empresa Scribd logo
1 de 18
JavaScript’s Hidden Treasures :
Closures and Hoisting
By Geekyants
INTRODUCTION
JavaScript possesses many hidden features that can often make us feel confused
and bewildered. Let’s demystify two of them.
1. Closures
2. Hoisting
Closures
We encounter closures several times while coding in JavaScript. So it’s quite necessary to
understand what they actually signify. Let’s first zip through some formal definitions.
What is a closure?
• A closure is a function that has access to the parent scope, even after the scope
has returned we can also define it as:
• A closure is the combination of a function and the lexical environment within which that
function was declared.
Scope
The Scope is essentially the lifespan of a variable in JavaScript. Where a variable is
defined plays a large role in how long that variable is around, and which functions in
your program have access to it.
So it would be safe to say that any function can be considered a closure because a
function can refer to or have access to:
• Any variable or parameter in its own function scope.
• Any variable or parameters of its outer (parent) functions.
• Any variable from the global scope.
Definition of closure into
3 parts.
1.We can refer to variables defined outside of
the current function.
Here, the printData() function refers to
the type variable and the model parameter of
the enclosing function setData(). So
when setData() is called, printData()uses the
variables and parameters of the former to
print the output “Audi is a Car”.
Inner Functions
2.Inner functions can refer to variables defined in
outer functions even after the latter have returned.
The code may seem similar to the one in the first
point. But here printData() is returned inside the
outer setData() function, instead of being immediately
called. So, the value of currentData is the
inner printData() function.
3. Inner functions store their outer
function’s variables by reference, not
by value
Here, carData() returns an object
containing two closures,get() and set(),
and they both refer to the outer
variable Car. While get()obtains the
current value of Car, set()updates it.
When myCar.get() is called for the second
time, it prints the updated value of Car –
“Mercedes” – rather than the previous
value “Audi”.
Closure Features
Closures have another very interesting features which is that the variables in
a closure are automatically hidden. Closures store data in their enclosed
variables without providing direct access to them. The only way to alter
those variables is by providing access to them indirectly. For example, in the
last code snippet, we saw that we can modify the variable Car only obliquely
by using the get() and set() closures.
Loops
Looping is something that tends to take a toll on everyone. When loops are
not written correctly, we are left with weird outputs. Let’s look at one such
example where a loop produces a confusing result.
Running the code snippet should give us the output as:
0 1 2
But instead our output will be:
3 3 3
JavaScript is single-threaded so it keeps an event queue where it queues up
things to do. The closure created in each loop iteration is queued to run as
soon as the rest of the current execution context finishes and CPU time is
returned to the event loop. setTimeout here serves to simply defer the
execution of each closure until after the loop finishes running. By that point,
the final value of i is ‘3’.
Solution to over come the problem
We can use closures to overcome this problem. In the following code
snippet, we make use of a closure by defining nested functions.
The code prints the desired output, which is:
0 1 2
If you already have a loop that you don’t want to convert to use an
iterator function, all you have to do is wrap your closure inside
another closure in which you define new variables which capture
the current value of the variables that change on each iteration.
The trick to capturing the variables is to make sure your outer
closure executes immediately during the current iteration of the
loop. Now the above code snippet will produce the desired result!
Hoisting
Hoisting is employed to explain how Variables and Function declarations are ‘lifted’ to the top of a
function or a global scope. A JavaScript interpreter performs many things behind the scene, and one
of them is called hoisting.
The best way of thinking about the behavior of JavaScript variables is to always visualize them as
consisting of two parts: a declaration and an assignment.
var state; // variable declaration
state = "ready"; // variable definition (assignment)
var state = "ready"; // declaration plus definition
Declarations & Definition
To understand why the concept of function declarations and definitions
getting pushed to the top and assignments staying is important, let’s
consider a simple example.
• At first look, this piece of code makes no sense, for the simple reason
that not only is the variable state being print even before it is declared
but also the function hoisting()is being called before it is even defined.
Normally Line 1 should throw an error since state as it is not even
declared yet.
• Also, why is the statement at Line 9 printing undefined even though the
variable stateis already declared at Line 3?
Types of execution context
There are two major types of execution contexts in JavaScript —Global execution context and Function
execution context.
Since JavaScript is based on a single-threaded execution model, only one piece of code can be
executed at a time. For our code, the process is as follows :
While the execution context keeps
track of the execution of the code,
Lexical environment keeps track of the
mapping of identifiers to specific
variables.
Lexical environment
• Lexical environment basically is an internal implementation of the JavaScript scoping mechanism.
• Generally, the lexical environment is associated with a specific structure of the JavaScript code. For
example, a function or a block of code like a forloop. Whenever a function is created, a reference to
the lexical environment in which it was created is passed internal property named [[Environment]].
• So in our code example, the first time we print the value of the state, it does not throw an error
because internally JavaScript has already assigned an identifier to it, which is not assigned any
value. So it prints undefined The second time it is called, it again prints undefined because now it is
in the hoisting()execution context and not in the global execution context. In this context, the
variable state is still undefined.
Change of Code
• Now let’s change our preceding code a bit.
This time we print the value of the
variable state before hoisting() .
• This time, our code prints Ready instead
of undefined. As we learned in the earlier
section, this happens because now we are
in the global execution context and not in
Hoisting’s function execution context.
Things to remember
• Both function and variable declarations are hoisted to the top of the
containing scope, before any part of our code is executed.
• Functions are hoisted first, and then variables.
• Function declarations have priority over variable declarations, but not
over variable assignments.
Conclusion
JavaScript developers often face these issues, but fail to grasp the
reason behind the unexpected behavior. Through this presentation, we
tried to clear some of the myths and ambiguities that a developer often
comes across while dealing with Closures and Hoisting.
THANK
YOU

Mais conteúdo relacionado

Mais procurados

Learn VbScript -String Functions
Learn VbScript -String FunctionsLearn VbScript -String Functions
Learn VbScript -String FunctionsNilanjan Saha
 
The Function Pointer Tutorials
The Function Pointer TutorialsThe Function Pointer Tutorials
The Function Pointer TutorialsNont Banditwong
 
Functors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaFunctors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaKnoldus Inc.
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++gourav kottawar
 
What is storage class
What is storage classWhat is storage class
What is storage classIsha Aggarwal
 
Intorudction into VBScript
Intorudction into VBScriptIntorudction into VBScript
Intorudction into VBScriptVitaliy Ganzha
 
Virtual function complete By Abdul Wahab (moon sheikh)
Virtual function complete By Abdul Wahab (moon sheikh)Virtual function complete By Abdul Wahab (moon sheikh)
Virtual function complete By Abdul Wahab (moon sheikh)MoonSheikh1
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 FunctionDeepak Singh
 
Inline function
Inline functionInline function
Inline functionTech_MX
 
7400354 vbscript-in-qtp
7400354 vbscript-in-qtp7400354 vbscript-in-qtp
7400354 vbscript-in-qtpBharath003
 
INLINE FUNCTION IN C++
INLINE FUNCTION IN C++INLINE FUNCTION IN C++
INLINE FUNCTION IN C++Vraj Patel
 
Notes: Verilog Part 2 - Modules and Ports - Structural Modeling (Gate-Level M...
Notes: Verilog Part 2 - Modules and Ports - Structural Modeling (Gate-Level M...Notes: Verilog Part 2 - Modules and Ports - Structural Modeling (Gate-Level M...
Notes: Verilog Part 2 - Modules and Ports - Structural Modeling (Gate-Level M...Jay Baxi
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingArunaDevi63
 
Data Type Conversion in C++
Data Type Conversion in C++Data Type Conversion in C++
Data Type Conversion in C++Danial Mirza
 
Data structure scope of variables
Data structure scope of variablesData structure scope of variables
Data structure scope of variablesSaurav Kumar
 

Mais procurados (20)

Learn VbScript -String Functions
Learn VbScript -String FunctionsLearn VbScript -String Functions
Learn VbScript -String Functions
 
The Function Pointer Tutorials
The Function Pointer TutorialsThe Function Pointer Tutorials
The Function Pointer Tutorials
 
Function pointer
Function pointerFunction pointer
Function pointer
 
85ec7 session2 c++
85ec7 session2 c++85ec7 session2 c++
85ec7 session2 c++
 
Functors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaFunctors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In Scala
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
 
What is storage class
What is storage classWhat is storage class
What is storage class
 
Intorudction into VBScript
Intorudction into VBScriptIntorudction into VBScript
Intorudction into VBScript
 
Virtual function complete By Abdul Wahab (moon sheikh)
Virtual function complete By Abdul Wahab (moon sheikh)Virtual function complete By Abdul Wahab (moon sheikh)
Virtual function complete By Abdul Wahab (moon sheikh)
 
Qtp - Introduction to fundamentals of vbscript
Qtp - Introduction to fundamentals of vbscriptQtp - Introduction to fundamentals of vbscript
Qtp - Introduction to fundamentals of vbscript
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 Function
 
Vbscript
VbscriptVbscript
Vbscript
 
VB Script Overview
VB Script OverviewVB Script Overview
VB Script Overview
 
Inline function
Inline functionInline function
Inline function
 
7400354 vbscript-in-qtp
7400354 vbscript-in-qtp7400354 vbscript-in-qtp
7400354 vbscript-in-qtp
 
INLINE FUNCTION IN C++
INLINE FUNCTION IN C++INLINE FUNCTION IN C++
INLINE FUNCTION IN C++
 
Notes: Verilog Part 2 - Modules and Ports - Structural Modeling (Gate-Level M...
Notes: Verilog Part 2 - Modules and Ports - Structural Modeling (Gate-Level M...Notes: Verilog Part 2 - Modules and Ports - Structural Modeling (Gate-Level M...
Notes: Verilog Part 2 - Modules and Ports - Structural Modeling (Gate-Level M...
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Data Type Conversion in C++
Data Type Conversion in C++Data Type Conversion in C++
Data Type Conversion in C++
 
Data structure scope of variables
Data structure scope of variablesData structure scope of variables
Data structure scope of variables
 

Semelhante a Javascripts hidden treasures BY - https://geekyants.com/

Basic construction of c
Basic construction of cBasic construction of c
Basic construction of ckinish kumar
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptAmanuelZewdie4
 
Library management system
Library management systemLibrary management system
Library management systemSHARDA SHARAN
 
Storage Class Specifiers in C++
Storage Class Specifiers in C++Storage Class Specifiers in C++
Storage Class Specifiers in C++Reddhi Basu
 
Web technologies-course 12.pptx
Web technologies-course 12.pptxWeb technologies-course 12.pptx
Web technologies-course 12.pptxStefan Oprea
 
1669958779195.pdf
1669958779195.pdf1669958779195.pdf
1669958779195.pdfvenud11
 
Operator Overloading and Scope of Variable
Operator Overloading and Scope of VariableOperator Overloading and Scope of Variable
Operator Overloading and Scope of VariableMOHIT DADU
 
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...NicheTech Com. Solutions Pvt. Ltd.
 
379008-rc217-functionalprogramming
379008-rc217-functionalprogramming379008-rc217-functionalprogramming
379008-rc217-functionalprogrammingLuis Atencio
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptxmiki304759
 
Fundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfFundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfStephieJohn
 
Android Application Development - Level 3
Android Application Development - Level 3Android Application Development - Level 3
Android Application Development - Level 3Isham Rashik
 
Password protected diary
Password protected diaryPassword protected diary
Password protected diarySHARDA SHARAN
 
Mastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_argumentsMastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_argumentsRuth Marvin
 
Memento Pattern Implementation
Memento Pattern ImplementationMemento Pattern Implementation
Memento Pattern ImplementationSteve Widom
 
Latest C Interview Questions and Answers
Latest C Interview Questions and AnswersLatest C Interview Questions and Answers
Latest C Interview Questions and AnswersDaisyWatson5
 
Contact management system
Contact management systemContact management system
Contact management systemSHARDA SHARAN
 

Semelhante a Javascripts hidden treasures BY - https://geekyants.com/ (20)

Basic construction of c
Basic construction of cBasic construction of c
Basic construction of c
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.ppt
 
Library management system
Library management systemLibrary management system
Library management system
 
Storage Class Specifiers in C++
Storage Class Specifiers in C++Storage Class Specifiers in C++
Storage Class Specifiers in C++
 
Web technologies-course 12.pptx
Web technologies-course 12.pptxWeb technologies-course 12.pptx
Web technologies-course 12.pptx
 
1669958779195.pdf
1669958779195.pdf1669958779195.pdf
1669958779195.pdf
 
Operator Overloading and Scope of Variable
Operator Overloading and Scope of VariableOperator Overloading and Scope of Variable
Operator Overloading and Scope of Variable
 
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
 
379008-rc217-functionalprogramming
379008-rc217-functionalprogramming379008-rc217-functionalprogramming
379008-rc217-functionalprogramming
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptx
 
Fundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfFundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdf
 
Functional Programming in Java
Functional Programming in JavaFunctional Programming in Java
Functional Programming in Java
 
Android Application Development - Level 3
Android Application Development - Level 3Android Application Development - Level 3
Android Application Development - Level 3
 
FUNCTION CPU
FUNCTION CPUFUNCTION CPU
FUNCTION CPU
 
Password protected diary
Password protected diaryPassword protected diary
Password protected diary
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
 
Mastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_argumentsMastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_arguments
 
Memento Pattern Implementation
Memento Pattern ImplementationMemento Pattern Implementation
Memento Pattern Implementation
 
Latest C Interview Questions and Answers
Latest C Interview Questions and AnswersLatest C Interview Questions and Answers
Latest C Interview Questions and Answers
 
Contact management system
Contact management systemContact management system
Contact management system
 

Último

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 

Último (20)

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 

Javascripts hidden treasures BY - https://geekyants.com/

  • 1. JavaScript’s Hidden Treasures : Closures and Hoisting By Geekyants
  • 2. INTRODUCTION JavaScript possesses many hidden features that can often make us feel confused and bewildered. Let’s demystify two of them. 1. Closures 2. Hoisting
  • 3. Closures We encounter closures several times while coding in JavaScript. So it’s quite necessary to understand what they actually signify. Let’s first zip through some formal definitions. What is a closure? • A closure is a function that has access to the parent scope, even after the scope has returned we can also define it as: • A closure is the combination of a function and the lexical environment within which that function was declared.
  • 4. Scope The Scope is essentially the lifespan of a variable in JavaScript. Where a variable is defined plays a large role in how long that variable is around, and which functions in your program have access to it. So it would be safe to say that any function can be considered a closure because a function can refer to or have access to: • Any variable or parameter in its own function scope. • Any variable or parameters of its outer (parent) functions. • Any variable from the global scope.
  • 5. Definition of closure into 3 parts. 1.We can refer to variables defined outside of the current function. Here, the printData() function refers to the type variable and the model parameter of the enclosing function setData(). So when setData() is called, printData()uses the variables and parameters of the former to print the output “Audi is a Car”.
  • 6. Inner Functions 2.Inner functions can refer to variables defined in outer functions even after the latter have returned. The code may seem similar to the one in the first point. But here printData() is returned inside the outer setData() function, instead of being immediately called. So, the value of currentData is the inner printData() function.
  • 7. 3. Inner functions store their outer function’s variables by reference, not by value Here, carData() returns an object containing two closures,get() and set(), and they both refer to the outer variable Car. While get()obtains the current value of Car, set()updates it. When myCar.get() is called for the second time, it prints the updated value of Car – “Mercedes” – rather than the previous value “Audi”.
  • 8. Closure Features Closures have another very interesting features which is that the variables in a closure are automatically hidden. Closures store data in their enclosed variables without providing direct access to them. The only way to alter those variables is by providing access to them indirectly. For example, in the last code snippet, we saw that we can modify the variable Car only obliquely by using the get() and set() closures.
  • 9. Loops Looping is something that tends to take a toll on everyone. When loops are not written correctly, we are left with weird outputs. Let’s look at one such example where a loop produces a confusing result. Running the code snippet should give us the output as: 0 1 2 But instead our output will be: 3 3 3 JavaScript is single-threaded so it keeps an event queue where it queues up things to do. The closure created in each loop iteration is queued to run as soon as the rest of the current execution context finishes and CPU time is returned to the event loop. setTimeout here serves to simply defer the execution of each closure until after the loop finishes running. By that point, the final value of i is ‘3’.
  • 10. Solution to over come the problem We can use closures to overcome this problem. In the following code snippet, we make use of a closure by defining nested functions. The code prints the desired output, which is: 0 1 2 If you already have a loop that you don’t want to convert to use an iterator function, all you have to do is wrap your closure inside another closure in which you define new variables which capture the current value of the variables that change on each iteration. The trick to capturing the variables is to make sure your outer closure executes immediately during the current iteration of the loop. Now the above code snippet will produce the desired result!
  • 11. Hoisting Hoisting is employed to explain how Variables and Function declarations are ‘lifted’ to the top of a function or a global scope. A JavaScript interpreter performs many things behind the scene, and one of them is called hoisting. The best way of thinking about the behavior of JavaScript variables is to always visualize them as consisting of two parts: a declaration and an assignment. var state; // variable declaration state = "ready"; // variable definition (assignment) var state = "ready"; // declaration plus definition
  • 12. Declarations & Definition To understand why the concept of function declarations and definitions getting pushed to the top and assignments staying is important, let’s consider a simple example. • At first look, this piece of code makes no sense, for the simple reason that not only is the variable state being print even before it is declared but also the function hoisting()is being called before it is even defined. Normally Line 1 should throw an error since state as it is not even declared yet. • Also, why is the statement at Line 9 printing undefined even though the variable stateis already declared at Line 3?
  • 13. Types of execution context There are two major types of execution contexts in JavaScript —Global execution context and Function execution context. Since JavaScript is based on a single-threaded execution model, only one piece of code can be executed at a time. For our code, the process is as follows : While the execution context keeps track of the execution of the code, Lexical environment keeps track of the mapping of identifiers to specific variables.
  • 14. Lexical environment • Lexical environment basically is an internal implementation of the JavaScript scoping mechanism. • Generally, the lexical environment is associated with a specific structure of the JavaScript code. For example, a function or a block of code like a forloop. Whenever a function is created, a reference to the lexical environment in which it was created is passed internal property named [[Environment]]. • So in our code example, the first time we print the value of the state, it does not throw an error because internally JavaScript has already assigned an identifier to it, which is not assigned any value. So it prints undefined The second time it is called, it again prints undefined because now it is in the hoisting()execution context and not in the global execution context. In this context, the variable state is still undefined.
  • 15. Change of Code • Now let’s change our preceding code a bit. This time we print the value of the variable state before hoisting() . • This time, our code prints Ready instead of undefined. As we learned in the earlier section, this happens because now we are in the global execution context and not in Hoisting’s function execution context.
  • 16. Things to remember • Both function and variable declarations are hoisted to the top of the containing scope, before any part of our code is executed. • Functions are hoisted first, and then variables. • Function declarations have priority over variable declarations, but not over variable assignments.
  • 17. Conclusion JavaScript developers often face these issues, but fail to grasp the reason behind the unexpected behavior. Through this presentation, we tried to clear some of the myths and ambiguities that a developer often comes across while dealing with Closures and Hoisting.