JavaScript concating with number as string - javascript

Why does x = "1"- -"1" work and set the value of x to 2?
Why doesn't x = "1"--"1" works?

This expression...
"1"- -"1"
... is processed as ...
"1"- (-"1")
... that is, substract result of unary minus operation applied to "1" from "1". Now, both unary and binary minus operations make sense to be applied for Numbers only - so JS converts its operands to Numbers first. So that'll essentially becomes:
Number("1") - (-(Number("1"))
... that'll eventually becomes evaluated to 2, as Number("1"), as you probably expect, evaluates to 1.
When trying to understand "1"--"1" expression, JS parser attempts to consume as many characters as possible. That's why this expression "1"-- is processed first.
But it makes no sense, as auto-increment/decrement operations are not defined for literals. Both ++ and -- (both in postfix and prefix forms) should change the value of some assignable ('left-value') expression - variable name, object property etc.
In this case, however, there's nothing to change: "1" literal is always "1". )
Actually, I got a bit different errors (for x = "1"--"1") both in Firefox:
SyntaxError: invalid decrement operand
... and Chrome Canary:
ReferenceError: Invalid left-hand side expression in postfix operation
And I think these messages actually show the reason of that error quite clearly. )

Because -- is an operator in JavaScript.
When you separate the - characters in the first expression, it's unambiguous what you mean. When you put them together, JavaScript interprets them as one operator, and the following "1" as an unexpected string. (Or maybe it's the preceding "1"? I'm honestly not sure.)

"-1" = -1 (unary minus converts it to int)
So. "1" - (-1)
now, "+" is thje concatenation operator. not -. so JS returns the result 2 (instead of string concat).
also, "1"--"1" => here "--" is the decrement operator, for which the syntax is wrong as strings will not get converted automatically in this case.

because -- is an operator for decrement and cannot be applied on constant values.

Related

Increment a number by prefix and postfix operator

