JavaScript Ternary with Logical OR - javascript

var a = '1';
console.log(a == ('2'||'1')?'hi':'hello');
Doing so the condition get failed as a = 1 .
It is comparing a's value 1 with 2 as this condition failed. so it always print hello.
Is there any way to check for value('1') also which is after "||" so that it print hi?

Either list the different possibilities out separately:
a === '2' || a === '1' ? 'hi' : 'hello'
Or use an array and .includes:
['2', '1'].includes(a) ? 'hi' : 'hello'
The problem with ('2'||'1') is that the whole section there gets evaluated to a single expression before the comparison against a is made, and || will evaluate to the initial value if it's truthy. So ('2' || '1') resolves to '2'.

var a = 1;
a == '2'?'hi': a=='1'?'hello' :'';
i Found this is also working.... Thanks to everyone who answered using different ways..

Related

Dynamically constructed if statement in one string variable

I am blacking out over issue and I am convinced I am thinking too complex about this, but summarized, my issue is about this:
// imagine this variable is dynamically filled by a loop with conditions inside
var condition = varA + " == " + varB + " && " + varC + " == " + varD;
if (condition) {
// something
}
So it doesn't check whether varA equals varB and varC equals varD as what I intended, but instead it just sees it as a string and that appears to be always true anyway. I don't want, I want to see it actually checking whether varA equals varB etc.
Is there a way to parse this statement into something that actually can be a 'legit' if condition?
Thanks!
I think I understand what your trying to do. You are trying to look at a number of comparisons and determine, in the end, if all comparisons were truly true.
In this case you can actually just keep building your condition out as in the following:
var a = 1, b = 1, c = 3, d = 3, e = 5, f = 6;
var condition = a === b; // condition is true
condition = condition && c === d; // condition is still true
condition = condition && e === f; // condition is now and forever false
why not just do
if(varA == varB && varC ==varD){
//do something
}
edit
maybe try using safe-eval. its a third party package but APPEARS to be an improvement on eval.
The issue with your condition variable is that it's not checking for equality between your variables. The whole condition variable is being read as a string because it sees the == and && as strings and ends up concatenating them together.
I suggest writing your if statement like so:
if (varA === varB && varB === varC && varC === varD) {
// do something
}
That way, you're checking if varA is equal to varB and varB is equal to varC, etc. Using the triple equals also ensures that the variables are of the type value type (i.e. string, boolean, number). Hope this helps.

Nesting ternary operators

I am trying to write a long if else if
(!contract.hasOwnProperty('COMMIT_CONTRACT') ? '1') : (contract.hasOwnProperty('COMMIT_CONTRACT') ? '2' : '3')
However, this is failing to evaluate.
I started with:
(!contract.hasOwnProperty('COMMIT_CONTRACT')) ? '1' : '2')
But according to here you can chain them: javascript shorthand if statement, without the else portion
But it's not evaluating correctly. What am I doing wrong and how do I fix it?
You messed up with parenthesis (()).
According to my understanding,
This is your first condition: !contract.hasOwnProperty('COMMIT_CONTRACT'),
Your if part of first condition is '1',
Your else part of first condition is second condition: contract.hasOwnProperty('COMMIT_CONTRACT'),
Your if part of second condition is '2',
Your else part of second condition is '3'.
Let's add some parenthesis to make it more readable by us as well to compilers,
( !contract.hasOwnProperty('COMMIT_CONTRACT') ) ? '1' : ( contract.hasOwnProperty('COMMIT_CONTRACT') ? '2' : '3' )
Fun Fact, You will never get '3'.
You don't need all the () around everything. This will work just fine:
var variable = !contract.hasOwnProperty('COMMIT_CONTRACT') ? '1' : contract.hasOwnProperty('COMMIT_CONTRACT') ? '2' : '3';

javascript or operation returns unexpected result

