JavaScript from(): Get an array from an iterable object

The JavaScript from() method returns an array from an array-like or iterable object. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
  
   <p id="xyz"></p>

   <script>
      let str = "codescracker";
      const arr = Array.from(str);
      document.getElementById("xyz").innerHTML = arr;
   </script>
   
</body>
</html>
Output

In the above example, the following JavaScript statement:

let str = "codescracker";

declares a string variable str with the value "codescracker".

Now using the second JavaScript statement:

const arr = Array.from(str);

invokes the Array.from() method, passing str as an argument. This method generates a new array from the input string's characters, with each character becoming an element in the new array. The array that results is saved in the arr variable.

Finally, the following JavaScript statement:

document.getElementById("xyz").innerHTML = arr;

finds the HTML element with the id attribute "xyz" and sets its innerHTML property to the arr variable using the document.getElementById() method. The contents of the arr variable (which contains the converted string as an array) will be displayed on the web page.

Note: from() is a static method. Static methods are called by classes, whereas dynamic methods are called by objects.

JavaScript from() syntax

The syntax of the from() method in JavaScript is:

Array.from(object, mapFn, thisArg)

The object refers to an array-like or iterable object that is going to be converted into an array.

mapFn refers to a map function. Use this parameter when you need to call a function on every element of the specified array.

thisArg refers to the value that will be used as this for the mapFn.

Advantages of the from() method in JavaScript

Disadvantages of from() method in JavaScript

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!