3
Most read
5
Most read
6
Most read
JavaScript
Execution Context (EC)
        Closures
     "this" keyword
 ...and other demons
Some key concepts

● JS is a high-level programming language
● Executed at runtime
● Weakly typed
● Prototype-based
   ○ Class-less
   ○ Inheritance through cloning of objects then...
   ○ Delegation from the prototype

var globant = {arg: 1500, uru: 150, col: 50};
var agency = {world: 1800};
agency.__proto__ = globant;
alert(agency.arg);
alert(agency.world);
What's going on here?
function outerFunc(externalArg) {
    var localVar = 100;

    function innerFunc(innerArg) {
        localVar += 100;
        return (externalArg + innerArg + localVar);
    }

    return innerFunc;
}

var globalVar = outerFunc(200);
alert(globalVar(300));
alert(globalVar(300));

globalVar = outerFunc(200);
alert(globalVar(300));
Execution Context Maxims

All the JS code runs within an   JS Code is encapsulated
Execution Context.               within a set of Objects &
                                 properties.



 Execute           code!
Execution Context Maxims

The default Execution Context   Each function( )
is the window Object.           invocation has an associated
                                Execution Context.
Execution Context Maxims

If a nested function( )is       When the control returns to
called a new EC is created      the original EC it is available
and the execution enters that   for garbage collection except
context until the               when we create a closure.
function( ) returns.



             Thus, running JavaScript code
                      generates a:
          Stack of Execution Contexts
Activation Object

● Execution Context creates an : Activation Object

  ○ Behaves as an JS Object with properties
  ○ But has NO prototype and cannot be referenced
  ○ Serves to store call( )arguments & var declarations
  ○ Let's not care about this



                                          Okay
Variable Instantiation

● Prepare the var, function(arg)declarations and
  arguments to be accessible during execution
   ○ var globant;
   ○ var rock = function(arg){ alert('rock')};
● Initially assigned null properties or 'undefined' values

● They become named properties of the
  var (Activation) Object

● The instantiated var will be interpreted against the scope of
  the current Execution Context


                                           Scope? Wait for it...
The Scope
● Each Execution Context has a Scope

● A Scope is an Activation Object
   ○ Part of the var Object

● Scopes can be chained by the JS interpreter

● The Scope chain is a native property of every
  function( )declaration
Variable Resolution

● Every time a var is called the interpreter will try to resolve it

● It resolves it against the Scope of the current EC

● It will continue upwards to the next EC until the window

● If it's not found it will return 'undefined'

● This is also a Scope chain
Textbook definition of Closures




        A "closure" is an expression (typically a
        function) that can have free variables
        together with an environment that binds
        those variables (that "closes" the expression).
Closures

If an Object (var) has no     Unless... we create a closure
remaining references once
the execution ends, it gets   ● A closure is the local
collected by the garbage        variables for a function -
collector                       kept alive after the function
                                has returned.

                              ● A closure is an Execution
                                Context which is not de-
                                allocated when the
                                function returns.
What's going on here? Closure!
function outerFunc(externalArg) {
    var localVar = 100;

    function innerFunc(innerArg) {
        localVar += 100;
        return (externalArg + innerArg + localVar);
    }

    return innerFunc;
}                                   outerFunc( ) returns a
                                    reference to innerFunc( )
var globalVar = outerFunc(200);     We declare a var that runs &
alert(globalVar(300));              holds whatever outerFunc( )
alert(globalVar(300));              returns

globalVar = outerFunc(200);         When we call globalVar(300)
alert(globalVar(300));              again, we still have access to local
                                    var defined in outerFunc( )
Another Closure example

function say778() {
    var num = 777;
    var sayAlert = function() {
        alert(num);
    }
    num++;
    return sayAlert;
}

var sayNumber = say778();
sayNumber();

alert(sayNumber);
The "this" keyword

● Gets assigned along every new Execution Context

● It always refers to the Object that the containing function(
  ) is a method of

function redColor() {
    this.color = 'red';
}

redColor();

alert(redColor.color);          //shows "undefined"
alert(window.color);            //shows "red"
Closures in jQuery
$(function() {
    var anchors = $('a');
    anchors.each(function(i, e) {
        var self = $(this);

            if($(this).text() !== 'Contact me') {
                $(this).click(function(e) {
                    var that = $(this);
                      that.css({'textDecoration' : 'underline'});
                      self.css({'color' : 'red'});
                      setTimeout(function(e) {
                          anchors
                          that.css({'color' : 'blue'});
                      }, 1000);
                });
            }
      });
});

More Related Content

PDF
JavaScript - Chapter 4 - Types and Statements
PDF
jQuery for beginners
PDF
Hibernate Presentation
PDF
NodeJS for Beginner
PDF
ReactJS presentation
PDF
Introduction to Node.js
PPTX
PDF
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
JavaScript - Chapter 4 - Types and Statements
jQuery for beginners
Hibernate Presentation
NodeJS for Beginner
ReactJS presentation
Introduction to Node.js
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...

