Introduction
Namaste, In this blog I will discuss 8 code scenarios on Javascript .
Identify the output of the below program
let nestedArray = [1, [2, [3]]]; const flattened = nestedArray.flat(2); console.log(flattened);
a. Object
b.[1, [2, [3]]]
c.[1, 2, 3]
d.[1, [2, 3]]
e.2
Answer:c
Reason:The flat() function returns a new array flattened at depth 2.
Identify the output of the below program
let myArr = [[1, 2], [3, 4], [5, 6]]; let newArr = myArr.flat(); console.log(newArr);
a.[[1, 2], [3, 4], [5, 6]]
b.[1, 2, 3, 4, 5, 6]]
c.[[1, 2], 3, 4, 5, 6]
d.[1, 2], [3, 4], [5, 6]
e.Object
Answer:b
Reason:The host array returns an array flattened at level 1 by default.
Identify the output of the below program
let myArr = [1, 2, 3, 4, 5, 6]; let newArr = myArr.flatMap((x) => x * 2); console.log(newArr);
a.[2, 4, 6, 8, 10, 12]
b.[2, 4, 6, 8]
c.[1, 2, 3, 4, 5, 6]
d.[12,10,8,6,4,2]
e.Object
Answer:a
Reason:The callback function returns a new updated array.
Identify the output of the below program
let myArr = [[1], [2], [3]]; let newArr = myArr.flat(); console.log(newArr);
a.[[1], [2], [3]]
b.[1], [2], [3]
c.[[1], [2], [3]]
d.[[1,2,3]]
e.[1,2,3]
Answer:e
Reason:The host array is flattened at level 1 and a new array is returned.
Identify the output of the below program
try { throw 10; }catch { console.log("error"); }
a.10
b.error
c.no output
d.object
e.1
Answer:b
Reason:The error raised is caught by catch where error is printed.
Identify the output of the below program
try { a=20; }catch { console.log("error"); }
a.20
b.Object
c.error
d.undefined
e.no output
Answer:c
Reason:The variable is not created hence caught by catch.
Identify the output of the below program
let nestedArray = [1, [2, [3]]]; const flattened = nestedArray.flat(1); console.log(flattened);
a.[1, [2, [3]]]
b.[1, 2, 3]
c.[1, [2, 3]]
d.[1, 2, [3]]
e.error
Answer:d
Reason:The array is flattened at depth 1 and returns a new array.
Identify the output of the below program
let myArr = [1, 2, 3, 4, 5, 6]; let newArr = myArr.flatMap((x) => x +1 ); console.log(newArr);
a.[2,3,4,5,6,7]
b.[1,2,3,4,5,6]
c.[2, 4, 6, 8, 10, 12]
d.Object
e.[1,2]
Answer:a
Reason:The callback function increments each value by 1 and returns a new array.