JavaScript Array from() Method


The from() method of JavaScript is used to return the Array object from any object with a length property or an iterable object.

The syntax is as follows −

Array.from(obj, mapFunction, val)

Above, the parameter obj is the object to convert to an array, mapFunction is a map function to call, val is a value to use as this when executing the mapFunction.

Let us now implement the from() method in JavaScript −

Example

 Live Demo

<!DOCTYPE html>
<html>
<body>
   <h2>Demo Heading</h2>
   <p id="test"></p>
   <script>
      var arr1 = Array.from("PQRS");
      var arr2 = Array.from("12345");
      document.getElementById("test").innerHTML = arr1 +" and "+arr2;
   </script>
</body>

Output

Example

 Live Demo

<!DOCTYPE html>
<html>
<body>
   <h2>Demo Heading</h2>
   <p id="test"></p>
   <script>
      var arr1 = Array.from("PQRS");
      var arr2 = Array.from("%$%#$$#$");
      var arr3 = Array.from("12345");
      document.getElementById("test").innerHTML = arr1 +", "+arr2+" and "+arr3;
   </script>
</body>

Output

Updated on: 17-Dec-2019

91 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements