Have you ever come across odd ways to use Array.of() and Array.from()?

Discover two innovative methods introduced in ES6 for Array: Array.of() and Array.from(). Their distinct uses are outlined on this informative page.

However, I find myself perplexed by the application of Array.of in this specific line.

// usage of Array.of
console.log(
    Array.of( "things", "that", "aren't", "currently", "an", "array" )
); // ["things", "that", "aren't", "currently", "an", "array"]

Consider the alternative approach below:

console.log(
    [ "things", "that", "aren't", "currently", "an", "array" ]
); // ["things", "that", "aren't", "currently", "an", "array"]

It's worth noting that the same outcome can be achieved using console.log(Array.of(...)). Is there any particular benefit to utilizing Array.of in this context?

Another source of confusion arises with the use of Array.from in the following line.

var divs = document.querySelectorAll("div");
console.log(
    Array.from( divs )
);

What if Array.from is omitted from the aforementioned code snippets.

var arr = [1, 2, 3];
console.log(Array.from(arr)); // [1, 2, 3]
console.log(arr); // [1, 2, 3]

Are there any advantages to employing Array.from in this scenario?

Answer №1

Understanding Array.of() Function in JavaScript

Brendan Eich, the creator of JavaScript, discussed the purpose of Array.of() in a forum post (Source):

Dmitry A. Soshnikov asked:

Brendan Eich responded:

The main goal of Array.of is to provide an array constructor that eliminates the special case for Array(42), which can lead to unexpected behavior by preallocating length but leaving gaps in the array.

Some developers questioned how using Array.of would be beneficial compared to manually enumerating items in an array initializer. The discussion highlighted the syntactic elegance and efficiency of using brackets for array initialization instead of relying on functions like Array.of.

Eich emphasized that Array.of is particularly useful when passing arguments as functions where the number of arguments might vary. In such cases, Array constructor may not behave as expected with single-number arguments, making Array.of a better option.

This explains the need for Array.of.

An example illustrating the difference between Array.of and Array constructors:

// Array.of(42) creates an array with 1 element (42). Using Array(42) will create an array with 42 undefined elements.
console.log(new Array(42));
console.log(Array.of(42));

Exploring Array.from() Method in JavaScript

The Array.from() method allows you to create a new Array instance from array-like or iterable objects.

  1. Array-like objects (objects with length property and indexed elements)
  2. Iterable objects (objects like Map and Set where you can access their elements)

For instance:

var sampleMap = new Map([[1, 2], [2, 4], [4, 8]]);
console.log("Original Map:");
console.log(sampleMap);

var newArrayFromMap = Array.from(sampleMap);
console.log("Transformed Array: ");
console.log(newArrayFromMap);

Answer №2

console.log(Array.of("Akansha")) //[ 'Akansha' ]

console.log(Array.from("Akansha")) //['A', 'k', 'a','n', 's', 'h','a']

let total1 = 100

let total2 = 200

let total3 = 300

console.log(Array.of(total1,total2,total3)) //[ 100, 200, 300 ]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to iterate through this array in ajax?

