One line of if..else if.. else statement - javascript

I tried to write one line if..elseif..else statement but it always goes in else if.
var x = "192.168.1.1";
x = x == ("google.com") ? ("true google.com") : (("yahoo.com") ? ("true yahoo.com") : ("192.168.1.1"));
console.log(x);
Is there something I am missing? Why does it always go in else if?

You missed the x == (""yahoo.com"") statement
var x = "192.168.1.1";
x = (x == "google.com") ?
"true google.com" :
(x == "yahoo.com") ?
"true yahoo.com" :
"192.168.1.1";
// --------------------------------------------^^^^^^^^^^^^^^^^------------------------------------
console.log(x);
But it will be more readable with if - else if - else statements. Don't make your code concise if it will decrease the readability.

Your ternary operation
x = x == ("google.com") ? ("true google.com") : (("yahoo.com") ? ("true yahoo.com") : ("192.168.1.1"));
can be thought of as if-else if-else block as follows:
if(x == ("google.com")) {
x = "true google.com";
}
else {
if("yahoo.com") {
x = "true yahoo.com"; //Always true since it is a non-empty string
}
else {
x = "192.168.1.1"
}
}
So since you are initializing x to "192.168.1.1", it obviously is not equal to the the string specified ("google.com") in the first condition (if block). So it moves on to the else block and evaluates the if condition inside the else block. This if block in turn only checks if a string literal "yahoo.com" is empty or not. Since it is not empty, the condition is satisfied.
For your purpose, you need to change that from if("yahoo.com") to x == if("yahoo.com"). However, once you make this change, it will always go to the else block because the first two conditions will never satisfy.

This does not answer the question
Why does it always go in else if?
but it could help with
Is there something I am missing?
Yes, you mis some clarity for further use and a clear pattern, how to get for a given string another string.
You could use an object, which is easy to maintain for the keyed values.
values = {
"google.com": "true google.com",
"yahoo.com": "true yahoo.com",
default : "192.168.1.1"
};
The call works with a default operator || (logical OR):
x = values[x] || values.default;
var x = "192.168.1.1",
values = {
"google.com": "true google.com",
"yahoo.com": "true yahoo.com",
default : "192.168.1.1"
};
x = values[x] || values.default;
console.log(x);

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.

Javascript simplified if-statement

I'm scratching my head trying to understand this very simplified if statement. When searching for the answer, all I find is answers related to ternary operators.
Anyway. Why is it that the first case below works, while the latter throws an ReferenceError? Just trying to understand how things work.
true && alert("test")
var x;
true && x = 10;
This has to do with operator precedence. As the && operation is computed before the =, your second example would end up making no sense : (true && x) = 10;
For your second case to work, add parenthesis this way :
var x;
true && (x = 10);
Javascript seems to give higher precedence to && than to the assignment operator. The second line you gave is parsed as:
(true && x) = 10;
If you add parenthesis around the assignment, I think you will see the behavior that you were expecting:
true && (x = 10); // Sets x to 10 and the whole expression evaluates to 10.
And just in case you needed a pointer as to why && can be used as an if-statement, the phrase "short-circuit evaluation" might help.
It'a Operator precedence.
As you can see && has higher priority than =
So true && x = 10; is actually (true && x) = 10; which is clearly wrong. You can only assign value to variables, and (true && x) is either false or the value of x.
The result of alert() is undefined. So first example could be retyped as:
var x; // x is now 'undefined'
true && x; // true and undefined is undefined
The second example is about operators priorities. Runtime evaluate expression as (true && x) = 10;
var x;
true && (x = 10); // result will be 10

What is the use of "?" in jquery

What is the use of "?" mark ?
can anyone explain what question mark is doing here.
0 ? 1 : 1+w
and also ":" symbol .
How to use "?" while writing the codes..
I have seen so many codes where people will use "?" like example above.
can anyone explain what question mark is doing.
This is nothing to do with jquery, this is standard javascript. It's known as a ternary operator. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
This:
x = a ? b : c
is the equivalent of writing:
if (a) {
x = b
} else {
x = c
}
It has nothing to do with jquery. it is javascript if else shorthand method
Check below example
var big;
if (x > 10) {
big = true;
}
else {
big = false;
}
shorthand
var big = (x > 10) ? true : false;
That's called ternary operator, a kind of conditional operator
var fooNotNull = (foo !== null) ? true : false;
if the first condition is 'true', it is saved in the variable 'fooNotNull', else the second value 'false' is stored in 'footNotNull'
The expression is a tenerary operator. It works like an 'if' and 'else'.
Whatever is before the '?' is evaluated, returning what is after the '?' when the condition is true, and whatever is after the ':' if it is false.
These expressions give the same results:
a = 0 ? 1 : 1+w
if(0){
a = 1;
}else{
a = 1 + w;
}

Ternary operators in JavaScript without an "else"

