Introduction
Namaste, In this blog I will discuss 10 code scenarios on Javascript const keyword .
Identify the output of the below program
const myval = "Hari"; const myval =12; console.log(myval);
a. error
b.Hari
c.12
d.null
e.undefined
Answer:a
Reason:The const variable cannot be re-declared.
Identify the output of the below program
let myval=10; if (myval > 6) { const myval2=11; } console.log(myval2);
a.10
b.11
c.error
d.undefined
e.error
Answer:c
Reason:The const variable has block scope.
Identify the output of the below program
console.log("myval3", myval3); const myval3=12;
a.12
b.undefined
c.null
d.error
e.nothing
Answer:d
Reason:The const variable is not hoisted
Identify the output of the below program
const obj = { no:10 }; obj = 100; console.log(obj);
a.10
b.100
c. {no:10}
d. {obj:100}
e.error
Answer: e
Reason: The const object cannot be updated
Identify the output of the below program
const myval=10; myval = "ram"; console.log(myval)
a.10
b.ram
c.error
d.undefined
e.null
Answer:c
Reason:The const variable cannot be re-initialised
Identify the output of the below program
let myval=10; function fx() { if (myval > 6) { const myval4=8; } console.log("myval 4", myval4); } fx();
a.10
b.8
c.6
d.error
e.undefined
Answer:d
Reason:The const variable has block scope
Identify the output of the below program
const obj = { no:10 }; obj.no = 200; console.log(obj.no);
a.10
b.200
c.undefined
d.error
e.null
Answer:b
Reason:Only the object is constant not it's properties
Identify the output of the below program
const i=10; const function fx() { i=20; return i; } console.log(fx());
a.error
b.10
c.20
d.undefined
e.null
Answer:a
Reason:Function cannot be declared as const
Identify the output of the below program
var i=20; const i=10; console.log(i);
a.10
b.20
c.error
d.no output
e.undefined
Answer:c
Reason:The variable i is already declared hence cannot be re-declared
Identify the output of the below program
const obj = { no:10, name: "Ram" }; obj.name = "Gopi"; console.log(obj.name);
a.Gopi
b.Ram
c.10
d.no output
e.error
Answer:a
Reason: The const object properties can be updated