What's hot (20)

PDF
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
PPTX
JavaScript
PPT
Core java concepts
PPTX
Javascript Execution Context Flow
PPTX
Java database connectivity with MySql
PPSX
Javascript variables and datatypes
PPTX
Java Notes by C. Sreedhar, GPREC
PPTX
Introduction to Basic Java Versions and their features
PPT
Oops in PHP
PDF
Use Node.js to create a REST API
PPT
Java Basics
PDF
What is JavaScript? Edureka
PPTX
Java Spring Framework
PPTX
Introduction Node.js
PPTX
Basic Concept of Node.js & NPM
PPT
Advanced JavaScript
PDF
Introduction to ASP.NET Core
PDF
JavaScript Programming
PPT
Oops in Java
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
JavaScript
Core java concepts
Javascript Execution Context Flow
Java database connectivity with MySql
Javascript variables and datatypes
Java Notes by C. Sreedhar, GPREC
Introduction to Basic Java Versions and their features
Oops in PHP
Use Node.js to create a REST API
Java Basics
What is JavaScript? Edureka
Java Spring Framework
Introduction Node.js
Basic Concept of Node.js & NPM
Advanced JavaScript
Introduction to ASP.NET Core
JavaScript Programming
Oops in Java
Ad

Similar to JavaScript Execution Context (20)

PDF
Javascript
PPT
Expert JavaScript tricks of the masters
PDF
Asynchronous programming done right - Node.js
PDF
Javascript: the important bits
PPT
Introduction to Javascript
PDF
Swift - One step forward from Obj-C
PPTX
Javascript
PPTX
Advanced JavaScript
PPTX
JavaScript (without DOM)
PPTX
Java script for web developer
PPTX
Using Reflections and Automatic Code Generation
PDF
The Evolution of Async-Programming (SD 2.0, JavaScript)
PDF
Think Async: Asynchronous Patterns in NodeJS
PDF
Underscore and Backbone Models
KEY
The JavaScript Programming Primer
PDF
Java scriptconfusingbits
PDF
Java scriptconfusingbits
PDF
Coding in Style
PDF
Let's JavaScript
PPTX
Kotlin Coroutines and Rx
Javascript
Expert JavaScript tricks of the masters
Asynchronous programming done right - Node.js
Javascript: the important bits
Introduction to Javascript
Swift - One step forward from Obj-C
Javascript
Advanced JavaScript
JavaScript (without DOM)
Java script for web developer
Using Reflections and Automatic Code Generation
The Evolution of Async-Programming (SD 2.0, JavaScript)
Think Async: Asynchronous Patterns in NodeJS
Underscore and Backbone Models
The JavaScript Programming Primer
Java scriptconfusingbits
Java scriptconfusingbits
Coding in Style
Let's JavaScript
Kotlin Coroutines and Rx
Ad

Recently uploaded (20)

PPT
Overviiew on Intellectual property right
PDF
Gestión Unificada de los Riegos Externos
PPTX
Rise of the Digital Control Grid Zeee Media and Hope and Tivon FTWProject.com
PDF
GDG Cloud Southlake #45: Patrick Debois: The Impact of GenAI on Development a...
PDF
State of AI in Business 2025 - MIT NANDA
PDF
Examining Bias in AI Generated News Content.pdf
PPTX
Strategic Picks — Prioritising the Right Agentic Use Cases [2/6]
PDF
Addressing the challenges of harmonizing law and artificial intelligence tech...
PDF
1_Keynote_Breaking Barriers_한계를 넘어서_Charith Mendis.pdf
PDF
The Basics of Artificial Intelligence - Understanding the Key Concepts and Te...
PPTX
Blending method and technology for hydrogen.pptx
PDF
【AI論文解説】高速・高品質な生成を実現するFlow Map Models(Part 1~3)
PDF
Domain-specific knowledge and context in large language models: challenges, c...
PDF
TrustArc Webinar - Data Minimization in Practice_ Reducing Risk, Enhancing Co...
PDF
NewMind AI Journal Monthly Chronicles - August 2025
PDF
TicketRoot: Event Tech Solutions Deck 2025
PDF
EGCB_Solar_Project_Presentation_and Finalcial Analysis.pdf
PPTX
Report in SIP_Distance_Learning_Technology_Impact.pptx
PDF
“Introduction to Designing with AI Agents,” a Presentation from Amazon Web Se...
PPTX
Introduction-to-Artificial-Intelligence (1).pptx
Overviiew on Intellectual property right
Gestión Unificada de los Riegos Externos
Rise of the Digital Control Grid Zeee Media and Hope and Tivon FTWProject.com
GDG Cloud Southlake #45: Patrick Debois: The Impact of GenAI on Development a...
State of AI in Business 2025 - MIT NANDA
Examining Bias in AI Generated News Content.pdf
Strategic Picks — Prioritising the Right Agentic Use Cases [2/6]
Addressing the challenges of harmonizing law and artificial intelligence tech...
1_Keynote_Breaking Barriers_한계를 넘어서_Charith Mendis.pdf
The Basics of Artificial Intelligence - Understanding the Key Concepts and Te...
Blending method and technology for hydrogen.pptx
【AI論文解説】高速・高品質な生成を実現するFlow Map Models(Part 1~3)
Domain-specific knowledge and context in large language models: challenges, c...
TrustArc Webinar - Data Minimization in Practice_ Reducing Risk, Enhancing Co...
NewMind AI Journal Monthly Chronicles - August 2025
TicketRoot: Event Tech Solutions Deck 2025
EGCB_Solar_Project_Presentation_and Finalcial Analysis.pdf
Report in SIP_Distance_Learning_Technology_Impact.pptx
“Introduction to Designing with AI Agents,” a Presentation from Amazon Web Se...
Introduction-to-Artificial-Intelligence (1).pptx

