JS Arrays

·

2 min read

Difference between : Array() and [] , Array[integer]

  1. Array[t]- It is used to access the t index of the array.

  2. Array(t)- This is like passing t in the constructor of Array. It will generate an array with t elements in it. [ t undefined spaces it will generate ]

  3. []- This is Array literal notation. Instead of new Array() , you can use square brackets []. Using square brackets is called the "array literal notation" .

    console.log([255]);
    VM419:1 [255]0: 255length: 1[[Prototype]]: Array(0)

Array.from()

The Array.from() static method creates a new, shallow-copied Array instance from an iterable or array-like object.

Syntax:

Array.from(arrayLike, CallBackmapFn, thisArg);

  • arrayLike An iterable or array-like object to convert to an array.

  • CallBackmapFn(element,index) Optional Map function to call on every element of the array. If provided, every value to be added to the array is first passed through this function, and mapFn's return value is added to the array instead.

The function is called with the following arguments:

-- element The current element being processed in the array.

-- index The index of the current element being processed in the array.

  • thisArg Optional Value to use as this when executing mapFn.

Use cases Array.from():

  1. Array from a String .

  2. Array from a Set .

  3. Array from a MAp.

  4. Array from a NodeList .

5.Array from an Array-like object (arguments) .

  1. Sequence generator (range). [ ]

Source :

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from

  2. https://www.freecodecamp.org/news/https-medium-com-gladchinda-hacks-for-creating-javascript-arrays-a1b80cb372b/