Test your JavaScript Skills:Fundamentals-7

Photo by Jess Bailey on Unsplash

Test your JavaScript Skills:Fundamentals-7

Part 7

Introduction

Namaste, In this blog I will discuss 7 code scenarios on Javascript fundamentals.

Video Tutorial

  1. Identify the output of the below program

     function fx() {
         for (var i=0; i< 3;) {
             i++;
         }
      console.log("value", i);
     }
     fx();
    

    a.3

    b.4

    c.NaN

    d. undefined

    e.error

    Answer: a

    Reason: Since var does not have block scope it can be accessed outside for loop.

  2. Identify the output of the below program

     function fx() {
         for (var i=0; i< 3;) {
             i++;
         }
    
     }
     fx();
     console.log("value", i);
    

    a.3

    b.4

    c.error

    d. undefined

    e.NaN

    Answer: c

    Reason: The scope of 'var' is limited to function fx hence cannot be accessed outside the function.

  3. Identify the output of the below program

     function fx() {
         var i=10;
         console.log("value", j);
         if (i > 3)
           var j=5;
    
     }
     fx();
    

    a.error

    b.5

    c.3

    d. NaN

    e.undefined

    Answer: e

    Reason: The variable 'j' is hoisted.

  4. Identify the output of the below program

     function fx() {
         var i=10;
         console.log("value", j);
         if (i > 32)
           var j=5;
    
     }
     fx();
    

    a.5

    b.10

    c.error

    d. undefined

    e.NaN

    Answer: d

    Reason: The variable 'j' is hoisted hence it is undefined. It should be noted that the condition (i>32) is false still the hoisting still happens.

  5. Identify the output of the below program

     try {
      var i=10;
     }catch (e) {
         console.log("catch");
     }
    
     console.log("value", i);
    

    a.error

    b.10

    c.undefined

    d. NaN

    e.0

    Answer: b

    Reason: The 'var' does not have a block scope and hence can be accessed outside.

  6. Identify the output of the below program

    
     function fx2() {
         var data=102;     
          function fx3() {
              console.log("value",data); 
          }
          fx3();
     }
    
     fx2();
    

    a.102

    b.error

    c.undefined

    d. NaN

    e.null

    Answer: a

    Reason: Since variable 'data' is global in the context of function fx3 it can be accessed inside function fx3.

  7. Identify the output of the below program

     function fx2() {    
          function fx3() {
              console.log("value",data); 
          }
          fx3();
          var data=102;
     }
     fx2();
    

    a.102

    b.error

    c.undefined

    d. null

    e.NaN

    Answer: c

    Reason: The variable is hoisted hence it is accessible inside function fx3.

Video Tutorial

Did you find this article valuable?

Support Programming with Mahavir by becoming a sponsor. Any amount is appreciated!