Is there a way to properly read this array using ajax? I need some assistance understanding the server response: Array ( [success] => 1 [0] => Array ( [0] => Mr Green [FirstName] => Mr Green ...

Need a jQuery callback function in PHP that only retrieves the value without any redirection

Initially, I expected this task to be simple but it turns out my skills are a bit rusty. The snippet of javascript/jquery code that I am using is: $.get("plugin.php", {up_vote:surl}, function(data){ //alert(data); document.getElementById(&apo ...

Remove an element from an array of string pointers

I am working with a string pointer array called test_array. If the array contains an empty string, my goal is to move to the end of the array and find an element that is not empty. I then want to copy this non-empty element to the previous empty position ...

The aspect ratio of a DIV element is not maintaining its scale properly in Firefox

My current challenge involves using a Script to Scale a Div while maintaining the aspect ratio. The objective is to ensure that 100% of the DIV remains visible while maximizing its size. As you scale the browser width, the div adjusts its height to 100%, a ...

What is the best way to implement a Facebook share button using the Facebook Javascript SDK within an Ajax request?

In my Rails application, I have implemented the following code in an Ajax call: <script type="text/javascript"> $(document).on('click','#share_button', function(e){ e.preventDefault(); FB.ui({ method: &apo ...

The Ajax GIF Loader is not functioning in the latest versions of Internet Explorer and Firefox, but it is running smoothly in

The animated GIF loader functions correctly in the latest version of Chrome, but does not animate when viewed in IE and Firefox. Below is the code snippet: $("#DIALOG").dialog({ buttons : { "Yes" : function() { ...

Preventing file visibility in Three.js resource directory

Once a user clicks on a specific 3D model, I retrieve it from the server and render it in the browser using three.js. However, there is an issue when the user tries to access a model that is not free - they can easily view and download the STL file by go ...

What is causing my website to refresh before I can save the edits I have made after clicking on the edit button

My website is fairly simple, allowing users to add blog posts with a title, author, and content. Each post has two buttons - one for deleting and one for editing. These actions add, delete, or edit the chosen posts within a .json file through a local json ...

Adding the classname "active" in ReactJS can be achieved by utilizing the `className` attribute within

I am facing an issue with adding the active classname in my code. Can anyone suggest a solution to add the active classname for this section: <li onClick = {() => onChangeStatus({status: 'on-hold'})} className = {appState === {'status& ...

I am struggling to make my button hover effects to function properly despite trying out numerous suggestions to fix it

As a newcomer, this is my first real assignment. I've managed to tackle other challenges successfully, but this one seems a bit more complex and I'm struggling to pinpoint where I'm going wrong. Despite googling various solutions, none of th ...

Ways to incorporate validation into Material-UI form input fields

I have a react functional component that utilizes Material UI form, which includes TextField. The onChange event is managed in the "Container Component". I have added required for client-side form validation, but it doesn't seem to be working. Do I ne ...

How can I pass a value to a javascript function when a button in asp.net is clicked?

For the client side code, I have written the following: <script> function initialize(x, y) { alert(x); alert(y); var mapProp = { center: new google.maps.LatLng(x, y), zoom: 7, mapTy ...

What is the reason for Jest attempting to resolve all components in my index.ts file?

Having a bit of trouble while using Jest (with Enzyme) to test my Typescript-React project due to an issue with an alias module. The module is being found correctly, but I believe the problem may lie in the structure of one of my files. In my jest.config ...

Tips for creating a Vue component that triggers the select dropdown to open when the entire div or wrapper is clicked

I have a custom-designed select dropdown with unique symbols for the select arrow. To achieve this look, I've hidden the default select arrow/triangle and placed our symbol on top as an image file. <div class="select-wrapper"> < ...

The #each helper in Handlebars is used to iterate over an array

I have a function that generates an array as output. I am looking for a way to iterate over this array using the each method. Can anyone provide guidance on how to achieve this? Consider if the handlebars helper produces the following array: details: [{ ...

angular-recaptcha: Adjusting language based on the website's language update

My website offers three different languages that users can switch between. The language switch functionality is implemented on the client side using JavaScript (AngularJS). I have integrated reCAPTCHA 2 into my website and now I need to update the languag ...

Error: Unable to access the 'wsname' property of an undefined value

I am attempting to retrieve values from a database using the code below (login.js) $.post("http://awebsite.com/app/login.php",{ rep1: rep, password1:password}, function(data) { if(data=='Invalid rep.......') { $('input[type="text"]').c ...

Displaying an additional section using hover effects in Bootstrap

I recently utilized Bootstrap to create pricing tables which can be viewed here: http://www.bootply.com/VyHsJBDoNc Is there a way for me to implement hover functionality on a span element (+ More Information!) that will display additional information as s ...

Prevent modal from closing when tapping outside of it

I'm currently facing a challenge in creating a popup modal that cannot be closed by clicking outside the modal window. I have explored various solutions involving backdrops but none of them seem to be effective. Any assistance would be greatly appreci ...

Is there a way to retrieve php session in a javascript file?

Here's the code snippet for reference: Contents of index.php file Javascript code from index.php function Result() { var marks = 55; document.getElementById("hdnmarks").innerHTML= marks; window.location = "results.php"; } HTML code from ind ...