I am very new to javascript. I have a programm like:
var a = 2
if(a !=2 || a != 3){
console.log("not")
}
Here I have set the variable a value to 2.
In my condition I have set if a is not 2 or a is not 3 it should print not
But here a's value being 2 it is printing not.
It always give not whatever the value is
I can check this is python easily like:
if not a == 2 or not a== 3
Whats wrong in here ??
var a = 2
a is now 2.
a !=2
This is false, so we look on the other side of the or
a != 3
This is true. So one of the two sides of the or test is true. Therefore the or test is true.
If you want to test if a value is not 2 and it is also not 3, then you need to use an && operator.
Maybe you want this:
if(a !=2 && a != 3){
console.log("not")
}
In other words, if a is not 2 AND a is not 3.
This is just how boolean logic works. In your example, because a does not equal 3, the condition is true.
Please read how logical operators work.
Your condition evaluates to true if a is not 2 or a is not 3, that means that is will be false only when a is both 2 and 3 at the same time which isn't possible - this condition will always be true.
You might be also interested in reading something on mathematical logic and negations.
If you want to ensure that a is not 2 or 3 then you should change it to
if((a != 2) && (a != 3)){
as in a is not 2 and a is not 3 - keep in mind that you are working with 2 statements.
Simple explanation
false || true = true
a != 2 //returns false
a != 3 //returns true
In python:
not a == 2 // returns false
not a == 3 //returns true
"OR" in the condition means that the statement in the if block will get executed if any one of the equations out of
(a != 2)
and
(a != 3)
returns true.
In your code snippet
(a != 3)
is true and hence the statement
console.log("not");
gets executed.
This is very expected behaviour and it work same in python and javascript
a = 2
if not a == 2 or not a== 3:
print ("not")
is equivalent to
var a = 2
if(a !=2 || a != 3){
console.log("not")
}
in or expression conditions check while one of theme be come true or until there was no condition.

Can someone please explain this syntax in Javascript - " type = type || 'fx' " [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What does this construct (x = x || y) mean?
I've seen this code here. And some similar code on other places that I can't recall.
time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
type = type || "fx";
What does it mean?
I don't understand a) at all but I *think* I understand b) like this:
If type is false then type will be equal to "fx" otherwise type will equal whatever it was before.
I'm not sure, but perhaps I'm wrong.
What is this syntax called? Conditional variable? :P I tried Googling for an answer but have no idea what to use in my query.
a)
time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
is synonym for
if (jQuery.fx) {
if (jQuery.fx.speeds[time]) {
time = jQuery.fx.speeds[time];
}
}
which is almost the same as
b)
type = type || "fx";
is synonym for
if (!type) {
type = "fx";
}
Simply it checks if type is not false, null, undefined. If yes, type is being filled with fx
For A, what we're doing is a shortcut for an if-else statement. The stuff before the question mark refers to the if statement, the next element is the "then" statement, and the final part is the "else" statement.
var action = my_status == 'hungry' ? 'eat' : 'do not eat';
In this case, it would translate into something like this:
if (my_status == 'hungry')
action = 'eat';
else
action = 'do not eat';
For B, double pipes (||) mean "or". What we're evaluating here is a Boolean value based on whether one OR the other is true.
var not_hungry = ate_lunch || full;
If either ate_lunch OR full is true, the not_hungry is also true.
You can do the same thing with double ampersands (&&) which mean AND.
var single = nerdy && cocky;
If nerdy AND cocky are true, then single is also true. If only one of those is true, then the statement resolves to false (since both must be true for single to be true).
Hope that helps. :)
Edit (h/t Phrogz):
It's worth noting that || and && in JavaScript don't only operate upon and evaluate to a Boolean value, but rather are "guard" operators that test for 'truthiness' and evaluate to one of the two operands. (
time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
Can be written as:
if (jQuery.fx) {
if (jQuery.fx.speeds[time]){
time = jQuery.fx.speeds[time];
}
}
In this case the ternary operation (? :) is redundant. The statement returns time if JQuery.fx.speeds[time] doesn't exist - so it returns itself.
More general: somevar = a || b is called short circuit evaluation. Basically it's a short way of writing
if (a) {
somevar = a;
} else {
somevar = b;
}
a) Set time to jQuery.fx.speeds[time] if and only if jQuery.fx and jQuery.fx.speeds[time] exists:
if(jQuery.fx && jQuery.fx.speeds[time])
time = jQuery.fx.speeds[time];
b) Your description is correct
a.) is structured using ternary operator, in simple term think of
time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
as equivalent to:
time = if(jQuery.fx){ jQuery.fx.speeds[time]; } else { time : time; }
b.) you are correct in that type will be defined if type is already defined, otherwise it'll default to "fx". However, I'm not sure if there's a technical name for it except it is the logical expression for OR
Yes, you're right about what it does. It's known as short-circuit evaluation. It does something similar to C's ternary operator.
It's a ternary operator
http://en.wikipedia.org/wiki/Ternary_operator
I was trying to link to the first result here...
https://www.google.com/#hl=en&cp=4&gs_id=1j&xhr=t&q=wiki+inline+if&

'' equals false in Javascript? What would be the safest way to distinguish between '' and boolean false?

We use an external API whcih returns '' or boolean false while Javascript seems to find the both equal.
for example:
var x = '';
if (!x) {
alert(x); // the alert box is shown - empty
}
if (x=='') {
alert(x); // the alert box is shown here too - empty
}
var z = false;
if (!z) {
alert(z); // the alert box is shown - displays 'false'
}
if (z=='') {
alert(z); // the alert box is shown here too - displays 'false'
}
How can we distinguish between the two?
Use the triple equal
if (x===false) //false as expected
if (z==='') //false as expected
A double equal will do type casting, while triple equal will not. So:
0 == "0" //true
0 === "0" //false, since the first is an int, and the second is a string
var typeX = typeof(x);
var typeZ = typeof(z);
if (typeX == 'string' && x == '')
else if (typeX == 'boolean' && !typeX)
I like Peirix's answer too, but here is an alternative.
as mentioned by peirix: tripple equal signs check both the value and the type
1 == '1' // true
1 === '1' // false
For avoid this questions use jslint validator. It helps for find unsafe operations.

Categories

Resources