typescript const x = [...this.x] - javascript

I have some inherited typescript code that looks like this (inside of a function):
const Statuses = [...this.Statuses]
this.Statuses refers to an array of status codes (defined as Statuses = status[];) defined inside the same .ts file. Subsequent to the line above, the code operates on Statuses
I'm trying to understand what the [...this.var] syntax does? Why not simply refer to this.Statuses in the first place?
Yes, I'm new to javascript/typescript....
Thanks in advance.

It's "spread notation", it spreads out this.Statuses (which must be some kind of Iterable, such as an array) into discrete elements. In this case, those form a new array (because the ...this.Statuses is within [], which creates an array).
So if this.Statuses is an array, it's functionally identical to const Statuses = this.Statuses.slice(); (or also the following).
If this.Statuses is another kind of Iterable, it's functionally identical to const Statuses = Array.from(this.Statuses);.

It's a aesthetically-pleasing way of copying an array, to avoid mutations to the original. It uses the spread syntax, as mentioned in other answers.
const a = [ 1 ]
const b = a
const c = [...a]
b.push(2)
c.push(3)
console.log(` original: ${a}`)
console.log(`reference: ${b}`)
console.log(` copy: ${c}`)

It's spread syntax. It allows to copy items from one array (or object) to another. In your case it's used to make a shallow copy of this.Statuses to avoid original array mutations. Thanks for this when you for example push new item to Statuses the original array (this.Statuses) will remain unchanged.

Related

Difference between [...obj] and {...obj}

I know about the spread operator ... in JavaScript. We can use it on both arrays and objects:
let user = {
name: "aman",
rollno: 11
}
let newobj1 = {...user}
let newobj2 = [...user]
console.log(newobj1)
console.log(newobj2)
Why does newobj2 give an error, TypeError: user is not iterable, but newobj1 works fine?
{...user} just creates a new object with the same properties as user.
[...user], on the other hand, iterates through the object and adds the values it finds into the array it returns. If there is no way to iterate, as there isn't by default on a plain object (as opposed to an array), then this doesn't work and raises the error you've quoted.
As always, there is much more information about this on MDN. Note in particular the following section:
Spread syntax (other than in the case of spread properties) can only
be applied to iterable objects like Array, or with iterating
functions such as map(), reduce(), and assign().
Many objects are not iterable, including Object:
let obj = {'key1': 'value1'};
let array = [...obj]; // TypeError: obj is not iterable
To use spread syntax with these objects, you will need to provide an
iterator function.
And note that the "spread syntax" being referred to here is the "array spread" version. "Object spread" is rather different and explained on this part of the page,
{...user}
means that you create new object and spread all the data from user inside it.
When you suppose to execute
[...user]
you tries to create brand new array and then spread the user object inside.

Most efficient way to mutate an item in array of objects? [VUEX]

I read the official Vuex example of how to mutate the state of element in array of objects data.
editTodo (state, { todo, text = todo.text, done = todo.done }) {
const index = state.todos.indexOf(todo)
state.todos.splice(index, 1, {
...todo,
text,
done
})
}
It seems a bit an overkill to find the index first (first loop), perform a splice and perform a copy with spread operator ...todo (would it be considered a second loop?).
Going by the docs:
When adding new properties to an Object, you should either:
Use Vue.set(obj, 'newProp', 123), or Replace that Object with a fresh one. For example, using the object spread syntax: state.obj = { ...state.obj, newProp: 123 }
There are only two ways to set / update properties to object.
In bigger data scenario that is causing some performance issues. Is there any better (more efficient) way to update an element in array of objects?

About immutable update pattern of objects: newObject=JSON.parse(JSON.stringify(object))?

demo here:
let objectTest={
a:"one",
b:"two",
c:"three"
}
let newObject = JSON.parse(JSON.stringify(objectTest))
console.log("hello, I am a new object: ", newObject)
console.log("newObject === objectTest: ", newObject === objectTest)
Is it okay to make an immutable copy of an object like that: newObject=JSON.parse(JSON.stringify(object))?
Just to grab the main properties of the object -the one that appears on the console.log().
Can we consider this transformation an immutable one?
From my demo I would say yes,since it seem to really create a new object.
Yes, it is; JSON.parse creates a new object every time