JavaScript Execution Context

  • 1. JavaScript Execution Context (EC) Closures "this" keyword ...and other demons
  • 2. Some key concepts ● JS is a high-level programming language ● Executed at runtime ● Weakly typed ● Prototype-based ○ Class-less ○ Inheritance through cloning of objects then... ○ Delegation from the prototype var globant = {arg: 1500, uru: 150, col: 50}; var agency = {world: 1800}; agency.__proto__ = globant; alert(agency.arg); alert(agency.world);
  • 3. What's going on here? function outerFunc(externalArg) { var localVar = 100; function innerFunc(innerArg) { localVar += 100; return (externalArg + innerArg + localVar); } return innerFunc; } var globalVar = outerFunc(200); alert(globalVar(300)); alert(globalVar(300)); globalVar = outerFunc(200); alert(globalVar(300));
  • 4. Execution Context Maxims All the JS code runs within an JS Code is encapsulated Execution Context. within a set of Objects & properties. Execute code!
  • 5. Execution Context Maxims The default Execution Context Each function( ) is the window Object. invocation has an associated Execution Context.
  • 6. Execution Context Maxims If a nested function( )is When the control returns to called a new EC is created the original EC it is available and the execution enters that for garbage collection except context until the when we create a closure. function( ) returns. Thus, running JavaScript code generates a: Stack of Execution Contexts
  • 7. Activation Object ● Execution Context creates an : Activation Object ○ Behaves as an JS Object with properties ○ But has NO prototype and cannot be referenced ○ Serves to store call( )arguments & var declarations ○ Let's not care about this Okay
  • 8. Variable Instantiation ● Prepare the var, function(arg)declarations and arguments to be accessible during execution ○ var globant; ○ var rock = function(arg){ alert('rock')}; ● Initially assigned null properties or 'undefined' values ● They become named properties of the var (Activation) Object ● The instantiated var will be interpreted against the scope of the current Execution Context Scope? Wait for it...
  • 9. The Scope ● Each Execution Context has a Scope ● A Scope is an Activation Object ○ Part of the var Object ● Scopes can be chained by the JS interpreter ● The Scope chain is a native property of every function( )declaration
  • 10. Variable Resolution ● Every time a var is called the interpreter will try to resolve it ● It resolves it against the Scope of the current EC ● It will continue upwards to the next EC until the window ● If it's not found it will return 'undefined' ● This is also a Scope chain
  • 11. Textbook definition of Closures A "closure" is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).
  • 12. Closures If an Object (var) has no Unless... we create a closure remaining references once the execution ends, it gets ● A closure is the local collected by the garbage variables for a function - collector kept alive after the function has returned. ● A closure is an Execution Context which is not de- allocated when the function returns.
  • 13. What's going on here? Closure! function outerFunc(externalArg) { var localVar = 100; function innerFunc(innerArg) { localVar += 100; return (externalArg + innerArg + localVar); } return innerFunc; } outerFunc( ) returns a reference to innerFunc( ) var globalVar = outerFunc(200); We declare a var that runs & alert(globalVar(300)); holds whatever outerFunc( ) alert(globalVar(300)); returns globalVar = outerFunc(200); When we call globalVar(300) alert(globalVar(300)); again, we still have access to local var defined in outerFunc( )
  • 14. Another Closure example function say778() { var num = 777; var sayAlert = function() { alert(num); } num++; return sayAlert; } var sayNumber = say778(); sayNumber(); alert(sayNumber);
  • 15. The "this" keyword ● Gets assigned along every new Execution Context ● It always refers to the Object that the containing function( ) is a method of function redColor() { this.color = 'red'; } redColor(); alert(redColor.color); //shows "undefined" alert(window.color); //shows "red"
  • 16. Closures in jQuery $(function() { var anchors = $('a'); anchors.each(function(i, e) { var self = $(this); if($(this).text() !== 'Contact me') { $(this).click(function(e) { var that = $(this); that.css({'textDecoration' : 'underline'}); self.css({'color' : 'red'}); setTimeout(function(e) { anchors that.css({'color' : 'blue'}); }, 1000); }); } }); });