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

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.

Related

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]]

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

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}`);
});

JS arrays - advanced assignment [duplicate]

This question already has answers here:
How do I replace a character at a particular index in JavaScript?
(30 answers)
Closed 6 years ago.
This is related to the arrays in Javascript, which I am trying to use in a complex logic.
Consider the following code:
a['a1'] = 'AJA'
We know that, this is same as a.a1 = 'AJA' (provided proper definitions were given).
So, if we go ahead and interpret this:
console.log(a.a1[0])
console.log(a.a1[1])
console.log(a.a1[2])
console.log(a.a1)
It logs :
A
J
A
AJA
Now, all I need is to assign a new character at the 4th position.
When I try a[a1][3] = 'Y' or a.a1[3] = 'Y' and then try console.log(a.a1), It still displays AJA instead of AJAY.
I know that we can do this using string concatenation, i.e.
a['a1'] = a['a1'] + 'Y' and get this accomplished.
But why wasn't the first method working? By what other ways can do this?
Strings are immutable. It means that if you create a string, you can't modify it anymore. So your a1 doesn't know anything about 4th character.
You can see this example. I try to change the second char of the already created string, but it will not be changed anymore.
let a = {};
a['a1'] = 'AJA';
a.a1[1] = 'A';
console.log(a.a1);
For more you can see MDN Documentation
As I know a[a1][3] or a.a1[3] is a string variable, you can treat it as:
var s = 'ss';
When you evaluate s[0] you'll get a string value. So when you assign any string value to s, you'll not get 'ss' + anyvalue but anyvalue instead. :)

Use a variable inside a dictionary (associative array) in javascript [duplicate]

This question already has answers here:
Is it possible to define a dynamically named property using object literal in JavaScript? [duplicate]
(7 answers)
Closed 8 years ago.
I have this particular script which uses a javascript dictonary
var z= 'Bingo';
var fruit={ 'Bingo' :1};
var fruit2={ z :1};
alert(fruit[z]);
alert(fruit2[z]);
alert(fruit2['z']);
The first alert gives the expected value 1. However, the second alert gives the alert value as "undefined" and third alert gives the output as 1. Is there a way to use a variable inside a dictionary, ie. can we specify the javascript interpreter to read z as a variable rather than as string 'z'?
Thanks!
Yes, you can do this easily, but not inside an object literal. Property names in object literals are taken literally. They are not variable names. JavaScript quotes them implicitly if you don't quote them.
For example, these two object literals are the same:
{ a: 1 }
{ 'a': 1 }
To use a variable, you need to use [] notation outside an object literal:
var z = 'Bingo';
var fruit2 = {};
fruit2[z] = 1;

Difference between "new Array(..)" and "[..]" in JavaScript? [duplicate]

This question already has answers here:
What’s the difference between "Array()" and "[]" while declaring a JavaScript array?
(19 answers)
Closed 8 years ago.
Is
var myCars=new Array("Saab","Volvo","BMW");
and
var myCars=["Saab","Volvo","BMW"];
exactly the same ?
Yes, for that case they are the same.
There is a difference if you have only one item, and it's numeric. This will create an array with a single item:
var myNumbers = [42];
but this will create an array with the length 42:
var myNumbers = new Array(42);
Yes, they are. However be aware that when you pass just a single numeric parameter to the Array constructor, you will be specifying the initial length of the array, instead of the value of the first item. Therefore:
var myCars1 = new Array(10);
... will behave differently from the following array literal:
var myCars2 = [10];
... note the following:
console.log(myCars1[0]); // returns undefined
console.log(myCars1.length); // returns 10
console.log(myCars2[0]); // returns 10
console.log(myCars2.length); // returns 1
That is one reason why it is often recommended to stick to the array literal notation: var x = [].
Yes, they are the same. There is no primitive form of an Array, as arrays in JavaScript are always objects. The first notation (new Array constructor syntax) was used heavily in the early days of JavaScript where the latter, short notation was not supported well.
Note that there is one behavioural difference: if you pass a single, numeric argument to new Array, like new Array(20), it will return a new array pre-initialised with that number of elements from 0 to n - 1, set to undefined.

Categories