SlideShare a Scribd company logo
Scoping and functions in
Javascript
 Aditya Gaur         Mentor: Apurba Nath
Why Scope?
   Controls the visibility of variables and
    parameters

   A programmer should know about scope to
    prevent naming collisions and ambiguity
Why Scope in Javascript?
   Javascript is NOT “s ome othe r la ngua ge ”

   Unlike other languages like C, C++,
    Javascript does not support bloc k le ve l
    s c ope

   Supports function level scope
Block level scope ?

        var a =10 ;      Output 20
        if(true){
           var a = 20;
        }
        alert(a);


        var a =10 ;      Output 10
        function
        randomFunc(){
           var a = 20;
        }
        randomFunc();
        alert(a);
Declaration and Definition

          var someVar = 10;



            is broken into


        var someVar=undefined;

        someVar =10;
Declaration and Definition

      function someFunc(){
          //some random statements
          var aVar = 10;
          //some more random statements
      }

            is converted to
      function someFunc(){
          var aVar = undefined
          //some random statements
          aVar = 10;
          //some more random statements
      }
The var

      function Dummy(){                          Output: Error- privateProperty is not
         var privateProperty = 10;               defined
      }
      alert (privateProperty);




      function Dummy(){                          Output: 10
         isItPrivate = 10;
      }
      alert(isItPrivate);

So what's happening? Actually the keyword var defines the scope of the variable. If
we don't give the keyword var then it is assigned to the window object
The eval function

eval("var a=10");                   Output: 10
alert(a);



function someFunc(){                Output: 10
   eval("var a=10");                         'a' is not defined
   alert(a);
}
someFunc();
alert(a);


Variables declared in the eval have the scope in which they are
called.
this is tricky
   It is one of the most important concept
    to grasp in javascript
   Its value depends in the way the function
    has been called.
   A function can be called in the following
    ways:
    –   As a method
    –   As function invocation
    –   As a constructor
    –   In apply invocation
1. Function as a method

var aVar=10;                Output: 40
var obj= {
    aVar: 40,
   show: function(){
      alert(this.aVar);
   }
};
obj.show();



this is bound to the object from which the method is
invoked.
2. function invocation

var aVar=10;                 Output: 10
function someFunc(){
  var aVar =40;
  alert(this.aVar);
}
someFunc();


Here the value of this is bound to the global object.
3. function as a constructor

 function Dummy(){                               Output: undefined
    var privateProperty = 10;
 }
 var dummyObject = new Dummy();
 alert(dummyObject.privateProperty);


function Dummy(){                                 Output: 10
   this.publicProperty = 10;
}
var dummyObject = new Dummy();
alert(dummyObject.publicProperty);


this is bound to the new object being created so it is accessible through the
object.
Privileged method

   function Dummy() {
      var privateProperty = 10;
      this.privilegedMethod = function() {
         return privateProperty;
      };
   }
   var dummyObject = new Dummy();
   alert(dummyObject.privilegedMethod());
4. function in apply invocation

    var obj = { x: 15 };
     function dummy(message)
    {
       alert(message);
       alert(this.x);
    }
    dummy.apply(obj, ["invoking dummy through apply"]);

    Output: invoking dummy through apply
           15




Here the value of this is bound to the scope passed as the first argument in the
apply function
A catch

function Dummy()
{
   return function (){
     alert (this);
  }();
}
var dummyObject = new Dummy();


Here this refers to the global object. Why?
The anonymous function here is executed immediately thus it is just like the
function invocation and in function invocation this refers to the global window
object
A fix

 function Dummy()
 {
   var that = this;
       return function (){
         alert (that);
   }();
 }
 var dummyObject = new Dummy();



Now we have the correct behaviour. This is possible because javascript
supports function closure.
Current and Future Work
   Working on
     – JSDocs – for the documentation
     – Integrated JSdocs in the build of the
       mVisualizer
   For unit testing would work either on
     – JSUnit
     – YUI test
Current and Future Work
References
   Javascript: the good parts by Douglas
    Crockford
   YUI theater videos by Douglas Crockford
Thank You

More Related Content

