How do you ignore an item when destructuring an array? [duplicate] - javascript

This question already has answers here:
How can I ignore certain returned values from array destructuring?
(2 answers)
Closed 4 years ago.
I'm self-answering this because I didn't come across a question or answer that discussed ignoring a destructured array element while searching.
Is there a way to ignore an element of a array when destructuring? The closest thing that I can think of is how in Go you can use the _ symbol to drop an argument.
I'm using ESLint and I'd like to be able to avoid unused variable warnings without having to explicitly turn off the warning. I also don't like the scope leak even though it is rather minimal.
For example:
const arr = [
["foo", "bar"],
["fizz", "buzz"],
["hello", "world"]
];
// I don't actually want 'a' to be available in the scope
arr.forEach(([a, b]) => console.log(`a: ${a} | b: ${b}`));
// _ is still defined and equates to 'a' above
arr.forEach(([_, b]) => console.log(`'a': ${_} | b: ${b}`));

You can ignore an element by simply not providing a variable for the value to be assigned to and just putting the comma as though you had. See MDN: Destructuring assignment#Ignoring some returned values.
For example:
const arr = [
["foo", "bar"],
["fizz", "buzz"],
["hello", "world"]
];
// Just use ','
arr.forEach(([, b]) => {
// No variable is populated with the first element
console.log(typeof(a));
console.log(typeof(b));
console.log(`b: ${b}`);
});

Related

Creating a 'const const' object in javascript [duplicate]

This question already has answers here:
How do I make a JavaScript variable completely immutable?
(3 answers)
Closed last year.
In javascript, if I create a const array, I can still modify the object the variable points to:
// The const declaration creates a read-only reference to a value.
// It does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const
const x = [1,2,3];
x.push(4);
console.log(x);
x=55 // But this is illegal and will error
console.log(x);
Is there a way to make the elements in an array immutable as well? Similar to something like const int* const x; in C?
You can use Object.freeze to prevent an object (or array) from being changed:
const x = [1, 2, 3];
Object.freeze(x);
x.push(4); // This will throw an exception
objects frozen with Object.freeze() are made immutable.
Here are the docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze
Example:
const x = [1,2,3];
Object.freeze(x);

How to print JavaScript array with set of pairs inside array [duplicate]

