Array behavior confusion [duplicate] - javascript

This question already has answers here:
Why does [5,6,8,7][1,2] = 8 in JavaScript?
(3 answers)
Closed 7 years ago.
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?

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?");
}

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"

Related

javascript function output problrm [duplicate]

This question already has answers here:
Difference between pre-increment and post-increment in a loop?
(22 answers)
Closed 1 year ago.
The output of console.log(in1()) should be 11 but it's 10 why?
function outer() {
let i = 10;
return function inner() {
return i++;
}
}
var in1 = outer();
console.log(in1());
Quoting https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment here:
If used postfix, with operator after operand (for example, x++), the increment operator increments and returns the value before incrementing.
Therefore, the postfix (that is, x++; postfix because it appears after) operator only gives the existing value before doing anything. That's why, when called, gives what exists, not what's the result of the addition.
Because of this, use the prefix operator instead, ++x, to get the value while still incrementing the variable.
The same applies to the decrement operator.
It's because using i++ returns i first, then adds 1 to i. If you call in1() the second time, you will see 11, 12 and so on.
Try using ++i instead.
When using the postfix syntax i++ the value is returned before incrementing. Use the prefix syntax instead ++i.

Define Variables like a, b, c [duplicate]

This question already has answers here:
What does the comma operator do in JavaScript?
(5 answers)
Closed 3 years ago.
When I Define variables in JS like this:
var a, b, c = 10;
I found out when call a,b,c this phrase (Or any other term that can be used) gives 10 value.
Now, i'm wondered and my question is what is that? and what type of this phrase? (Returned Number in console)
What is its use?
var a, b, c = 10;
a,b,c; //10
a, b,c; //10
The comma has 2 different means depending on context.
You use it in both these ways in your code sample - this is probably causing some confusion.
1) Multiple variable assignment using var
var a,b,c = 10;
Here the var keyword is used to assign multiple variables on a single line, in your case you only assign the final variable c, and so a and b are undefined.
Here is an example which makes its usage clearer:
var a = 1, b = 2, c = 3;
a; // 1
b; // 2
c; // 3
2) JavaScript Comma Operator
a,b,c; // 10
The JavaScript comma operator evaluates a comma separated list of expressions and returns the result of the last one.

Why is [] !== [] in JavaScript? [duplicate]

This question already has answers here:
Why isn't [1,2,3] equal to itself in Javascript? [duplicate]
(6 answers)
Closed 4 years ago.
Why is [] !== [] in JavaScript?
I read through https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness but I could not find anything that explains this.
Edit:
I don't think this question or this question is an exact duplicate of mine. It asks about the == operator which just behaves crazy. The answer is an answer to my question but it's not the same question.
That does a reference check on the two array literals to see if they are the same instance. The fact that you have two literals means that you are constructing two separate arrays, therefore the reference check returns false. This would return true:
var a = []
var b = a
//b === a
This is because we have two references to the same array.
[] creates a new (and empty) array each time you write it. You are comparing two arrays, regardless of their content, their pointer (or reference) are being compared.
var array = [];
var anotherArray = array; // these two will point to the same array, so they are equal
array === anotherArray; // true
array === []; // false
array.push('something');
anotherArray.length; // 1
Because [] is an object, and a comparison of objects only returns true when both sides of the comparison point to the exact same object. You have created two separate objects, so they aren't equal.
var x = []
var y = x
var z = []
x == x // true
x == y // true
x == z // false

Difference between return ("abcd") and return "abcd"? [duplicate]

This question already has answers here:
Why use parentheses when returning in JavaScript?
(9 answers)
Closed 6 years ago.
I'm struggling with some JavaScript code that has examples that return a string in parens. Is there any difference between this:
var x = function() {
return "abcd";
}
And
var x = function() {
return ("abcd");
}
They are the same.
The parenthesis, i.e. grouping operator, here will just work as higher precedence, so that'll be evaluated first, and then the value will be returned.
There's no difference, at least in the way it is written.
Consider,
var x = 1 + 2;
vs
var x = (1 + 2);
Some prefer writing brackets around return statement but it is optional and often unnecessary. But I would advise stick to your existing code style.
In reference to this question the parenthesis do not have a specific meaning as a string is being returned. There is no expression evaluation involved so both the return statements work in the same way. In case we have an expression that needs to be evaluated, the parenthesis will provide a liberty to first evaluate the expression and then return the desired value according to the precedence rules.

JavaScript parentheses (1,2,3,4,5) [duplicate]

This question already has answers here:
Javascript expression in parentheses
(2 answers)
Closed 8 years ago.
I just came across some notation in JavaScript like so:
var a = (1,2,3,4,5);
This will always return the last value, in the above case 5. I'm aware of using brackets to namespace my JavaScript code, but have never seen it used this way.
Is there any use for this notation, or is it just some JavaScript byproduct?
It's the comma operator. As the mdn states (link) it always returns the later value. In your example it doesn't make much sense, since it will always assign a = 5. But consider this:
for (var i = 0, j = 9; i <= 9; i++, j--) {
...
}
It's used to increment and decrement in a single statement: i++, j--
Edit:
The parentheses in your example are necessary because its a variable declaration. In other cases they can be left out.
Parens are used to groups operations together. This is helpful for both setting operation precedence (e.g. x = (2+3) * 5 vs x = 2 + 3 * 5) and for making your code a little easier to read.
I suspect this is more a question about the comma operator. This is for making multiple assignments or operations on the same line. Here is a nice article about it: http://javascriptweblog.wordpress.com/2011/04/04/the-javascript-comma-operator/

Categories

Resources