By mistake, I wrote:
++number++;
and got this:
Uncaught ReferenceError: Invalid left-hand side expression in prefix operation
Why? I would except this to to first increment number by one and then increment number by one again.
In JavaScript, ++ is both the prefix and postfix increment operator. The postfix operator has higher precedence, and so when we apply precedence, your expression becomes:
++(number++);
The result of number++ is a value, not a variable reference, and so it cannot be the operand of the prefix increment operator, for the same reason ++42 is invalid — there's nowhere to write the result back to.
Why does it call it the "left-hand side expression" when it's to the right of the operator? You'd have to look at the V8 source code (I can tell from the text of the error you're doing this on V8, probably Chrome). I can speculate that it's because many operators accept two operands (left and right), and that they just call the only operand to unary operators like ++ the "left-hand" by default. But that's speculation.

Why does 1|0,2|0 equal 2 in JavaScript?

If you evaluate 1|0,2|0 in JavaScript, you'll get 2.
If you evaluate 1|0+','+2|0, you'll get 1.
I cannot make sense of this.
The binary bitwise operators (including |) bind less tightly than the addition operator +. Thus
1|0+','+2|0
is really
1|(0+','+2)|0
which is
1|('0,2')|0
which is
1|0|0
which is 1. (The string "0,2" is converted to an integer; as a number it's NaN, but because NaN is a floating-point concept it turns into 0 when forced to be an integer.)
edit — as to the first expression, 1|0,2|0, that involves the JavaScript comma operator. The comma operator allows a list of separate, essentially independent (other than through side-effects) expressions to be "glued together" into something the parser will recognize as a single expression. When evaluated, each expression will be computed as it normally would be, but the value of the overall expression is just the value of the last one in the list. Thus, 1|0,2|0 will first cause 1|0 to be evaluated, but that result is thrown away and the overall value is just that of 2|0.
The comma operator is common to many languages that derive their expression syntax from C. (For all I know, C got it from somewhere else; it's hardly a revolutionary concept.) Because such languages allow for an expression — just one expression — to appear in several interesting grammatical situations, and because expressions can (and often do) have side effects, it's sometimes handy to be able to jam several separate expressions into a spot where the language really wants only one. That said, there are often cleaner and better ways to do things. In JavaScript, I would personally prefer to use an immediately-invoked function. It's more typing and probably a little worse for performance reasons, but I think it's a lot cleaner because it allows for an isolated namespace for temporary variables and more involved logic.
You need to look at an operator precedence table to make sense of this.
The expression 1|0,2|0 has bitwise-or at a higher precedence than the comma operator, so it's equivalent to (1|0), (2|0). The comma operator evaluates both operands and returns the second one, so you get the value of (2|0). That value is 2.
The expression 1|0+','+2|0 has addition at a higher precedence than bitwise-or, so it's equivalent to 1|(0+','+2)|0. The result of 0+','+2 is "0,2", which is not numerical, so it evaluates to NaN in numerical operations. It is coerced to 0 in bitwise-or, so that leaves 1|0|0, and the result of that is 1.
From MDN:
The comma operator evaluates both of its operands (from left to right)
and returns the value of the second operand.
Thus, in 1|0,2|0, first the two expressions 1|0 and 2|0 are evaluated from left to right and then the result of the last expression (2|0) is returned. 1|0 === 1 and 2|0 === 2, so the result of the last expression is 2 and that's returned.
In 1|0+','+2|0, the comma appears in a string literal which is concatenated with 0 and 2. The whole thing is evaluated as followed:
( 1 | ( (0+',')+2 ) ) | 0
( 1 | ( '0,'+2 ) ) ) | 0 (number + string = string concatenation)
( 1 | '0,2' ) | 0 (string + number = string concatenation)
( 1 | NaN ) | 0 (bitwise OR needs number operands. 0,2 fails to be converted, giving NaN instead)
1 | 0 (bitwise OR only deals with integers, so the floating-point NaN is cast to 0)
1

Javascript Compiler behavior - double plus for array of empty array and array of zero is.. ONE

My question may be already answered, but I could not find it not in Search Engines google or bing doesn't like '+' (plus) sign in search request.
Anyway, why this is zero
+[[]][0] // = 0
and this is one
++[[]][0] // = 1
UPD:
Michael Berkowski have a good answer, but I steal don't understand one thing
if [[]][0] evaluates to an empty array, then why ++[] is ReferenceError: Invalid left-hand side expression in prefix operation
UPD2:
now I get it.. it seems I was trying to type ++0 in console and getting an Error, but I should be using var a = 0; ++a
This is best explored by breaking down the way its components evaluate.
[[]][0] alone evaluates to the empty array []. By adding + in front, you cast its string representation to an integer 0 (like saying +4 or -3) via a unary positive operator. +0 is just 0.
++ as a numeric operator, also casts the empty string to an integer 0, but applies its operation (the prefix increment) resulting 1.
[[]][0]
// [] empty array
[[]][0].toString()
// ""
// Unary + casts the empty string to an integer
+("")
// 0
// Prefix increment on an empty string results in 1 (increments the 0)
var emptyString = "";
++emptyString;
// 1

Javascript + operator vs - operator

I am puzzled by this snippet:
var n1 = 5-"4";
var n2 = 5+"4";
alert(n1);
alert(n2);
​I understand that n1 is 1. That is because a minus operator would convert the string "4" into number and subtract it from 5.
But why do we get 54 in case of + operator?
Can someone explain this difference between + and = operators to me?
By type conversion any + expression, that contains a strings, will result in a string. Thus all operands (in your case 5) will be converted to a string, before executing the concatenation.
- on the other hand is just an arithmetic operand, thus "4" is converted to an integer and the calculation is performed as you expect.
It's because in n2, + is being treated as concatenation, not addition. So 5 is converted to the string "5" and "4" is concatenated, giving "54".
When there's a string in either side of +, the + will be considered as a string concatenating operator, the other side will be converted to string and then do the concatenating.
And be careful of something like 1+2+'3', the result is '33' rather than '123'.
- operator has only one meaning - numbers subtraction (or negation and in that case, also conversion to number). In case of + operator, however, there are two: number addition and strings concatenation. When one of the operands of + operator is a string it does string concatenation instead of numbers addition.
The entire process is a bit more complicated than that though and involves an algorithm that you can learn a bit more here, for example.
The + operator is also a string operator. Quite every basic type variable in javascript can be interpreted also in its string representation. You are just attaching 5 to 4 getting 54.
The - operator is not a string operator so the compiler tries to interpret "4" as a number, thus getting 1
Javascript takes 5 as a number and "4" as string.
The javascript + operator use to concat two things.
If you want to addition please use parseInt.
var n1 = 5-"4";
var n2 = parseInt(5)+parseInt("4");
alert(n1);
alert(n2);

Javascript Unexpected Behaviour during Subtraction

Hi i have a javascript code like this
var a=10;
var b="100";
document.write(b-a);
Actually it should show an error when we are subtracting a number from a string but it is showing as 90 as output but when we do b+a it is showing 10010 as output what is this behaviour.
the - operator in JavaScript only applies to math, so your vars are both converted to numbers. You'll only get an error (or more specifically NaN) if you try to do invalid math, e.g. 100 - 'a'. The + operator is valid for both strings and numbers, so its behavior changes:
If both vars are numbers, mathematical additions is used
otherwise string concatenation is used
When you subtract, Javascript attempts to cast the String b to Number, because there is no - operation defined for String.
When you use the + sign, Javascript attempts to cast the Number a to a String, because + is defined as concatenation for a String.

Categories