POSTFIX and PREFIX increment/decrement precedence in JavaScript - javascript

I've been coding for years and suddenly stuck to some simple thing about operators precedence in case of increment/decrement operators.
According to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
the postfix increment/decrement has higher priority than the prefix one.
So, I expect that in expression
x = --a + a++;
the increment will be calculated first and only after that the decrement.
But, in tests this expression calculates left-to-right like that operators have the same priority. And as result
a=1;x = --a + a++ equals to 0 instead of 2.
Ok. Assuming that prefix/postfix operators have the same precedence, I try to reorder it with parentheses:
a=1;x = --a + ( a++ )
But again, the result will be 0 and not 2 as I expected.
Can someone explain that please? why parentheses here do not affect anything? How can I see that postfix has higher precedence than prefix?

In the expression, evaluation proceeds like this:
--a is evaluated. The variable a is decremented, and the value of --a is therefore 0.
a++ is evaluated. The value of a is obtained, and then a is incremented. The value of a++ is therefore 0.
The + operation is performed, and the result is 0.
The final value of a is 1.
Because --a and a++ are on either side of the lower-precedence + operator, the difference in precedence between pre-decrement and post-increment doesn't matter; the + operator evaluates the left-hand subexpression before it evaluates the right-hand subexpression.

Operator precedence is not the same thing as evaluation order.
Operator precedence tells you that
f() + g() * h()
is parsed as
f() + (g() * h())
(because * has higher precedence than +), but not which function is called first. That is controlled by evaluation order, which in JavaScript is always left-to-right.
Parentheses only override precedence (i.e. they affect how subexpressions are grouped), not order of evaluation:
(f() + g()) * h()
performs addition before multiplication, but in all cases f is called first and h last.
In your example
--a + a++
the relative precedence of prefix -- and postfix ++ doesn't matter because they're not attached to the same operand. Infix + has much lower precedence, so this expression parses as
(--a) + (a++)
As always, JS expressions are evaluated from left to right, so --a is done first.
If you had written
--a++
that would have been parsed as
--(a++)
(and not (--a)++) because postfix ++ has higher precedence, but the difference doesn't matter here because either version is an error: You can't increment/decrement the result of another increment/decrement operation.
However, in the operator precedence table you can see that all prefix operators have the same precedence, so we can show an alternative:
// ! has the same precedence as prefix ++
!a++
is valid code because it parses as !(a++) due to postfix ++ having higher precedence than !. If it didn't, it would be interpreted as (!a)++, which is an error.

Well, it strange, but looks like increment/decrement behaves in expressions like a function call, not like an operator.
I could not find any documentation regarding order of function evaluations in expression, but looks like it ignores any precedence rules. So strange expression like that:
console.log(1) + console.log(2)* ( console.log(3) + console.log(4))
will show 1234 in console. That the only explanation I could found why parentheses do not affect to order of evaluation of dec/inc in expressions

Related

Meaning of + on javascript autoexecutable function [duplicate]

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.

Clarification of Operand in Variable Assignment

I am doing this for the benefit of Javascript but the knowledge and terms cross all languages I would imagine. This is why I included JAVA and C as programmers knowledge on the subject from these fields are generally higher level.
If the question has been posed and answered, kindly just let me know.
I understand the basics of operators and operands.
1 + 2 = 3
1 and 2 are the operands and + is the operator. Solutions to the expression are not considered operands as they are the returned value.
If I am wrong with this summary please let me know
My question is that in assigning a value to variable
var x = 1
Is the variable considered to be the operand in this instance? My guess would be yes, as x is being assigned via an operator the value 1. But is it not, or are both x and 1 the operands with = being the assignment operator as the solution is x is now 1.
= is a simple assignment operator that assigns values from right side operands to the variable on the left side.
Example: x = y + z will assign value of y + z into x
So it is clear that = is an operator having left and right sides as operands.
The java spec tells us the following about the assignment operator:
The result of the first operand of an assignment operator must be a variable
So yes, the left hand side of the assignment operator is an operand.
A little further on we can read:
Next, the right hand operand is evaluated.
So the right hand side is an operand too!
Although i don't know why it would be important to know if the java developers call the left/right hand side of an assignment an 'operand' or not!

javascript +function ($) { ... }(jQuery) [duplicate]

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.

What is the purpose for multiple comma-separated expressions in a WHILE condition?

I stumbled over the following JavaScript:
Code:
var x="", i=0;
while (i<4, i<7, i<5, i<6)
{
x=x + "The number is " + i + "<br>";
i++;
}
document.write(x);
I never know that it is possible to use multiple comma-separated expression in one WHILE statement.
Result:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
What is the reason for this and what is the behavior (only the last expression is evaluated for the while-exit)?
Is the behavior standardize in all Javascript/C/Java languages?
Only the last result is kept in result of the comma operator, so
while (i<4, i<7, i<5, i<6)
is really equivalent to
while (i<6)
That's the reason why you don't see this more often : it's useless if your comparisons don't have side effects.
This is a special operator in JavaScript which is called comma operator;
so when JavaScript comes across this line
(i<4, i<7, i<5, i<6)
it will evaluate one by one all the operands in the parenthesis and will return the evaluation of the last item i.e. i < 6
It is rarely used; One occasion that I remember to have used it was for indirect call to eval.
(0, eval)(src)
But again in you example the use of it is redundant.

JavaScript plus sign in front of function expression

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.

Categories

Resources