JavaScript: Weird (edge?) case of a mixed Array/Object

I saw this for the first time (or noticed it for the first time) today during a maintenance of a colleagues code.
Essentially the "weird" part is the same as if you try to run this code:
var arr = [];
arr[0] = "cat"; // this adds to the array
arr[1] = "mouse"; // this adds to the array
arr.length; // returns 2
arr["favoriteFood"] = "pizza"; // this DOES NOT add to the array. Setting a string parameter adds to the underlying object
arr.length; // returns 2, not 3
Got this example from nfiredly.com
I don't know what the technical term for this "case" is so I haven't been able to find any additional information about it here or on Google but it strikes me very peculiar that this "behaviour" can at all exists in JavaScript; a kind of "mix" between Arrays and Objects (or Associative Arrays).
It states in the above code snippet that that Setting a string parameter adds to the underlying object and thus not affect the length of the "array" itself.
What is this kind of pattern?
Why is it at all possible? Is it a weird JS quirk or is it deliberate?
For what purpose would you "mix" these types?
It's possible because arrays are objects with some special behaviors, but objects nevertheless.
15.4 Array Objects
However, if you start using non-array properties on an array, some implementations may change the underlying data structure to a hash. Then array operations might be slower.
In JavaScript, arrays, functions and objects are all objects. Arrays are objects created with Array constructor function.
E.g.
var a = new Array();
Or, using shortcut array literal,
var a = [];
Both are the same. They both create objects. However, special kind of object. It has a length property and numeric properties with corresponding values which are the array elements.
This object (array) has methods like push, pop etc. which you can use to manipulate the object.
When you add a non-numeric property to this array object, you do not affect its length. But, you do add a new property to the object.
So, if you have
var a = [1];
a.x = 'y';
console.log(Object.keys(a)); // outputs ["0", "x"]
console.log(a); // outputs [1];

Javascript passing arrays to functions by value, leaving original array unaltered

