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

Enhance Vuetify functionality using TypeScript for custom components

I'm facing a challenge with extending a Vuetify component and setting default props in TypeScript. While I had success doing this in JavaScript, I am struggling to do the same in TS. Below is an example of how the Component was implemented in JS: imp ...

Unable to insert a JSON object into an Array

This might appear to be a duplicate, but it's not. None of the solutions I've tried have worked. Within my angular module, I have a list: this.checkedInterviews = [] Followed by a function that does the following: var interviewModel = { ...

Exploring the process of sending props via the render method in Vue.js and observing their behavior

Struggling with passing a prop from a parent component down to a child created using CreateElement/render in vue.js and then watching it. Here is the parent component: Vue.component('my-drawing', MyDrawing) new Vue({ el: '#drawing' ...

A guide to increasing a loop counter in Vue

Having trouble looping through a specific group of objects in a multi-object array? Take a look at the code below: <template> <div> <h1>My Test App</h1> <button v-on:click="getHockeyData">Get Team Data< ...

Adjusting the size of the snap increments

When using gridstack, I have the ability to resize my widgets. However, I've noticed that when dragging on the widgets' handles, they snap to specific sizes, which seems to be a fixed amount. If I wanted to set the widget's size to something ...

A clever JavaScript function generator encapsulated within an instant function nested within a jQuery ready statement

This code snippet features an immediate function enclosed within a jQuery ready function. $((function(_this) { return function() { document.write('called!'); }; })(this)); I am puzzled by where the resultant function ...

Using references to pass variables in TypeScript [Angular 8]

I have several variables within the html of this component that are assigned their values by the typescript file. The declaration in the html is as follows: <h1>{{myproperty1}}<\h1> <h1>{{myproperty2}}<\h1> <h1>{{myp ...

What is the term used to describe the way console.log styles the Json object?

Have you ever noticed that when a JSON object is printed, say in a script run by node using console.log, it doesn't exactly pretty print the JSON? It sort of strikes a balance between showing as few lines as possible while still maintaining readabilit ...

Creating a primary index file as part of the package building process in a node environment

Currently, I have a software package that creates the following directory structure: package_name -- README.md -- package.json ---- /dist ---- /node_modules Unfortunately, this package cannot be used by consumers because it lacks an index.js file in the r ...

Modify a section of the "src" parameter in an iframe using jQuery

Seeking to deactivate the autoplay feature on a Vimeo iframe embed within a Drupal 6 website. Unable to modify settings in the embedmedia module, opting to utilize jQuery instead. Here is the original "src" for the Vimeo content: <iframe src="http:// ...

Using Sequelize to Include Model Without Specifying Table Name

I am new to Sequelize I am facing an issue with "Nested Eager Loading" I have 2 tables with a one-to-many relationship Comment Table User Table This is the code I am using for the query Comment.findAll({ include: [User] }) The result I got was ...

Tips for sending a MySQL parameter

Hey there, I need some help with the trigger setup I have: CREATE TRIGGER `update` AFTER UPDATE ON `table 1` FOR EACH ROW INSERT INTO table 2 ( Id, Revision, Purpose, Change ) VALUES ( OLD.Id, OLD.Revision, OLD.Purpose, @purpose_change /* user variable ...

Sending a post request with data to an ExpressJS server resulted in a 404 error indicating that the server

My setup includes a React frontend communicating with my own ExpressJS API backend running version 4.16.0. Currently, using the fetch method in the React frontend to retrieve data is functioning properly: fetch('/desResData') .then(res = ...

I'm having trouble getting a response from the user.php file in my login system

I am trying to create a login system using ajax and pdo with a button as the submitter. The issue I am facing is that when I click the button to execute, nothing happens. There are no errors in the console. I can see in the network tab that it sends the us ...

"Unexpected Type Inference Issue: A variable initially defined as a string inexplicably transforms into 'undefined'

Currently, I am incorporating the await-to-js library for handling errors (specifically utilizing the to method from the library). In an intriguing scenario, the variable type shifts to string | undefined within a for..of loop, whereas outside of the loop ...

What is the best method for sending form data, specifically uploaded images, in Python Bottle with Ajax?

This form belongs to me <form method='post' enctype='multipart/form-data' id='uploadForm' name='formn'> <input type='file' value='' name='newfile'> <input type=&a ...

Sharing information between different components in React can be done using props, context, or a

When attempting to edit by clicking, the parent information is taken instead of creating a new VI. I was able to achieve this with angular dialog but I am unsure how to do it with components. This is done using dialog: <div class="dropdown-menu-item" ...

The node command line does not recognize the term 'require'

My Typescript project was compiling and running smoothly until recently when I started encountering the error ReferenceError: require is not defined every time I try to run node. I am uncertain whether this issue stems from Typescript, as even when I ru ...

The jQuery Show Hide feature is experiencing issues specifically on Internet Explorer

Everything looks good in Firefox and Chrome, but unfortunately it's malfunctioning in IE. Does anyone have a suggestion for hiding select Dropdown options? I attempted using CSS with display: none but it didn't work. $j("#id option[value=&apos ...

Issue with conditional image source URL in NUXT component not functioning as expected

I am currently attempting to dynamically render an image source path based on the provided prop in the component. In case the image does not exist in the assets folder, I want to include a fallback path. Below is the code snippet for my image tag: <img ...