Table of contents
Introduction
Namaste, In this blog I will discuss 8 code scenarios on Javascript : var keyword .
Identify the output of the below program
console.log(myval); var myval=4;
a.4
b.null
c.undefined
d.error
e. no output
Answer:c
Reason:The var variable is hoisted
Identify the output of the below program
var i=10; var i=12; console.log(i);
a.10
b.12
c.Error
d.undefined
e.null
Answer:b
Reason:Variable declared can be re-declared
Identify the output of the below program
function fx() { console.log(fxval); var fxval=123; } fx();
a.123
b.null
c. no output
d.undefined
e.error
Answer:d
Reason:The var variable is hoisted
Identify the output of the below program
for (var a=10;a<15;a++) { a++; } console.log(a);
a.undefined
b.15
c.16
d.17
e.error
Answer:c
Reason:The var variable does not have block scope hence can be accessed outside
Identify the output of the below program
function fx3() { try { var d=20; }catch(e) { console.log(e); } console.log(d); } fx3();
a.Error
b.20
c. no output
d.undefined
e.0
Answer:b
Reason:The var variable does not have block scope
Identify the output of the below program
let i=10; if ( i > 9){ var c = 13; } console.log(c);
a.10
b.9
c.13
d.error
e.undefined
Answer:c
Reason:The var variable does not have block scope
Identify the output of the below program
var i=10; let i=12; console.log("i:", i);
a.10
b.12
c.Error
d.Undefined
e.11
Answer: c
Reason: A variable once declared cannot be re-declared using let
Identify the output of the below program
function fx3() { try { var d=20; throw new Error("Test"); }catch(e) { console.log(d); } } fx3();
a.20
b.Error
c.Undefined
d. No output
e.null
Answer:a
Reason:The var variable does not have block scope