JavaScript Coding Question – 16

  • Generally arr.sort() method gives the output as [ 14, 23, 34, 54, 87, 9 ]. Because sort() treats elements as strings and sorts them lexicographically (like words in a dictionary).
  • arr.sort((a, b) => b – a) sorts numbers correctly in descending order as [ 87, 54, 34, 23, 14, 9 ]. This method compares by taking two arguments as a and b, 1). If b-a > 0, then b should come before a. 2) If b-a < 0, then b should come after a. 3) If a-b=0, then order should be unchanged.
  • From the array [ 87, 54, 34, 23, 14, 9 ], Final output is arr[arr.length – 1] = arr[5] = 9.

JavaScript Coding Question – 15

  • [ a, , b] = array : Here, a is assigned the first element of array, which is 10. Second element is skipped by using comma(,). b is assigned with the third element of the array, which is 30.
  • array.fill(5, 1, 2) : fill method modifies the original array. Here it replaces elements from index 1 to 2(index 2 is excluded) with the value 5.
  • result = b + array[1] : Here b is 30 and value of array[1] is 5. So 30+5 is 35.

JavaScript Coding Question – 14

  • number1() : This will give output as 123. Because it calls with no arguments and returns default value 123.
  • number2(new Number(123)) : This is called with a Number object wrapping 123, so number2 returns this Number object as-is as [Number: 123]
  • The === operator checks for both value and type. Since a primitive number (123) and a Number object wrapping 123 have different types, the comparison returns false.
  • NOTE : Suppose if we use == operator for comparison it gives the output as true because JavaScript attempts to convert the Number object into a primitive for comparison. When an object like new Number(123) is compared to a primitive, JavaScript calls the object’s .valueOf() method to get its primitive value.

JavaScript Coding Question – 13

Output:

[
  [ 'firstName', 'abc' ],
  [ 'lastName', 'xyz' ],
  [ 'age', 50 ]
]
  • Above code will convert the properties of the Person object into an array of key-value pairs using Object.entries().
  • Object.entries(Person) : takes each property of the Person object and convert it into an array, where each element is a [key, value] pair.