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

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

Related

how does javascript work when add number with array [duplicate]

This question already has answers here:
Why is [1,2] + [3,4] = "1,23,4" in JavaScript?
(14 answers)
Closed 5 years ago.
var array = [1,2,4];
array+1 //gives '1,2,41'.
Can anyone explain this behaviour?
Can anyone explain this behaviour?
This answer attempts to explain this behavior from the point of view of spec.
As per spec, during the run-time evaluation of +, both expressions (left and right) are converted to their primitive values.
Let lprim be ToPrimitive(lval).
Let rprim be ToPrimitive(rval).
toPrimitive tries to pass hint:number (since invoked during arithmetic evaluation) to OrdinaryToPrimitive
If hint is "string", then
a. Let methodNames be «"toString", "valueOf"».
Else,
b. Let methodNames be «"valueOf", "toString"». //this gets invoked
Since one of the values were casted to string via 4a) above, string concatenation takes place.
Hence
[1,2,4] + 1 => [1,2,4].toString() + "1" => "1,2,4" + "1" => (finally) "1,2,41"
Array is casted to string - then concatenated with integer value which is also casted to string.
When you use the + sign with a declared javascipt object (var array), even if one of the elements is a number, it doesn't perform an arithmetic addition operation - it concatenates the values as two strings.
In your example, your array [1,2,4] is being casted into a string with a value of 1,2,4. So 1,2,4 concatenated with 1 is 1,2,41
What did you expect? [2,3,5]?
You haven't wrote a mutator for array, you added 1 to array (which is an object). Why do you expect for object to be able to add 1 to it?
JS figured out you need a primitive from that object and listed that object into a string. Now it knows how to "add" 2 strings (precisely its concatenate) so it did.
If you expected an entire array to get +1 on all elements. You want:
for (var i=array .length; i--;) {
array [i]++;
}
Or
array = array.map(function(e) {return '#' + e});
Or in ES6 and beyond arrow function with map
array = array.map(i => i + 1);
When the operands of an operator are different types, they will be converted to a common type.
Both an array and a Number can be converted to string, this is called coercion.
If you would like to add 1 to an array, you can do this:
var array = [1,2,4];
array.push(1);

On arrow function bodies, whats the difference between using brackets, placing direclty the condition, or using pharentesis? [duplicate]

This question already has answers here:
When do we have to use () and {} in ES6 Arrow Functions
(2 answers)
Arrow function without curly braces
(9 answers)
Curly Brackets in Arrow Functions
(3 answers)
What does the comma operator do in JavaScript?
(5 answers)
Closed 2 months ago.
In my years of JS development I've seen the following examples:
let a = () => console.log("a");
let b = () => { console.log("b"); }
let c = () => (console.log("c"));
I know the difference between the first two options, but the last one always seem'd a little off to me. I've also tried to do the following, which surprisingly works:
let c = () => (console.log("c1"), console.log("c2")); // Outputs both console logs.
And also this:
let c = () => (1, 2, 3, 4 ,5);
let x = c(); // 5
I've searched about this way of defining function bodies, yet I'm not satisfied with what I have found since every example I've stumbled on was poorly explained.
Can anyone please explain to me a bit more in-depth the difference between the three examples, and also what's special about the last one?
Thanks in advance.
let c = () => (console.log("c"))
I know the difference between the first two options, but the last one always seem'd a little off to me.
Arrow syntax allows you to return the value of the expression directly without having to enclose in curly braces and using a return statement. In the example above, enclosing the value (returned by console.log) in brackets does not change its value.
And also this:
let c = () => (1, 2, 3, 4, 5);
What you are seeing is the comma operator in action. It will return the value of the last operand, which is why c returns 5.
I've also tried to do the following, which surprisingly works:
let c = () => (console.log("c1"), console.log("c2")); // Outputs both console log
In this case, both expressions are evaluated, and thus both strings are logged. However, the expression yields a value of undefined, since console.log returns undefined.
First of all, you're talking specifically about arrow (=>) functions. Traditional functions must have a body enclosed in { }.
An arrow function can have a traditional body enclosed in { }. It can also have a single expression as its body, in which case the result of evaluating the expression is implicitly the return value. Given that, note that any expression in JavaScript in any context can be enclosed in parentheses ( ) and the value is the same as the enclosed expression.
The comma effect is the operator in the JavaScript expression grammar ,, which allows disparate expressions to be chained together into a list that, syntactically, is still a single expression. The comma operator is useful sometimes because expressions can have side-effects; for example, a function call is an expression, and a function call may do almost anything. The value of a list of expressions in a comma operator list is the value of the last one of the expressions after evaluation.

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.

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. :)

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