Ternary operators in JavaScript without an "else" - javascript

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

Related

How does this code work as conditional statements, why aren't there any "if" or "else if" statements?

Given the following problem that I need to solve about nested logic, I saw the following possible solution online but I hadn't seen code organized like this and can't help to figure it out. It looks like a different approach I hadn't seen to "if" and "else if" statements, so I would like to understand what's going on. Thank you.
let fine = 0;
const [actual, expected] = input.split('\n').map(item => {
const [day, month, year] = item.split(' ').map(Number);
return {
day,
month,
year
};
});
(
actual.year === expected.year &&
actual.month === expected.month &&
actual.day > expected.day
) && (fine = (actual.day - expected.day) * 15);
(
actual.year === expected.year &&
actual.month > expected.month
) && (fine = (actual.month - expected.month) * 500);
(actual.year > expected.year) && (fine = 10000);
console.log(fine);
}
The code takes advantage of something called short-circuit evaluation, which isn't unique to JavaScript. In a broad sense, short-circuit evaluation means only evaluating a boolean expression if it is necessary to determine the ultimate outcome. It also takes advantage of the fact that in JS, assignment operators act as expressions.
Here's an example of what I mean:
let x;
console.log(x = 2) // 2
What this means is that you can have an assignment expression at the end of a list of conditions to act as an if statement. Due to short circuit evaluation, the assignment expression will only be evaluated if the ultimate true/false value of the full expression is not predetermined by the conditions.
let x;
(false && x = 1) // does nothing, false && ___ = false
(true || x = 2) // does nothing, true || ___ = true
(true && x = 3) // sets x = 3, true && ___ evaluates ___
(false || x = 4) // sets x = 4, false || ___ evaluates ___
JavaScript has short-circuit boolean evaluation, and the code in your question uses that extensively.
Take for example:
a() && b(); // if (a()) b();
Because both a() and b() need to evaluate to a truthy value for the entire statement to be considered true, JavaScript will not evaluate b() if a() already evaluates to a falsy value.
Similarly:
c() || d(); // if (!c()) d();
Because only one of c() or d() needs to evaluate to a truthy value for the entire statement to be considered true, JavaScript will not evaluate d() if c() already evaluates to a truthy value.
This can be used to implement logical branching, much like an if-else structure, although in most cases it does adversely impact the code's readability.
Nothing big changes in your code.
Heare simple syntax with the conditional operation in javascript var varname = condition ? true part code : false part code.
let fine = 0;
const [actual, expected] = input.split('\n').map(item => {
const [day, month, year] = item.split(' ').map(Number);
return { day, month, year };
});
fine = (actual.year === expected.year && actual.month === expected.month && actual.day > expected.day) ? ((actual.day - expected.day) * 15) : 0;
fine = (actual.year === expected.year && actual.month > expected.month) ? ((actual.month - expected.month) * 500) : 0;
fine = (actual.year > expected.year) ? 10000 : 0;
console.log(fine);
Something more

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;
}

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&

How does javascript logical assignment work?

In javascript, if we have some code such as
var a = "one";
var b = q || a;
alert (b);
The logical OR operator will assign a's value to b, and the alert will be "one."
Is this limited to assignments only or can we use it everywhere?
It seems an empty string is treated the same as undefined. Is this right?
How does this work with AND variables? What about combinations of them?
What is a good example of when to use these idioms, or when not to?
For your q || a to evaluate to a, q should be a 'falsy' value. What you did is called "Short circuit evaluation".
Answering your questions:
The logical operators (like and - &&, or - ||) can be used in other situations too. More generally in conditional statements like if. More here
Empty string is not treated as undefined. Both are falsy values. There are a few more falsy values. More here
AND, or && in JavaScript, is not a variable. It is an operator
The idiom you have used is quite common.
var x = val || 'default'; //is generally a replacement for
var x = val ? val : 'default' //or
if (val)
var x = val;
else
var x = 'default';
The way || works in Javascript is:
If the left operand evaluates as true, return the left operand
Otherwise, return the right operand
&& works similarly.
You can make use of this for in-line existence checks, for example:
var foo = (obj && obj.property)
will set foo to obj.property if obj is defined and "truthy".
I'm not quite sure I follow your question. You can use an expression anywhere you can use an expression, and a logical operator on two expressions results in an expression.
alert(q||a);
alert(true||false);
var x=5;
var y=0;
if (y!=0 && x/y>2) { /*do something*/ }
The last bit is useful. Like most languages, Javascript 'short-circuits' ANDs and ORs. If the first part of an AND is false, it doesn't evaluate the second bit - saving you a divide-by-0. If the first part of an OR is true, it doesn't evaluate the second.
But you can use boolean operators anywhere you can use an expression.
Javascript evaluates logic by truethness/falseness. Values such as (false, "", null, undefined, 0, -0) are evaluated as logic false.
Combine this with the lazy evaluation, 'OR' operations are now evaluated from left to right and stops once true is found. Since, in your example, the truthness is not literally a boolean, the value is returned.
In this case:
x = 0; y = 5; alert(y || x)/*returns 5*/; alert(x || y)/*also returns 5*/;
this can also be other objects.
functionThatReturnsTrue() || functionThatDoesSomething();
This behavior is shared with other scripting languages like Perl. The logical OR operator can be used as a syntactic shorthand for specifying default values due to the fact that the logical OR operator stops evaluating its operands when it encounters the first expression that evaluates to true: "evaluate the first operand and if the value is interpreted as not false, assign it. Otherwise repeat for the second operand."
I find I often use this behavior to specify default values for function parameters. E.g.
function myFunction(foo, bar) {
var fooValue = foo || "a";
// no need to test fooValue -- it's guaranteed to be defined at this point
}
IMHO - don't use for boolean type assignment. It can be confusing. As undefined !== false, ie false itself is a value.
E.g. If u want to copy a field value from an object if and only if that field is defined
var bar.value = false;
var foo = true;
var foo = bar.value || foo; // ==> should be false as bar.value is defined
For boolean type assignment, u should really use
var foo = (bar.value !== undefined) ? bar.value : foo;

Categories

Resources