Does EcmaScript have "reverse if notation"? - javascript

The normal way to write an if-statement is
if (a == b) {a=1}
but in eg. Perl it is possible to write the same as
a=1 if (a == b)
Question
Is a similar syntax possible with EcmaScript?

There is not a specific statement to do that. You still have several options though
if (a == b) {
a = 1
}
if (a == b) a = 1 // No parenthesis
a == b ? a = 1 : null // Using ternary operator
a = a == b ? 1 : a // Using ternary operator

Related

Using and (&&) and or (||) together in the same condition in JavaScript

I'm wondering how to combine and (&&) with or (||) in JavaScript.
I want to check if either both a and b equal 1 or if both c and d equal 1.
I've tried this:
if (a == 1 && b == 1 || c == 1 && d == 1)
{
//Do something
}
But it doesn't work.
How can I write this condition correctly?
&& precedes ||. == precedes both of them.
From your minimal example I don't see, why it doesn't achieve your desired effect. What kind of value types do a–d have? JavaScript might have some non-obvious type coercion going on. Maybe try comparing with === or convert to numbers explicitly.
Side note: many lint tools for C-like languages recommend to throw in parentheses for readability when mixing logical operators.
Operator Precedence can be overridden by placing the expression between parenthesis.
if ((+a == 1 && +b == 1) || (+c == 1 && +d == 1)) // Use brackets to group them
{
// your code
}
This will prevent you from such cases like if(0&&0 || 1&&1) .
Well now that I've finished telling everybody else (except David) why their answers are wrong, let me give them the same chance to hassle me.
Your existing code as shown should already do what you seem to be describing. But is it possible that when you say:
"I want to check if either both a and b equals 1 or if both c and d equals 1."
...your use of the word "either" mean that you want to check if one and only one of the following conditions is true:
both a and b are 1, but c and d are not both 1
both c and d are 1, but a and b are not both 1
That is, you want one pair of variables to be 1, but you don't want all four variables to be 1 at the same time?
If so, that is an exclusive OR operation, which in JS is the ^ operator:
if ((a == 1 && b == 1) ^ (c == 1 && d == 1)) {
Note that unlike with a logical OR || operator, you have to add parentheses around the AND && parts of the expression because ^ has higher precendence. (^ is actually a bitwise operator, but it will work for you here since the operands you'd be using with it are all booleans.)
place some extra brackets to differentiate the and n or conditions
if ((a == 1 && b == 1) || (c == 1 && d == 1))

Why is the Javascript operator "&&" so weird?

a = 1;
b = "1";
if (a == b && a = 1) {
console.log("a==b");
}
The Javascript code above will result in an error in the if statement in Google Chrome 26.0.1410.43:
Uncaught ReferenceError: Invalid left-hand side in assignment
I think this is because the variable a in the second part of the statement &&, a=1 cannot be assigned. However, when I try the code below, I'm totally confused!
a = 1;
b = "1";
if (a = 1 && a == b) {
console.log("a==b");
}
Why is the one statement right but the other statement wrong?
= has lower operator precendence than both && and ==, which means that your first assignment turns into
if ((a == b && a) = 1) {
Since you can't assign to an expression in this way, this will give you an error.
The second version is parsed as a = (1 && a == b); that is, the result of the expression 1 && a == b is assigned to a.
The first version does not work because the lefthand side of the assignment is not parsed as you expected. It parses the expression as if you're trying to assign a value to everything on the righthand side--(a == b && a) = 1.
This is all based on the precedence of the various operators. The problem here stems from the fact that = has a lower precedence than the other operators.
Because the order of operations is not what you expect. a == b && a = 1 is equivalent to (a == b && a) = 1 which is equivalent to false = 1.
If you really want to do the assignment, you need to use parentheses around it: a == b && (a = 1).
In if (a = 1 && a == b),
The operations to be first performed is 1 && a == b. 1 && the result of a == b is performed. The result of this && operation is assigned to a.

How to have multiple 'and' logical operators and an 'or' logical operator

It is slightly hard to explain but I want to do something that looks like this:
if(a === 4 && b === true && c === "words" || "numbersandwords")DoSomething();
but it ends running without it matching the first operators. I want to know how to have the last operator except 2 different inputs while still making sure the other criteria are met before running.
You just need to use parentheses, e.g.:
if(a == 4 && b == true && (c == "words" || c == "numbersandwords")) { DoSomething(); }
Just use a few brackets to separate your or parts and the and parts, and add the c === before the last string. Without that equality part at the end, the 'numbersandwords' string always equates to true.
if(a === 4 && b === true && (c === "words" || c === "numbersandwords")){
DoSomething();
}
In JavaScript, like other languages, every operator (like && and ||) has a precendence that determines the order in which it's evaluated. && has higher precedence than ||, so it's evaluated first. Therefore, every term on the left is anded together. Even if they are all false, however, the overall result is true because it's ored with "numbersandwords", which evaluates to true (as does everything except 0, -0, null, false, NaN, undefined, or the empty string). The first thing you need to do is actually compare something (presumably c) to it. Then you can change the order of evaluation using parentheses, which has higher precedence than anything else:
if(a === 4 && b === true && (c === "words" || c === "numbersandwords")) DoSomething();
Alternatively, you can break the test up into several if statements if you may want to eventually do something slightly different based on the value of c (or it just better expresses your intent):
if(a === 4 && b === true)
{
if(c === "words" || c === "numbersandwords")
{
DoSomething();
}
}

How to write an inline IF statement in JavaScript?

How can I use an inline if statement in JavaScript? Is there an inline else statement too?
Something like this:
var a = 2;
var b = 3;
if(a < b) {
// do something
}
You don't necessarily need jQuery. JavaScript alone will do this.
var a = 2;
var b = 3;
var c = ((a < b) ? 'minor' : 'major');
The c variable will be minor if the value is true, and major if the value is false.
This is known as a Conditional (ternary) Operator.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Conditional_Operator
There is a ternary operator, like this:
var c = (a < b) ? "a is less than b" : "a is not less than b";
For writing if statement inline, the code inside of it should only be one statement:
if ( a < b ) // code to be executed without curly braces;
You can also approximate an if/else using only Logical Operators.
(a && b) || c
The above is roughly the same as saying:
a ? b : c
And of course, roughly the same as:
if ( a ) { b } else { c }
I say roughly because there is one difference with this approach, in that you have to know that the value of b will evaluate as true, otherwise you will always get c. Bascially you have to realise that the part that would appear if () { here } is now part of the condition that you place if ( here ) { }.
The above is possible due to JavaScripts behaviour of passing / returning one of the original values that formed the logical expression, which one depends on the type of operator. Certain other languages, like PHP, carry on the actual result of the operation i.e. true or false, meaning the result is always true or false; e.g:
14 && 0 /// results as 0, not false
14 || 0 /// results as 14, not true
1 && 2 && 3 && 4 /// results as 4, not true
true && '' /// results as ''
{} || '0' /// results as {}
One main benefit, compared with a normal if statement, is that the first two methods can operate on the righthand-side of an argument i.e. as part of an assignment.
d = (a && b) || c;
d = a ? b : c;
if `a == true` then `d = b` else `d = c`
The only way to achieve this with a standard if statement would be to duplicate the assigment:
if ( a ) { d = b } else { d = c }
You may ask why use just Logical Operators instead of the Ternary Operator, for simple cases you probably wouldn't, unless you wanted to make sure a and b were both true. You can also achieve more streamlined complex conditions with the Logical operators, which can get quite messy using nested ternary operations... then again if you want your code to be easily readable, neither are really that intuative.
In plain English, the syntax explained:
if(condition){
do_something_if_condition_is_met;
}
else{
do_something_else_if_condition_is_not_met;
}
Can be written as:
condition ? do_something_if_condition_is_met : do_something_else_if_condition_is_not_met;
If you just want an inline IF (without the ELSE), you can use the logical AND operator:
(a < b) && /*your code*/;
If you need an ELSE also, use the ternary operation that the other people suggested.
You could do like this in JavaScript:
a < b ? passed() : failed();
<div id="ABLAHALAHOO">8008</div>
<div id="WABOOLAWADO">1110</div>
parseInt( $( '#ABLAHALAHOO' ).text()) > parseInt( $( '#WABOOLAWADO ).text()) ? alert( 'Eat potato' ) : alert( 'You starve' );
I often need to run more code per condition, by using: ( , , ) multiple code elements can execute:
var a = 2;
var b = 3;
var c = 0;
( a < b ? ( alert('hi'), a=3, b=2, c=a*b ) : ( alert('by'), a=4, b=10, c=a/b ) );
FYI, you can compose conditional operators
var a = (truthy) ? 1 : (falsy) ? 2 : 3;
If your logic is sufficiently complex, then you might consider using an IIFE
var a = (function () {
if (truthy) return 1;
else if (falsy) return 2;
return 3;
})();
Of course, if you plan to use this logic more than once, then you aught to encapsulate it in a function to keep things nice and DRY.
inline if:
(('hypothesis') ? 'truthy conclusion' : 'falsey conclusion')
truthy conclusion: statements executed when hypothesis is true
falsey conclusion: statements executed when hypothesis is false
your example:
var c = ((a < b) ? 'a<b statements' : '!(a<b) statements');
You can use the Ternary operator which equates to a simple if, else.
Ternary operation which calls functions for both outcomes:
(a < b) ? DoSomething() : DoSomethingElse();
Ternary operation which calls a function for only one of the outcomes:
(a < b) ? DoSomething() : {}; or (a < b)?.DoSomething();
To add to this you can also use inline if condition with && and || operators.
Like this
var a = 2;
var b = 0;
var c = (a > b || b == 0)? "do something" : "do something else";
Inline if in JavaScript is simple and requires no braces:
if (a < b) doSomething()
Technically you can have an else in the same line, but it requires a semicolon:
if (a < b) doSomething(); else doSomethingElse()
The above examples may not be desired by your team's coding standards. The most important thing is that you follow conventions that work for your team. Personally, I prefer if statements over ternaries in many cases because I find them easier to read.
Isn't the question essentially: can I write the following?
if (foo)
console.log(bar)
else
console.log(foo + bar)
the answer is, yes, the above will translate.
however, be wary of doing the following
if (foo)
if (bar)
console.log(foo)
else
console.log(bar)
else
console.log(foobar)
be sure to wrap ambiguous code in braces as the above will throw an exception (and similar permutations will produce undesired behaviour.)
Simplify ternary operator
var locked = 1;
var canChange = locked != 1 ? true : false;
If the locked is 1, then the canChange variable is set to false, otherwise, it is set to true.
In this case, you can simplify it by using a Boolean expression as follows:
var locked = 1;
var canChange = locked != 1;
For multiple JavaScript ternary operators
The following example shows how to use two ternary operators in the same expression:
var speed = 90;
var message = speed >= 120 ? 'Too Fast' : (speed >= 80 ? 'Fast' : 'OK');
console.log(message);
It is a best practice to use the ternary operator when it makes the code easier to read. If the logic contains many if...else statements, you shouldn’t use the ternary operators.
(condition) ? expressionTrue : expressionFalse;
Example
int a=20, b=10;
if (a>b) {
cout << "a greater than b";
} else {
cout << "b greater than a";
}
You can simply write:
int a=20, b=10;
(a>b) ? cout << "a greater than b" : cout << "b greater than a";

What is this JS syntax? Assignment in expression? (x != null && (y = x))

I'm working with this JS plugin, and I've encountered some syntax I've never seen before. I understand what it's doing, but I'm not sure why it works.
Here's an example of one instance of it:
settings.maxId != null && (params.max_id = settings.maxId);
Is this just taking advantage of conditionals and the single = ? Is this common syntax for JS?
In JavaScript the = operator is an expression and evaluates the assigned value. Because it is an expression it can be used anywhere an expression is allowed even though it causes a side-effect.
Thus:
settings.maxId != null && (params.max_id = settings.maxId)
Means: If settings.maxId is not null then (and only then, since && is short circuiting) evaluate the right-expression (params.max_id = settings.maxId) which in turn causes the value of settings.maxId to be assigned to params.max_id.
This is much more clearly written as:
if (settings.maxId != null) {
params.max_id = settings.maxId
}
Happy coding.
The && operator is known as "boolean AND". Typically, you'd see it in an if statement:
if (x == true && y == false) {
but that's not a restriction. You may use it in any valid expression to "combine" the boolean values of its operands into a single boolean result, according to the logical "AND" operation:
var z = (x == true && y == false);
// z is now true or false, accordingly
One of the lovely things about && is that it "short circuits". In false && true, because the first operand is false the entire expression may only evaluate to false, so the second operand is not even evaluated.
Let's check that again:
var z = (false && foo());
// z is now false
In this statement, the function foo is never even called! It doesn't have to be, for the program to know that z will be false.
This is more than an optimisation — you can rely on it.
Some silly people use this technique to rewrite conditional statements:
if (x == 0) {
foo();
}
into hard-to-read single expressions:
(x == 0) && foo();
Now, consider that assignment can be an expression just like a function call:
var a = (b = c);
Or:
var a = (b = foo());
And add in a conditional via the above technique:
var a = ((x == 0) && (b = foo()));
Now the entire expression b = foo() won't be evaluated at all if x is not 0, because of short circuiting.
We don't even need to do anything with the result of the && operation, and if we don't store it to a you're left with just:
(x == 0) && (b = foo());
which is a statement that'll assign b to the value of foo() only if x is 0.
Avoid it. It's hard to read. Just use an if statement.
this statement will assign params.max_id = settings.maxId only if settings.maxId != null due to the fact that && is a short-circuit logic operator
this behaviour is due to the fact that javascript will evaluate the condition until it's necessary. thus, if first condition is false and the second is in AND there's no need to check further

Categories