What sets apart Object.assign {} from Object.assign []?

While reviewing code done by a previous developer who is no longer with us, I observed that they sometimes used

Object.assign({}, xyz) 

and other times they used

 Object.assign([], abc);

Could there be a distinction between the two methods?

Answer №1

Indeed, there exists a distinction between the two methods. One method assigns the values to a new object while the other assigns the values to a new array.

Take a look at the displayed results here and compare them with what appears in the actual browser console.

var abc = {foo:"bar"};

var r1 = Object.assign({},abc);
var r2 = Object.assign([],abc);

console.log(r1);
console.log(r2);

It's important to note that the second method does not add a new item to the array - it will still have a length of 0.

Answer №2

Object.assign is a method that duplicates the enumerable own properties from one object to another (referred to as the target) and then returns the target object. Even though arrays are considered objects, you can still duplicate properties onto them; however, these properties will not be visible during iteration.

Let's look at this example:

  • obj is an object
  • arr is an object, but also an array
  • arr.a equals 1
  • arr.forEach does not display a
const obj = Object.assign({}, {
  a: 1,
  0: 2
});
const arr = Object.assign([], {
  a: 1,
  0: 2
});

console.log(typeof obj);
console.log(typeof arr);

console.log(Array.isArray(arr));

console.log(obj);

console.log(arr);
console.log(Object.keys(arr));
console.log(arr.a);

arr.forEach((item, idx) => console.log(`${idx}: ${item}`));

// To test the query in the comments

let copiedObj = { a: 123 };

let copy = Object.assign({}, copiedObj);

console.log(copy);

copiedObj = [];

console.log(copiedObj);
console.log(copy);

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

Support for BigInt is not available in TypeScript version 3.5.*

It seems that TypeScript has supported BigInt since version 3.2, and my project is using TypeScript 3.5. Despite not explicitly declaring any variables as BigInt, I recently integrated a package called BufferUtility from https://github.com/Pharuxtan/Buffer ...

How can I successfully implement the Add To Calendar Button Package?

Recently, I decided to incorporate this particular component into my application. Although it seemed simple enough at first, I'm now faced with a puzzling TypeError originating from within the package. The react component I am constructing is as foll ...

Adjust the size of an input field in jquery or javascript based on user input

Ensure that an input text box can only contain a maximum of 13 numbers, but if the user enters a 14th number as a decimal point, then allow up to 16 numbers. HTML: <input type="text" maxlength="15" onkeyup="checkCurrency(this)"/> Script: func ...

Tips for converting text from an HTML input field to a JSON file

After designing a form with four text fields and a submit button, my goal is to save the data into a JSON file upon submission. Additionally, I am looking for a way to display all of the JSON data on my webpage. ...

Testing a Component Function in ReactJS: A Step-by-Step Guide

Testing methods in a Meteor application using mocha/chai can be done like this: describe('postMessage', () => { it('should add message', (done) => { // EXECUTE const messageId = postMessage.call({ articleId: 123, conten ...

Using PHP to extract all occurrences of window.location from an HTML document using regex

Is there a way to extract all the window.location instances in PHP? I have a list of URLs that I am fetching using cURL, saving the HTML content as a string, and now I need to identify and display all the occurrences of window.location separately. I atte ...

Tips for preserving selection state in a multi-page results display?

In the process of developing a web application, I am working on implementing a way to save selection states. Specifically, I am building a query interface that interacts with a MongoDB backend. The search results are displayed in a grid format with check ...

Using TypeScript to efficiently filter an Array by converting all values to lowercase

I have a custom array in TypeScript that needs to be filtered based on the city and job, with case-insensitivity as a requirement. array = [{ name: "Hardik", city: null, job: null }, { name: "John", city: "Ahmedabad", job: "IT" }, { name: "Margie", c ...

Steps to generate an error in the 'response' function of a $httpProvider interceptor

I am currently working on creating a custom HTTP interceptor in Angular and I am looking to generate an error from the response of the $httpProvider interceptor. According to the provided documentation: response: Interceptors are triggered by the http re ...

performing functions concurrently within angularjs

I am currently utilizing angularjs 1.0 within my application. There is a dropdown on my cshtml page <select tabindex="2" id="Employee" ng-model="models.SelectedEmployee" ng-change="changeEmployee()" disabled="disabled" class="Answer" size="6"> < ...

PHP: Eliminating Line Breaks and Carriage Returns

My content entered into the database by CKEditor is adding new lines, which poses a problem as I need this data to be rendered in JavaScript as a single line of HTML. Within my PHP code, I have implemented the following steps: $tmpmaptext = $map['ma ...

Using React.js to pass data iterated with map function to a modal

I am trying to display my data in a modal when clicking on buttons. The data is currently shown as follows: 1 John watch 2 Karrie watch 3 Karen watch ... like this It is presented in the form of a table with all the 'watch' items being button ...

Flickering transitions in Phonegap and jQuery Mobile pages

As a beginner in Phonegap/jQuery Mobile, I have encountered a frustrating issue of a white screen appearing during page transitions. Despite trying various solutions found online, such as using -webkit-backface-visibility:hidden;, the problem persists. I ...

Ways to retrieve the file name and additional attributes from a hidden input type

Is it possible to access the file name and other attributes of a hidden file when submitting it using the <input type="hidden"> tag? My current project involves drag and drop file functionality on a server using Node.js. If I am able to dynamically ...

Unable to synchronize Rijdnael encryption across C# and Javascript/Node platforms

I have encountered an issue while trying to convert a Rijndael encryption function from C# to Node. Despite using the same Key, IV, Mode, and Block Size, I am unable to achieve matching results. What could be causing this discrepancy? C# MRE: using System ...

Is there a way in Vue.js to create a description list (dl) using v-for?

The v-for directive in vue is truly remarkable. I am currently faced with a situation where I need to create a description list similar to this. To achieve this, I have to generate two DOM elements for each item in my array: <dl class="row"> < ...

Encountering a snag when trying to load JavaScript within an HTML document

I encountered an error while trying to load an HTML file in the JavaScript console of the Brave browser. The error message reads: require.js:5 Uncaught Error: Module name "constants.js" has not been loaded yet for context: _. Use require([]) https://requir ...

Obtain the string value of `reader.result` from the `FileReader

Struggling to retrieve a string in a reader.onloadend but it's constantly returning my entire function. Here is the function I'm using: uploadFile() { let vm = this; var file = vm.$refs["testeLogo"].files[0]; var reade ...

Tips for getting information from a GET/POST response message with superagent

I'm currently utilizing Node.js and Superagent for testing my server implementation. I have successfully sent a Superagent GET request and received a positive response with the code provided below. My goal is to extract and log only the "id" value fro ...

An issue occurred with the session being undefined in Node.js Express4

I'm encountering an issue where my session is undefined in new layers even after setting the value within an "if" statement. /*******************************************/ /**/ var express = require('express'), /**/ cookieParse ...