JavaScript Array of() MethodThe of() method creates and returns a new array from different a number of arguments. It does not focus on the type and number of arguments. Similar to Array, it also provides a constructor that handles the integer arguments, but in a different manner. SyntaxThe syntax of Array of() method is as follows: ParameterIt takes and put elements in an array form. Thus, these elements create the array. ReturnIt returns a newly created array instance. JavaScript Array of() Method ExampleLet's implement some examples to understand better: Example1 Here's an example that shows the working of Array of() method. Test it NowOutput: The output represents the elements in the array form. Example2 Here's an example to represent a single value in the form of an array. Test it NowOutput: Here, 1 is a single element of the newly created array. Example3 Test it NowOutput: Here, each alphabet is an element of the newly created array. Example4 Using 'undefined' as an element of the Array.of() method. Test it NowOutput: It displays a new array with 'undefined' as its element. Note: If we try to run this code in the web browser, it will not display 'undefined' as an array value. Thus, above snapshot shows the output of the console.As discussed above, Array.of method creates constructor as an Array does, but the handling of integer arguments varies. For example, Array.of(10) will create an array holding 10 as its element. In the case of Array(10), it will create an array of length as 10. Let's see the code implementation: Simple Array Constructor ExampleOutput1: On console The output shows an empty array with length 7. Output2: On Browser The output represents an empty array having length 7. Array.of() Constructor Example:Output: Thus, the above examples will help to understand the difference between Array.of() and Array constructor. Next TopicJavaScript Array |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India