Have the parenthesis in the javascript expression "(p) ? 1 : 0" any effect? - javascript

Take the following javascript:
var x = (p) ? 1 : 0;
p can be any value. It there any situation the parenthesis can have effect?
If so: please provide examples.

This is a bit of a contrived example, but hey, why not?
var y = -2;
var x = (y+=2)?0:1?1:0;
alert(x); // will alert '1'
versus
var y = -2;
var x = y+=2?0:1?1:0;
alert(x); // will alert '-2'
Check out this Javascript precedence table: http://www.codehouse.com/javascript/precedence/. Anything below the ternary operator (e.g. "?:") is going to require parentheses if you use it in ternary operator's evaluated expression.

In case p was divided into several boolean expressions with different operators, nested parenthesis can decide the order of how to expressions are computed. But I have the feeling you already know that, and it was not part of the question.
But no, parenthesis have no effect on p as a whole. And I don't know why would someone put them, for I don't think they improve readability.

I can't think of any reason you would need parenthesis there except for readability.

No. It's sometimes done by analogy with:
if (p)
where the brackets are compulsory.

Related

JavaScript : Expected and assignment or function call and instead saw an expression

I am using JSHint to ensure my JavaScript is "strict" and I'm getting the following error:
Expected an assignment or function call and instead saw an expression
On the following code:
var str = 'A=B|C=D'
var data = {};
var strArr = str.split( '|' );
for (var i = 0; i < strArr.length; i++) {
var a = strArr[i].split('=');
a[1] && (data[a[0].toLowerCase()] = a[1]); // Warning from JSHint
}
Any ideas why I'm getting such an error or how I can code to remove the error.
Here is a simplified version that gives the same warning:
var a, b;
a && (b = a);
Expected an assignment or function call and instead saw an expression
This means that you have an expression but do not assign the result to any variable. jshint doesn't care about what the actual expression is or that there are side effects. Even though you assign something inside of the expression, you are still ignoring the result of the expression.
There is another error by jslint if you care about it:
Unexpected assignment expression
This warns you that you may want to use == instead of = inside logical expressions. It's a common error, therefore you are discouraged to use assignments in logical expressions (even though it is exactly what you want here).
Basically, jshint/jslint do not like misuse of shortcut evaluation of logical operator as replacement for if statements. It assumes that if the result of an expression is not used, it probably shouldn't be an expression.
http://jshint.com/docs/options/#expr - JSHINT says, Expr warnings are part of relaxing options. So, if you write /* jshint expr: true */, it won't give you the warning. But, you have to know the scope of function too. If you just type this line on top of everything, it will apply this rule globally. So, even if you made a mistake on the other lines, jshint will ignore it. So, make sure you use this wisely. Try to use if for particular function ( i mean inside one function only)

Is <boolean expression> && statement() the same as if(<boolean expression>) statement()?

Are the two identical?
Suppose you have:
var x = true;
And then you have one of either:
x && doSomething();
or
if(x) doSomething();
Is there any differene whatsoever between the two syntaxes? Did I stumble across a nice bit of sugar?
Strictly speaking, they will produce the same results, but if you use the former case as a condition for something else, you will get dissimilar results. This is because in the case of x && doSomething(), doSomething() will return a value to signify its success.
No, they are not identical. While if is a statement, the AND operator is an expression.
That means you could use its result in an other expression, which you can't with an if-statement:
var result = x && doSomething();
Yet, in your case both have the same effect. Use the one that is more readable and represents your program structure better; I'd recommend the if-statement.
Short answer: No.
Long answer:
A stated by #Steve x && doSomething() is an expression,
whereas if(x) doSomething(); is a statement,
As suggested by #Daniel Li and #Bergi, think:
an expression is computed ( supposed to return a value here ).
a statement is declared ( not supposed to return a value here, think side-effects ).
Why is it confusing?
JS allows us to write ( thatExpression );
JS allows us to write thatExpression;
both assuming some kind of doNothingWithValueOf statement.
How to choose?
Do you use:
doSomething() as an
expression , think IsMyObjectWhatever() or MyObjectComputedValue(),
or as a statement, think ModifyMyObject()
And then: Do you use x && doSomething() as an expression ?
You'll end up thinking something like thisStatement( thatExpression ); everywhere, think:
() expression,
; statement.
Then why should I choose?
Obvious is that "It works." doesn´t stand for "It´s right".
If less obvious is when it will make the difference:
just think ()(()())()(); can be right, (;) is wrong.
check #wwaawaw Javascript: difference between a statement and an expression?
or expressions-vs-statements post by Axel Rauschmayer
In a word no, the two statements are not equal, though in the specific circumstances you present the outcome is the same.
x && doSomething(); is an expression, first the x evaluated, because this is an AND and since x is true the second argument (doSomething()) is then evaluated. In this case this means that the method is executed. If x were false then doSomething() would not be executed as the result of the expression cannot be true.
if(x) doSomething(); is a statement. The value of x is checked, and if it is true the scope of the if statement is executed.
I've put together this fiddle to demonstrate (with minor modifications).
Let's play detective.
We'll call our first approach Conditional Arrow Invocation and our second approach Traditional If Else.
We'll create two separate cases in jsperf to evaluate how these two approaches fair.
Conditional Arrow Invocations
const VALUE = true;
const TEST = false;
//test 1
VALUE && !TEST && (() => {
console.log('print me!');
})();
Ops/sec result:
FireFox: 65,152
Chrome: 129,045
Traditional If Else
const VALUE = true;
const TEST = false;
//test 2
if(VALUE && !TEST) {
console.log('print me!');
}
Ops/sec result:
FireFox: 65,967
Chrome: 130,499
Conclusion
As you can see, performance wise there isn't a huge difference but marginally Traditional If Else won over Conditional Arrow Invocation most of the times by an insignificantly small number. This might have something to do with creating an implicit function on the fly.
I also realized Chrome's JavaScript is a lot faster than FireFox's JavaScript execution.
Here is the jsperf link that you can run to evaluate this for yourself.
https://jsperf.com/conditional-methods-vs-traditional-if-else/1