This question already has answers here:
JavaScript expressions, comma delimited within parentheses [duplicate]
(3 answers)
Closed 2 years ago.
I was going through documentation of JavaScript about arrays and objects.I found one unique query about arrays
var a= [1,2,3]
console.log(a) // give [1,2,3]
var b = [(1,2) , (3,4) , (5,6)]
console.log(b) // gives [2,4,6]
I didn't understand the logic behind the same.It just ran over my mind.If we do same thing in python
a = [(1,2),(3,4)]
print(a) // [(1,2),(3,4)]
Can some one explain the same and can someone explain me how to get the same output in JavaScript like the way I got in python.How to iterate through all the elements in array in javascript
I'm not a Python programmer, but those parentheses differ in their functionality between Python and JavaScript.
I understand in Python they indicate a tuple literal. In JavaScript, they merely group things they say "execute each statement and return the last one." That's why you only see some items in your JS arrays.
See also https://stackoverflow.com/a/25280412/1371131
What you have encountered is the comma operator.
When there is no other context, a , in an expression behaves like an operator just like + or = or / etc.
The comma operator behaves as follows:
evaluate the first expression
ignore the result of the first expression
evaluate the second expression
return the value of the second expression
Thus the following code:
a = 1,2;
b = 1,2,3,4;
will result in a being assigned the value 2 and b assigned the value 4.
This may seem kind of silly because we already have ; but the comma operator is useful if you need more than one thing to happen in a single expression context. For example if you need more than one thing to happen in one of the conditions of a for loop you cannot use ; because that is used to separate the conditional expressions. The comma operator comes to the rescue:
for (let a = 0, b = 0; a < 10; a++, b++) { //...
// ^ ^
// | |____ two things happen here
// |_______________________________ and here
So (1,2) is just another way to write 2.
Therefore [(1,2) , (3,4) , (5,6)] and [2,4,6] is the same array.
Just like [1+1, 2+2, 3+3] and [2,4,6] is the same array.
They are just different ways to write [2,4,6]. The same way you cannot loop through the array and extract 1+ from [1+1, 2+2, 3+3] you cannot loop through the array and extract (1, from [(1,2) , (3,4) , (5,6)].
If you really need an array of pairs you need to use an array of arrays:
a = [[1,2],[3,4],[5,6]]

Unfamiliar use of square brackets during multiple variable declaration in Javascript [duplicate]

This question already has answers here:
Multiple assignment in JavaScript? What does `[ a, b, c ] = [ 1, 2, 3 ]` mean?
(4 answers)
Closed 5 years ago.
I'm a beginner to Javascript and encountered this syntax usage(simplified):
var testString ="firstName, lastName";
var [a,b] = testString.split(", ");
My question is what typeof variable a & b then becomes at line2?
My simplistic investigation seems to indicate a & b are assigned respective string values.
But what goes on under the hood? why do we use square brackets [] here? Isn't an array returned & created in the process by .split()? Otherwise, what objects were created in the background?
Links to understand this style of declaration for [a,b] would also be welcomed.
But what goes on under the hood?
// You declare a string variable
var testString = "firstName, lastName";
// Split method help you to divide the string value according with the
//indicated separator, in this examle the comma
var [a,b] = testString.split(", ");
The destructuring assignment syntax is a JavaScript expression that
makes it possible to unpack values from arrays, or properties from
objects, into distinct variables.
Since the split function returns an array, with the var [a,b] = array
you are assigning the value in index order, in the example:
console.log(a); // 'firstName'
console.log(b); // 'lastName'
And they are simple string variables. You may want to vist the links below:
Destructuring asignation
split function
Further resources: Since you have mentioned you are beginning with JS, I suggest you to read books mentioned in this magnific post
This is destructuring assignment. It resembles the pattern-matching found in many functional languages.

JavaScript ES6: Split array into rest and last with destructuring [duplicate]

This question already has answers here:
Destructuring to get the last element of an array in es6
(17 answers)
Closed 5 years ago.
I just discovered the delightful ES6 destructuring syntax for lists, i.e.
ls = [1, 2, 3]
[first, ...rest] = ls
which sets first to 1 and rest to [2,3]. However, is it possible to split the list into rest=[1,2] and last=3 using similar syntax?
I didn't have any luck googling it. I tried some obvious guesses for such a syntax (see below), but they all produced syntax errors.
[rest..., last] = ls
[...rest, last] = ls
I suppose I could do it by reversing the list twice, so an alternate solution to my question would be a constant time list reversal function.
What is commonly called "array destructuring" is actually destructuring an iterable, of which an array is a special case. The thing about iterables is that they can be infinite, or "lazy". That is the reason that you cannot destructure into some arbitrary number of elements followed by the last one:
const [...first, last] = integers();
because integers could be
function* integers() {
let n = 0;
while (true) yield n++;
}
and then what would last be?
No, this only works on trailing array elements. So, as you said, they way to achieve what you want would be reversing the array first.
Just in case you haven't come across a similar pattern for object, there is one:
const {a, ...rest} = {a: "prop1", b: "prop2", c: "prop3"}
A great tool to try all this new features out is https://babeljs.io/repl

Assigning objects in Javascript: shallow or deep copy? [duplicate]

This question already has answers here:
JavaScript by reference vs. by value [duplicate]
(4 answers)
Closed 7 years ago.
I want to know if javascript does shallow or deep copy when copying objects.
const a = ['value1', 'value2'];
const b = ['value3', 'value4'];
const new_ab = [a, b];
new_ab are going to have new allocated values or a reference? If it is a deep copy, how can I make it to be swallow? Thanks.
As alluded in the comments, JavaScript operates entirely on references, the only exception being that primitive values are kept on the stack and a program does not therefore require a reference to access them. In your example all variable declarations create new values - each an instance of Array - however what is returned from declaring an array is a reference, not the array itself. For example, [1, 2] is an array of values (integers), but [a, b] is an array of references.
So... nothing is copied. We can demonstrate this by placing an object as an element of an array and inspecting that a previously assigned property is still accessible through the new 'parent' array.
(And to answer your question in the comments, yes, your example is more performant than if you (or JavaScript) were to copy values.)
'use strict';
const arrayOne = [];
arrayOne.someProperty = "This string is a property of `arrayOne`, " +
"accessed via the reference to it in `arrayTwo`."
const arrayTwo = [arrayOne];
span.innerHTML = arrayTwo[0].someProperty;
<span id="span"></span>

Categories