Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does [5,6,8,7][1,2] = 8 in JavaScript?

Tags:

javascript

People also ask

What does {} mean in JavaScript?

google doesn't have value (undefined, null) then use {} . It is a way of assigning a default value to a variable in JavaScript.

What is the result of 2 2 in JavaScript?

In our previous blog post we looked at how to retrieve values from various HTML form controls. For instance the following JavaScript code shows you how to retrieve the value typed in a textbox.

What does 1 mean in JavaScript?

It means "subtract one from the previous value". Same thing it always means. Possibly you intended to ask "why is it there?" In that case, the answer is that JavaScript arrays are zero-indexed, which means the last index in the array is one less than the length of the array (because the first index is 0, not 1).

What is the correct syntax to create an array in JavaScript?

Creating an Array Using an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [item1, item2, ...]; It is a common practice to declare arrays with the const keyword.


[1,2,3,4,5,6][1,2,3];
      ^         ^
      |         |
    array       + — array subscript access operation,
                    where index is `1,2,3`,
                    which is an expression that evaluates to `3`.

The second [...] cannot be an array, so it’s an array subscript operation. And the contents of a subscript operation are not a delimited list of operands, but a single expression.

Read more about the comma operator here.


Because (1,2) == 2. You've stumbled across the comma operator (or simpler explanation here).

Unless commas appear in a declaration list, parameter list, object or array literal, they act like any other binary operator. x, y evaluates x, then evaluates y and yields that as the result.


[1,2,3,4,5,6][1,2,3];

Here the second box i.e. [1,2,3] becomes [3] i.e. the last item so the result will be 4 for example if you keep [1,2,3,4,5,6] in an array

var arr=[1,2,3,4,5,6];

arr[3]; // as [1,2,3] in the place of index is equal to [3]

similarly

*var arr2=[1,2,3,4,5,6];

 // arr[1,2] or arr[2] will give 3*

But when you place a + operator in between then the second square bracket is not for mentioning index. It is rather another array That's why you get

[1,2,3] + [1,2] = 1,2,31,2

i.e.

var arr_1=[1,2,3];

var arr_2=[1,2];

arr_1 + arr_2; // i.e.  1,2,31,2

Basically in the first case it is used as index of array and in the second case it is itself an array.