Javascript: multiple variable declaration - when does the variable become available?

Let's say I'm declaring a list of variables in the following manner:
var a = "value_1"
, b = "value_2"
, c = b;
What is the expected value of c? In other words, is the scope of a variable immediately available after the comma, or not until the semicolon?
This is as opposed to the following code snippet, where it is very clear that the value of c will be "value_2":
var a = "value_1";
var b = "value_2";
var c = b;
I thought I'd ask rather than test in a browser and just assume that the behavior will be consistent.
See the comma operator:
The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand
So b = "value_2" is evaluated before c = b
It's not really an answer to the question, but when faced with such a choice between two expressions of the same thing, always choose the one which is the less ambiguous.
In your second code snippet, it's clear to everybody what the final state is. With the first one, well, you had to ask a question here to know :) If you come back to the code in a month from now, or if somebody else does, then you'll have to go through the same process of finding out the actual meaning. I don't think it's worth the 6 characters you're saving.

Are these line codes the same?

I want to know if these two scripts do the same thing:
parseInt(num)?num=parseInt(num):num=str.length
and
num=parseInt(num)||str.length;
And in case they are not, I need to know what the second do.
Yes they are same with later (short circuit evaluation) being terse and a beauty of JS (or other languages that support it):
num = parseInt(num) || str.length;
Both in turn are short-cut of this:
if (parseInt(num)){
num = parseInt(num);
}
else {
num = str.length;
}
Good Practices:
Don't foget var keyword before num variable otherwise it goes into global scope.
Always specify a base to parseInt eg parseInt(num, 10) unless otherwise needed
Readings:
Short-Circuit Evaluation
Ternary Operator
Yes, they do (but the second is very slightly more efficient as it doesn't have to run parseInt twice).
yes, they are equal. This is also the same:
num = parseInt(num)?parseInt(num):str.length

How does parentheses work in arrays? (javascript) [duplicate]

This question already has answers here:
What does the comma operator do in JavaScript?
(5 answers)
Closed 8 years ago.
I don't get why this.array[0] equals 1 if this.array[0] = [(2,1)]?
What does Javascript do with the 2 and how do i reach/use it? How does parenthesis work inside arrays?
I'd like to do different things with X if the boolean before it is true or false.
this.array[0] = [(true, X)] and this.array[0] = [(false, X)].
Parenthesis in that context act as a statement with the last item passed being the passed value.
In other words:
(2, 1) === 1
The 2 is evaluated, however, so:
(foo(), bar())
is effectively doing:
foo();
return bar();
What you want in this case is [2, 1]
If you use the comma operator inside parentheses, it evaluates both items and returns the second. This is rarely used, but there are two canonical reasons for using the comma operator:
Loop Logic
You can use the comma operator to have more complex login in a loop, like this:
for (var i = 0, j = 10; i < a && j > b; i++, j--) { }
Side Effect in Condition
You can use the comma operator to execute a statement before evaluating a condition, like this:
if (DoX(), CheckIfXHasBeenDoneSuccessfully()) { }
Other than that, the comma operator is basically naff. In your parentheses, (2,1), both 2 and 1 are evaluated and 2 is ignored and 1 is returned. You can use parentheses inside an array, but you will almost never want to put commas inside of the parentheses.
What I believe you want is something like this:
var bool = true; //or false, if you like
if(bool){ this.array[0] = X }
else { this.array[0] = Y }
its not the parens, its the incredibly arcane comma. What a comma will do is that it will evaluate each expression in turn, and return the result of the last one.
Your snippet is either a bug, or someone being an ass. Its the sort of thing that is only rarely useful, and probably shouldnt even be used in those times due to how confusing it is to people.
I think you want array[0] = [2,1].
In javascript, the expression
(2, 1)
evaluates to 1. The parentheses cause the expression 2, 1 to get evaluated before the brackets turn it into an array.
You actually want
this.array[0] = [false, X];

Categories

Resources