I've read many answers here relating to 'by value' and 'by reference' passing for sending arrays to javascript functions. I am however having a problem sending an array to a function and leaving the original array unaltered. This example llustrates the problem:
function myFunction(someArray)
{
// any function that makes an array based on a passed array;
// someArray has two dimensions;
// I've tried copying the passed array to a new array like this (I've also used 'someArray' directly in the code);
funcArray = new Array();
funcArray = someArray;
var i = 0;
for(i=0; i<funcArray.length; i++)
{
funcArray[i].reverse;
}
return funcArray;
}
I can't understand why anything in this function should alter the original array.
calling this function directly changes the original array if the function call is assigned to a new array:
myArray = [["A","B","C"],["D","E","F"],["G","H","I"]];
anotherArray = new Array();
anotherArray = myFunction(myArray);
// myArray gets modified!;
I tried using .valueOf() to send the primitive:
anotherArray = myFunction(myArray.valueOf());
// myArray gets modified!;
I have even tried breaking the array down element by element and sub-element by sub-element and assigning all to a new 2-d array and the original array still gets modified.
I have also joined the sub-elements to a string, processed them, split them back into arrays and the original array still gets modified.
Please, does any one know how I can pass the array values to a function and not have the passed array change?
Inside your function there's this:
funcArray = new Array();
funcArray = someArray;
This won't actually copy someArray but instead reference it, which is why the original array is modified.
You can use Array.slice() to create a so-called shallow copy of the array.
var funcArray = someArray.slice(0);
Modern versions of ES also support destructuring expressions, which make it look like this:
const funcArray = [...someArray];
The original array will be unaltered, but each of its elements would still reference their corresponding entries in the original array. For "deep cloning" you need to do this recursively; the most efficient way is discussed in the following question:
What is the most efficient way to deep clone an object in JavaScript?
Btw, I've added var before funcArray. Doing so makes it local to the function instead of being a global variable.
Make a copy of the array that you can use.
A simple way to do this is by using var clone = original.slice(0);
With ES6, you can use the rest element syntax (...) within a destructuring expression to perform a shallow copy directly in the parameter list, allowing you to keep the original array unaltered.
See example below:
const arr = [1, 2, 3, 4, 5];
function timesTen([...arr]) { // [...arr] shallow copies the array
for(let i = 0; i < arr.length; i++) {
arr[i] *= 10; // this would usually change the `arr` reference (but in our case doesn't)
}
return arr;
}
console.log(timesTen(arr));
console.log(arr); // unaltered
The above is useful if you have an array of primitives (strings, booleans, numbers, null, undefined, big ints, or symbols) because it does a shallow copy. If you have an array of objects, or an array of arrays (which are also technically just objects), you will want to perform a deep clone to avoid modifying the array and its references. The way to do that in modern-day JS is to use a structured clone, which helps deal with many of the shortcomings of deep cloning with the JSON.stringify() technique as previously used:
function myFunction(someArray) {
const funcArray = structuredClone(someArray);
...
}
What about destructuring assignment (ES6+, check compatibility)? Nice and clean solution.
function myFunction(someArray) {
for(let i = 0; i < someArray.length; i++)
{
someArray[i].reverse();
}
return someArray;
}
let myArray = [["A","B","C"],["D","E","F"],["G","H","I"]];
// Using destructuring assignment.
// NOTE: We can't just use `[...myArray]` because nested arrays will still be copied by reference.
let anotherArray = myFunction([...myArray.map(nested => [...nested])]);
console.log({original: myArray, copy: anotherArray});
A variable pointing to an array is a reference to it. When you pass an array, you're copying this reference.
You can make a shallow copy with slice(). If you want a full depth copy, then recurse in sub objects, keeping in mind the caveats when copying some objects.
If you need to do this with an object, try this fancy trick...
MY_NEW_OBJECT = JSON.parse(JSON.stringify(MY_OBJECT));
A generic solution would be...
// Use the JSON parse to clone the data.
function cloneData(data) {
// Convert the data into a string first
var jsonString = JSON.stringify(data);
// Parse the string to create a new instance of the data
return JSON.parse(jsonString);
}
// An array with data
var original = [1, 2, 3, 4];
function mutate(data) {
// This function changes a value in the array
data[2] = 4;
}
// Mutate clone
mutate(cloneData(original));
// Mutate original
mutate(original);
This works for objects as well as arrays.
Very effective when you need deep cloning or you don't know what the type is.
Deep cloning example...
var arrayWithObjects = [ { id: 1 }, { id: 2 }, { id: 3 } ];
function mutate(data) {
// In this case a property of an object is changed!
data[1].id = 4;
}
// Mutates a (DEEP) cloned version of the array
mutate(cloneData(arrayWithObjects));
console.log(arrayWithObjects[1].id) // ==> 2
Warnings
Using the JSON parser to clone is not the most performant option!
It doesn't clone functions only JSON supported data types
Cannot clone circular references
by default in javascript except objects and arrays, everything is copy-by-value
but if you want to use copy-by-value for arrays: use [yourArray].slice(0)
and for objects use Object.assign(target, ...sources)
var aArray = [0.0, 1.0, 2.0];
var aArrayCopy = aArray.concat();
aArrayCopy[0] = "A changed value.";
console.log("aArray: "+aArray[0]+", "+aArray[1]+", "+aArray[2]);
console.log("aArrayCopy: "+aArrayCopy[0]+", "+aArrayCopy[1]+", "+aArrayCopy[2]);
This answer has been edited. Initially I put forth that the new operator handled the solution, but soon afterward recognized that error. Instead, I opted to use the concat() method to create a copy. The original answer did not show the entire array, so the error was inadvertently concealed. The new output shown below will prove that this answer works as expected.
aArray: 0, 1, 2
aArrayCopy: A changed value., 1, 2

Categories

Resources