Table of contents
Introduction
Namaste, In this blog I will discuss 10 code scenarios on Javascript .
Identify the output of the below program
let obj = { name: { firstname : "ram", lastname : "kumar" } } console.log(obj.name.middlename.name);
a.undefined
b.null
c.crash
d.kumar
e.ram
Answer:c
Reason:It crashes because middlename.name does not exist on obj.name.
Identify the output of the below program
let arr =null; console.log(arr[1]);
a.null
b.undefined
c.crash
d.1
e.0
Answer:c
Reason:The program crashes because arr is initialized to null.
Identify the output of the below program
let fx = () => console.log("fx"); fx = null; fx?.();
a.null
b.fx
c.undefined
d.no output
e.crash
Answer:d
Reason: Since fx is initialized to null the function is not called (but does not crash).
Identify the output of the below program
let num = null num = num ?? 5 console.log(num)
a.null
b.undefined
c.error
d.5
e.no output
Answer:d
Reason:Nullish operator returns 5 as the num is null.
Identify the output of the below program
const big = 1234124123412412341234123412341234n; console.log(typeof big);
b.number
c.float
d.error
e.bigint
Answer:e
Reason:A integer value suffixed by n is bigint type.
Identify the output of the below program
let big = BigInt(45252345235252352353523534523453252345235235345); console.log(typeof big);
a.number
c.bigint
d.error
e.float
Answer:c
Reason:A variable assigned by function BigInt is bigint type.
Identify the output of the below program
let obj = { name: { firstname : "ram", lastname : "kumar" } } console.log(obj.name.middlename?.name);
a.null
b.ram
c.crash
d.undefined
e.kumar
Answer:d
Reason:The optional chaining operator returns undefined for non existent properties.
Identify the output of the below program
let arr =null; console.log(arr?.[1]);
a.null
b.undefined
c.1
d.crash
e.no output
Answer:b
Reason:For non existent index access the optional chaining operator returns undefined.
Identify the output of the below program
let obj = { name: { firstname : "ram", lastname : "kumar" } } console.log(obj.name.middlename?.name ?? "Default");
a.undefined
b.null
c.error
d.ram
e.Default
Answer:e
Reason:By computation the value displayed is Default.
Identify the output of the below program
let obj = { name: { firstname : "ram", lastname : "kumar" } } console.log(obj.name.middlename ?? "default");
a.ram
b.kumar
c.undefined
d.default
e.error
Answer:d
Reason:Since middlename property is non existent default is printed.