This question already has an answer here:
Increment a number by prefix and postfix operator
(1 answer)
Closed last year.
I'm struggling to understand the behaviour of Javascript's increment operator, and more specifically, why certain cases fail.
Why does adding increment operator on both sides of an argument fail?
EXAMPLE:
let a = 1;
++a++;
This returns a horrible error stating that:
ReferenceError: Invalid left-hand side expression in prefix operation
What does this mean, and should I be worried?
The increment operators work on variables, not on expressions. You can't increment a numeric expression:
3++ // Uncaught ReferenceError: Invalid left-hand side expression in postfix operation
The reason for this is that it must increment the value, then save it back to the variable. If you gave it any old numeric expression, what would it assign the result to?
One of the two operators will work, but it returns the result of the operation, which is an expression, not a variable:
++(a++)
The first operator, a++, will increment a, and return the result: 2. The second operator is then trying to perform the increment on the value 2, which is invalid syntax.
That code could be rewritten as: ++(a++) which would translate to ++(1), and then ++1, which is not a valid expression.
Related
I am trying to make a web-app in JavaScript that converts arithmetic expressions to i486-compatible assembly. You can see it here:
http://flatassembler.000webhostapp.com/compiler.html
I have tried to make it able to deal with expressions that contain the incremental and decremental operators ("--" and "++"). Now it appears to correctly deal with expressions such as:
c++
However, in a response to an expression such as:
c--
the web-app responds with:
Tokenizer error: Unable to assign the type to the operator '-' (whether it's unary or binary).
The error message seems quite self-explanatory. Namely, I made the tokenizer assign to the "-" operator a type (unary or binary) and put the parentheses where they are needed, so that the parser can deal with the expressions such as:
10 * -2
And now, because of that, I am not able to implement the decremental operator. I've been thinking about this for days, and I can't decide what to even try. Do you have any ideas?
Please note that the web-app now correctly deals with the expressions such as:
a - -b
The way that this works in all existing languages (that I know of anyway) that have these operators, is that -- is a single token. So when you see a -, you check whether the very next character is another -. If it is, you generate a -- token (consuming both - characters). If it isn't, you generate a - token (leaving the next character in the buffer).
Then in the parser an l-expression, followed by -- token becomes a postfix decrement expression and -- followed by an l-expression becomes a prefix decrement expression. A -- token in any other position is a syntax error.
This means that spaces between -s matter: --x is a prefix decrement (or a syntax error if the language doesn't allow prefix increment and decrement), - -x is a double negative that cancels out to just x.
I should also note that in languages where postfix increment/decrement is an expression, it evaluates to the original value of the operand, not the incremented value. So if x starts out as 5, the value of x++ should be 5 and afterwards the value of x should be 6. So your current code does not actually correctly implement postfix ++ (or at least not in a way consistent with other languages). Also x++ + y++ currently produces a syntax error, so it doesn't seem like it's really supported at all.
This question already has an answer here:
Increment a number by prefix and postfix operator
(1 answer)
Closed 5 years ago.
I was reading about Javascript operators precedence over here and got curious why I can't write something like this:
let num = 1;
++num++;
Which gets Uncaught ReferenceError: Invalid left-hand side expression in prefix operation error. But why is that? :)
It evaluates as
++(num++)
so, the expression
num++
returns a number, not the variable, because it is a primitive value. The added plusses, throws an exception, because a primitive value is not a variable and an assigment is not possible.
I’ve been looking for information about immediately invoked functions, and somewhere I stumbled on this notation:
+function(){console.log("Something.")}()
Can someone explain to me what the + sign in front of the function means/does?
It forces the parser to treat the part following the + as an expression. This is usually used for functions that are invoked immediately, e.g.:
+function() { console.log("Foo!"); }();
Without the + there, if the parser is in a state where it's expecting a statement (which can be an expression or several non-expression statements), the word function looks like the beginning of a function declaration rather than a function expression and so the () following it (the ones at the end of the line above) would be a syntax error (as would the absense of a name, in that example). With the +, it makes it a function expression, which means the name is optional and which results in a reference to the function, which can be invoked, so the parentheses are valid.
+ is just one of the options. It can also be -, !, ~, or just about any other unary operator. Alternately, you can use parentheses (this is more common, but neither more nor less correct syntactically):
(function() { console.log("Foo!"); })();
// or
(function() { console.log("Foo!"); }());
Subsidiary to #TJCrowder's answer, + is usually used to force numerical casting of a value as this SO answer explains. In this instance it is called the 'unary plus operator' (for ease of googling).
var num = +variant;
So in front of a function it can be a way to force the function's result to be interpreted as a number. I doubt it happens yet, but theoretically the JIT could use that to compile the function as a numerical-only function etc. However, to prevent the unary plus being a concatenation when used in a larger expression, you would need parentheses:
blah + (+(function(){ var scope; return "4"; })());
So the short answer is that it prevents a syntax error, by using the function results in one way or another.
You can also instruct the engine that you're not even interested in the return value by using the void operator:
void function() { console.log("Foo!"); }();
Of course, putting braces around the whole thing also serves that purpose.
TL;DR (Quick Answer)
Plus Sign Casts (Converts) the proceeding operand to a Number if it isn't already.
Solution & Origins
The + sign before the function, actually called Unary plus and is part of a group called a Unary Operators and (the Unary Plus) is used to convert string and other representations to numbers (integers or floats).
A unary operation is an operation with only one operand, i.e. a single
input. This is in contrast to binary operations, which use two
operands
Basic Uses:
const x = "1";
const y = "-1";
const n = "7.77";
console.log(+x);
// expected output: 1
console.log(+n);
// expected output: 7.77
console.log(+y);
// expected output: -1
console.log(+'');
// expected output: 0
console.log(+true);
// expected output: 1
console.log(+false);
// expected output: 0
console.log(+'hello');
// expected output: NaN
When the + sign is positioned before a variable, function or any returned string representations the output will be converted to integer or float; the unary operator (+) converts as well the non-string values true, false, and null.
Advanced Uses
The right way to use the function you mentioned above will be:
+function(){return "3.141"}()
// expected output: 3.141
I love to use + to turn a new Date() object to a timestamp, like this:
+new Date()
// expected output: 1641387991035
Other Unary Operators
- The unary negation operator converts its operand to Number type
and then negates it.
~ Bitwise NOT operator.
! Logical NOT operator.
delete The delete operator deletes a property from an object.
void The void operator discards an expression's return value.
typeof The typeof operator determines the type of a given object.
I’ve been looking for information about immediately invoked functions, and somewhere I stumbled on this notation:
+function(){console.log("Something.")}()
Can someone explain to me what the + sign in front of the function means/does?
It forces the parser to treat the part following the + as an expression. This is usually used for functions that are invoked immediately, e.g.:
+function() { console.log("Foo!"); }();
Without the + there, if the parser is in a state where it's expecting a statement (which can be an expression or several non-expression statements), the word function looks like the beginning of a function declaration rather than a function expression and so the () following it (the ones at the end of the line above) would be a syntax error (as would the absense of a name, in that example). With the +, it makes it a function expression, which means the name is optional and which results in a reference to the function, which can be invoked, so the parentheses are valid.
+ is just one of the options. It can also be -, !, ~, or just about any other unary operator. Alternately, you can use parentheses (this is more common, but neither more nor less correct syntactically):
(function() { console.log("Foo!"); })();
// or
(function() { console.log("Foo!"); }());
Subsidiary to #TJCrowder's answer, + is usually used to force numerical casting of a value as this SO answer explains. In this instance it is called the 'unary plus operator' (for ease of googling).
var num = +variant;
So in front of a function it can be a way to force the function's result to be interpreted as a number. I doubt it happens yet, but theoretically the JIT could use that to compile the function as a numerical-only function etc. However, to prevent the unary plus being a concatenation when used in a larger expression, you would need parentheses:
blah + (+(function(){ var scope; return "4"; })());
So the short answer is that it prevents a syntax error, by using the function results in one way or another.
You can also instruct the engine that you're not even interested in the return value by using the void operator:
void function() { console.log("Foo!"); }();
Of course, putting braces around the whole thing also serves that purpose.
TL;DR (Quick Answer)
Plus Sign Casts (Converts) the proceeding operand to a Number if it isn't already.
Solution & Origins
The + sign before the function, actually called Unary plus and is part of a group called a Unary Operators and (the Unary Plus) is used to convert string and other representations to numbers (integers or floats).
A unary operation is an operation with only one operand, i.e. a single
input. This is in contrast to binary operations, which use two
operands
Basic Uses:
const x = "1";
const y = "-1";
const n = "7.77";
console.log(+x);
// expected output: 1
console.log(+n);
// expected output: 7.77
console.log(+y);
// expected output: -1
console.log(+'');
// expected output: 0
console.log(+true);
// expected output: 1
console.log(+false);
// expected output: 0
console.log(+'hello');
// expected output: NaN
When the + sign is positioned before a variable, function or any returned string representations the output will be converted to integer or float; the unary operator (+) converts as well the non-string values true, false, and null.
Advanced Uses
The right way to use the function you mentioned above will be:
+function(){return "3.141"}()
// expected output: 3.141
I love to use + to turn a new Date() object to a timestamp, like this:
+new Date()
// expected output: 1641387991035
Other Unary Operators
- The unary negation operator converts its operand to Number type
and then negates it.
~ Bitwise NOT operator.
! Logical NOT operator.
delete The delete operator deletes a property from an object.
void The void operator discards an expression's return value.
typeof The typeof operator determines the type of a given object.
I’ve been looking for information about immediately invoked functions, and somewhere I stumbled on this notation:
+function(){console.log("Something.")}()
Can someone explain to me what the + sign in front of the function means/does?
It forces the parser to treat the part following the + as an expression. This is usually used for functions that are invoked immediately, e.g.:
+function() { console.log("Foo!"); }();
Without the + there, if the parser is in a state where it's expecting a statement (which can be an expression or several non-expression statements), the word function looks like the beginning of a function declaration rather than a function expression and so the () following it (the ones at the end of the line above) would be a syntax error (as would the absense of a name, in that example). With the +, it makes it a function expression, which means the name is optional and which results in a reference to the function, which can be invoked, so the parentheses are valid.
+ is just one of the options. It can also be -, !, ~, or just about any other unary operator. Alternately, you can use parentheses (this is more common, but neither more nor less correct syntactically):
(function() { console.log("Foo!"); })();
// or
(function() { console.log("Foo!"); }());
Subsidiary to #TJCrowder's answer, + is usually used to force numerical casting of a value as this SO answer explains. In this instance it is called the 'unary plus operator' (for ease of googling).
var num = +variant;
So in front of a function it can be a way to force the function's result to be interpreted as a number. I doubt it happens yet, but theoretically the JIT could use that to compile the function as a numerical-only function etc. However, to prevent the unary plus being a concatenation when used in a larger expression, you would need parentheses:
blah + (+(function(){ var scope; return "4"; })());
So the short answer is that it prevents a syntax error, by using the function results in one way or another.
You can also instruct the engine that you're not even interested in the return value by using the void operator:
void function() { console.log("Foo!"); }();
Of course, putting braces around the whole thing also serves that purpose.
TL;DR (Quick Answer)
Plus Sign Casts (Converts) the proceeding operand to a Number if it isn't already.
Solution & Origins
The + sign before the function, actually called Unary plus and is part of a group called a Unary Operators and (the Unary Plus) is used to convert string and other representations to numbers (integers or floats).
A unary operation is an operation with only one operand, i.e. a single
input. This is in contrast to binary operations, which use two
operands
Basic Uses:
const x = "1";
const y = "-1";
const n = "7.77";
console.log(+x);
// expected output: 1
console.log(+n);
// expected output: 7.77
console.log(+y);
// expected output: -1
console.log(+'');
// expected output: 0
console.log(+true);
// expected output: 1
console.log(+false);
// expected output: 0
console.log(+'hello');
// expected output: NaN
When the + sign is positioned before a variable, function or any returned string representations the output will be converted to integer or float; the unary operator (+) converts as well the non-string values true, false, and null.
Advanced Uses
The right way to use the function you mentioned above will be:
+function(){return "3.141"}()
// expected output: 3.141
I love to use + to turn a new Date() object to a timestamp, like this:
+new Date()
// expected output: 1641387991035
Other Unary Operators
- The unary negation operator converts its operand to Number type
and then negates it.
~ Bitwise NOT operator.
! Logical NOT operator.
delete The delete operator deletes a property from an object.
void The void operator discards an expression's return value.
typeof The typeof operator determines the type of a given object.