PPTX
Pro typescript.ch03.Object Orientation in TypeScript
PDF
Welcome to Modern C++
PPT
Lecture16
PDF
CppCat Checks OpenMW: Not All is Fine in the Morrowind Universe
PPTX
exception handling in cpp
PPT
Exception handling
PPT
Handling Exceptions In C & C++[Part A]
PPTX
03loop conditional statements
Pro typescript.ch03.Object Orientation in TypeScript
Welcome to Modern C++
Lecture16
CppCat Checks OpenMW: Not All is Fine in the Morrowind Universe
exception handling in cpp
Exception handling
Handling Exceptions In C & C++[Part A]
03loop conditional statements

What's hot (20)

PPT
Lecture04
PDF
Exception Handling in the C++ Constructor
PDF
What's up with Prototype and script.aculo.us?
PPTX
JS Frameworks Day April,26 of 2014
PDF
Js fwdays unit tesing javascript(by Anna Khabibullina)
PPT
Exceptions in c++
PDF
Async js - Nemetschek Presentaion @ HackBulgaria
PDF
C++ exception handling
PDF
EXCEPTION HANDLING in C++
PPTX
Exception handling chapter15
PPTX
Алексей Кутумов, Вектор с нуля
PPT
Javascript Design Patterns
PDF
Javascript & Ajax Basics
PPT
Handling Exceptions In C & C++ [Part B] Ver 2
PPTX
Exception handling
PDF
The Future of JavaScript (Ajax Exp '07)
PDF
Swift で JavaScript 始めませんか? #iOSDC
PDF
Architecture for Massively Parallel HDL Simulations
PDF
N Things You Don't Want to Repeat in React Native
PPTX
soscon2018 - Tracing for fun and profit
Lecture04
Exception Handling in the C++ Constructor
What's up with Prototype and script.aculo.us?
JS Frameworks Day April,26 of 2014
Js fwdays unit tesing javascript(by Anna Khabibullina)
Exceptions in c++
Async js - Nemetschek Presentaion @ HackBulgaria
C++ exception handling
EXCEPTION HANDLING in C++
Exception handling chapter15
Алексей Кутумов, Вектор с нуля
Javascript Design Patterns
Javascript & Ajax Basics
Handling Exceptions In C & C++ [Part B] Ver 2
Exception handling
The Future of JavaScript (Ajax Exp '07)
Swift で JavaScript 始めませんか? #iOSDC
Architecture for Massively Parallel HDL Simulations
N Things You Don't Want to Repeat in React Native
soscon2018 - Tracing for fun and profit
Ad

Similar to Javascript scoping (20)

PPTX
Object oriented java script
PDF
java script functions, classes
PPT
Object Oriented JavaScript
PPTX
Lecture 4- Javascript Function presentation
PDF
The mighty js_function
PPTX
11_Functions_Introduction.pptx javascript notes
PPTX
Javascript functions
PPT
JavaScript Introductin to Functions
PDF
Javascript foundations: Function modules
PPTX
Javascript for the c# developer
PDF
Javascript basic course
PPT
JavaScript - Programming Languages course
PPT
Basic Javascript
KEY
The JavaScript Programming Primer
PDF
JavaScript Execution Context
PDF
Let's JavaScript
PPT
JavaScript Functions
PDF
Java scriptconfusingbits
PDF
Java scriptconfusingbits
Object oriented java script
java script functions, classes
Object Oriented JavaScript
Lecture 4- Javascript Function presentation
The mighty js_function
11_Functions_Introduction.pptx javascript notes
Javascript functions
JavaScript Introductin to Functions
Javascript foundations: Function modules
Javascript for the c# developer
Javascript basic course
JavaScript - Programming Languages course
Basic Javascript
The JavaScript Programming Primer
JavaScript Execution Context
Let's JavaScript
JavaScript Functions
Java scriptconfusingbits
Java scriptconfusingbits
Ad

Recently uploaded (20)

PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
Machine Learning_overview_presentation.pptx
PDF
Encapsulation theory and applications.pdf
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
cuic standard and advanced reporting.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Machine Learning_overview_presentation.pptx
Encapsulation theory and applications.pdf
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Unlocking AI with Model Context Protocol (MCP)
gpt5_lecture_notes_comprehensive_20250812015547.pdf
The AUB Centre for AI in Media Proposal.docx
sap open course for s4hana steps from ECC to s4
Review of recent advances in non-invasive hemoglobin estimation
Per capita expenditure prediction using model stacking based on satellite ima...
Advanced methodologies resolving dimensionality complications for autism neur...
“AI and Expert System Decision Support & Business Intelligence Systems”
Programs and apps: productivity, graphics, security and other tools
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
MYSQL Presentation for SQL database connectivity
cuic standard and advanced reporting.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?

Javascript scoping

  • 1. Scoping and functions in Javascript Aditya Gaur Mentor: Apurba Nath
  • 2. Why Scope?  Controls the visibility of variables and parameters  A programmer should know about scope to prevent naming collisions and ambiguity
  • 3. Why Scope in Javascript?  Javascript is NOT “s ome othe r la ngua ge ”  Unlike other languages like C, C++, Javascript does not support bloc k le ve l s c ope  Supports function level scope
  • 4. Block level scope ? var a =10 ; Output 20 if(true){ var a = 20; } alert(a); var a =10 ; Output 10 function randomFunc(){ var a = 20; } randomFunc(); alert(a);
  • 5. Declaration and Definition var someVar = 10; is broken into var someVar=undefined; someVar =10;
  • 6. Declaration and Definition function someFunc(){ //some random statements var aVar = 10; //some more random statements } is converted to function someFunc(){ var aVar = undefined //some random statements aVar = 10; //some more random statements }
  • 7. The var function Dummy(){ Output: Error- privateProperty is not var privateProperty = 10; defined } alert (privateProperty); function Dummy(){ Output: 10 isItPrivate = 10; } alert(isItPrivate); So what's happening? Actually the keyword var defines the scope of the variable. If we don't give the keyword var then it is assigned to the window object
  • 8. The eval function eval("var a=10"); Output: 10 alert(a); function someFunc(){ Output: 10 eval("var a=10"); 'a' is not defined alert(a); } someFunc(); alert(a); Variables declared in the eval have the scope in which they are called.
  • 9. this is tricky  It is one of the most important concept to grasp in javascript  Its value depends in the way the function has been called.  A function can be called in the following ways: – As a method – As function invocation – As a constructor – In apply invocation
  • 10. 1. Function as a method var aVar=10; Output: 40 var obj= { aVar: 40, show: function(){ alert(this.aVar); } }; obj.show(); this is bound to the object from which the method is invoked.
  • 11. 2. function invocation var aVar=10; Output: 10 function someFunc(){ var aVar =40; alert(this.aVar); } someFunc(); Here the value of this is bound to the global object.
  • 12. 3. function as a constructor function Dummy(){ Output: undefined var privateProperty = 10; } var dummyObject = new Dummy(); alert(dummyObject.privateProperty); function Dummy(){ Output: 10 this.publicProperty = 10; } var dummyObject = new Dummy(); alert(dummyObject.publicProperty); this is bound to the new object being created so it is accessible through the object.
  • 13. Privileged method function Dummy() { var privateProperty = 10; this.privilegedMethod = function() { return privateProperty; }; } var dummyObject = new Dummy(); alert(dummyObject.privilegedMethod());
  • 14. 4. function in apply invocation var obj = { x: 15 }; function dummy(message) { alert(message); alert(this.x); } dummy.apply(obj, ["invoking dummy through apply"]); Output: invoking dummy through apply 15 Here the value of this is bound to the scope passed as the first argument in the apply function
  • 15. A catch function Dummy() { return function (){ alert (this); }(); } var dummyObject = new Dummy(); Here this refers to the global object. Why? The anonymous function here is executed immediately thus it is just like the function invocation and in function invocation this refers to the global window object
  • 16. A fix function Dummy() { var that = this; return function (){ alert (that); }(); } var dummyObject = new Dummy(); Now we have the correct behaviour. This is possible because javascript supports function closure.
  • 17. Current and Future Work  Working on – JSDocs – for the documentation – Integrated JSdocs in the build of the mVisualizer  For unit testing would work either on – JSUnit – YUI test
  • 19. References  Javascript: the good parts by Douglas Crockford  YUI theater videos by Douglas Crockford