I've always had to put null in the else conditions that don't have anything. Is there a way around it?
For example,
condition ? x = true : null;
Basically, is there a way to do the following?
condition ? x = true;
Now it shows up as a syntax error.
FYI, here is some real example code:
!defaults.slideshowWidth ? defaults.slideshowWidth = obj.find('img').width()+'px' : null;
First of all, a ternary expression is not a replacement for an if/else construct - it's an equivalent to an if/else construct that returns a value. That is, an if/else clause is code, a ternary expression is an expression, meaning that it returns a value.
This means several things:
use ternary expressions only when you have a variable on the left side of the = that is to be assigned the return value
only use ternary expressions when the returned value is to be one of two values (or use nested expressions if that is fitting)
each part of the expression (after ? and after : ) should return a value without side effects (the expression x = true returns true as all expressions return the last value, but it also changes x without x having any effect on the returned value)
In short - the 'correct' use of a ternary expression is
var resultofexpression = conditionasboolean ? truepart: falsepart;
Instead of your example condition ? x=true : null ;, where you use a ternary expression to set the value of x, you can use this:
condition && (x = true);
This is still an expression and might therefore not pass validation, so an even better approach would be
void(condition && x = true);
The last one will pass validation.
But then again, if the expected value is a boolean, just use the result of the condition expression itself
var x = (condition); // var x = (foo == "bar");
UPDATE
In relation to your sample, this is probably more appropriate:
defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width()+'px';
No, it needs three operands. That's why they're called ternary operators.
However, for what you have as your example, you can do this:
if(condition) x = true;
Although it's safer to have braces if you need to add more than one statement in the future:
if(condition) { x = true; }
Edit: Now that you mention the actual code in which your question applies to:
if(!defaults.slideshowWidth)
{ defaults.slideshowWidth = obj.find('img').width()+'px'; }
More often, people use logical operators to shorten the statement syntax:
!defaults.slideshowWidth &&
(defaults.slideshowWidth = obj.find('img').width() + 'px');
But in your particular case the syntax can be even simpler:
defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width() + 'px';
This code will return the defaults.slideshowWidth value if the defaults.slideshowWidth is evaluated to true and obj.find('img').width() + 'px' value otherwise.
See Short-Circuit Evaluation of logical operators for details.
var x = condition || null;
You could write
x = condition ? true : x;
So that x is unmodified when the condition is false.
This then is equivalent to
if (condition) x = true
EDIT:
!defaults.slideshowWidth
? defaults.slideshowWidth = obj.find('img').width()+'px'
: null
There are a couple of alternatives - I'm not saying these are better/worse - merely alternatives
Passing in null as the third parameter works because the existing value is null. If you refactor and change the condition, then there is a danger that this is no longer true. Passing in the exising value as the 2nd choice in the ternary guards against this:
!defaults.slideshowWidth =
? defaults.slideshowWidth = obj.find('img').width()+'px'
: defaults.slideshowwidth
Safer, but perhaps not as nice to look at, and more typing. In practice, I'd probably write
defaults.slideshowWidth = defaults.slideshowWidth
|| obj.find('img').width()+'px'
We also have now the "Nullish coalescing operator" (??). It works similar to the "OR" operator, but only returns the left expression if it's null or undefined, it doesn't return it for the other falsy values.
Example:
const color = undefined ?? 'black'; // color: 'black'
const color = '' ?? 'black'; // color: ''
const color = '#ABABAB' ?? 'black'; // color: '#ABABAB'
What about simply
if (condition) { code if condition = true };
To use a ternary operator without else inside of an array or object declaration, you can use the ES6 spread operator, ...():
const cond = false;
const arr = [
...(cond ? ['a'] : []),
'b',
];
// ['b']
And for objects:
const cond = false;
const obj = {
...(cond ? {a: 1} : {}),
b: 2,
};
// {b: 2}
Original source
In your case i see the ternary operator as redundant. You could assign the variable directly to the expression, using ||, && operators.
!defaults.slideshowWidth ? defaults.slideshowWidth = obj.find('img').width()+'px' : null ;
will become :
defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width()+'px';
It's more clear, it's more "javascript" style.
You might consider using a guard expression instead (see Michael Thiessen's excellent article for more).
Let x be a logical expression, that you want to test, and z be the value you want to return, when x is true. You can then write:
y == x && z
If x is true, y evaluates to z. And if x is false, so is y.
The simple way to do this is:
if (y == x) z;
Why not writing a function to avoid the else condition?
Here is an example:
const when = (statement, text) => (statement) ? text : null;
const math = when(1 + 2 === 3, 'Math is correct');
const obj = when(typeof "Hello Word" === 'number', "Object is a string");
console.log(math);
console.log(obj);
You could also implement that function for any objects. Here is an example for the type string:
const when = (statement, text) => (statement) ? text : null;
String.prototype.if = when;
const msg = 'Hello World!';
const givenMsg = msg.if(msg.length > 0, 'There is a message! Yayyy!');
console.log(givenMsg);
Technically, it can return anything.
But, I would say for a one liner the Ternary is easier to type and at least 1 character shorter, so therefore faster.
passTest?hasDriversLicense=true:0
if(passTest)hasDriversLicense=true

'' 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