Find the largest and smallest numbers in an array in JavaScript using Math.max() and Math.min().

  • Here, spread operator converts an array into individual arguments.
  • So Math.max and Math.min expect a list of arguments, not an array directly.
  • For small and medium size arrays Math.max and Math.min are the simplest and most effective way.
  • For Large Arrays we need to use Array.reduce() for better performance.
  • And most importantly Math.max and Math.min works only for array of numbers.

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 – 1

  • Here, in the above code the line const result = […new Set(arr)] removes duplicate values from the array arr using a Set, which only allows unique values.
  • new Set(arr): Creates a new Set from the array. The Set will only keep unique values.
  • [...new Set(arr)]: The spread operator ... is used to convert the Set back into an array.

typeError: cannot read properties of undefined (reading ‘join’)

  1. We should apply the join method only on Array. So before applying the join method, first we need to check that the output is coming in the form of array or not.
  2. if you are using any online code editor, check that you should use return instead of console.log. May be in the background they are applying the join method. So, for that they don’t want log reports. We need to return the output and the output should be in the form of Array to apply the Join method.