Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array behavior confusion [duplicate]

Tags:

javascript

In a coding test I have recently encountered a question that asks me to find out what will be printed in console. The question is below. I did not understand how this below code will be understood and executed.

Need help

var arr = ["a" , "b" , "c" , "d"][1,2,3];
console.log(arr);

What does that arr definition even mean?

like image 596
Raviteja Avvari Avatar asked Mar 25 '15 07:03

Raviteja Avvari


2 Answers

Arrays in JS are one dimensional.

So var arr = ["a" , "b" , "c" , "d"][1,2,3];

Here [1,2,3] represents the indexes.

And comma is the least preceded operator so [1,2,3] will return you 3 (i.e. The right most element always).

Therefore

The result will return you the value at index 3 that's d

Update:

Let's see some more points for comma operator:

From MDN:

The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.

So, It means:

var a = (10, 18);
a; //18

Also note that it's essential to mention them inside brackets while assigning to a variable.

If you try something like:

var a = 1,2,3;
a; // will return 1

So it's important that you wrap them using ().

When will you use it , operator?

You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. The most common usage of this operator is to supply multiple parameters in a for loop.

for (var i = 0, j = 9; i <= 9; i++, j--)

Now that you've understood about comma operator, Let's see few more examples to test our understanding:

1.  var a = (1,3)/(2,1);
    a // what will be the o/p

2.  var a = ["Stack", "OverFlow","is","Awesome"][1,3,2][2,0]
    a // What will be the o/p

3.  var a = (true,0,1), b, c;
    if(b,c,a) {
        console.log("Will it execute?");
    }
like image 190
mohamedrias Avatar answered Sep 19 '22 06:09

mohamedrias


Your example caught me offguard. Here's another example which illustrates what is going on. Essentially a list of comma separated values evaluates to the value of the last.

if (false, false, true) {
    console.log("hello")
} 
// --> "hello"
like image 22
cdosborn Avatar answered Sep 21 '22 06:09

cdosborn