Javascript Ternary operator with empty else - javascript

I'm trying to convert the following if-else to it's ternary operator representation in javascript as follows
var x = 2;
if (x === 2) {alert("2");}
else
{ //do nothing}
But when I do this:
(t==2)?(alert("1")):();
Chrome throws a SyntaxError.
My question is -
How to have a ternary operator in javascript with an empty "else" branch - i.e the part that comes after ":".
Also, is this allowed- using a ternary operator in javascript to execute statements - NOT do assignment.
Also: the above code was just a base case. I'm actually trying to get all the DOM elements of the page as an array (called all2) and then add only those elements to another array (called only) only if they have non-null class names. Here is my code:
all2.forEach(function(e){ e.getAttribute("class") ? (only.push(e.getAttribute("class"))) : (); });
If I leave the third operand blank, it throws a syntax error. Passing a null works

Answer to your real question in the comments:
all2.forEach(function (e) {
e.getAttribute("class") && only.push(e.getAttribute("class"));
});

Do this :
(t==2)?(alert("1")):null;
You could replace null by any expression that has no side effect. () is not a valid expression.

You putted a lot of useless parentheses, and the best NULL value in js is undefined.
document.getElementById('btn-ok').onclick = function(){
var val = document.getElementById('txt-val').value;
val == 2 ? alert(val) : undefined;
}
<input id="txt-val" type="number" />
<button type="button" id="btn-ok">Ok</button>
using a single line if statement is better though
if(value === 2) alert(value);

you have a few options to do this nicely in one line:
option1 - noop function
set a global noop function:
function noop(){}
(t==2)?(alert("1")):(noop());
option2 - && operator
when you use && operater, operands are evaluted only if previos ones where true, so you could miply write:
(t==2) && alert("1");
or, for exapmle if you have an arry you want to push to, you could test it is not null before:
arr && arr.push(obj)

I don't like it's either. So you're on the right track looking for alternatives.
In this case, I would write:
t===2 && alert("2")
Your idea is valid too, for instance you can do this:
t===2 ? alert("2") : null
But it's four extra chars.

In that case you don't need to use Ternary operator. Ternary operator requires a third argument.
condition ? expr1 : expr2
Lokki at Conditional (ternary) Operator
You can use the if statement
if ( t == 2 ) alert(1);

NO, you can't have empty else, better don't use the ternary operator, it requires a third argument. Go with simple if condition.
if(t==2) alert("2");

Related

One-line short-circuit evaluation with && || in JavaScript

var prefix = options && options.prefix || '';
In JavaScipt in my case. Can someone explain what kind of statement or condition is this? Or at the end what's the value of prefix variable?
I know about (ternary operator):
condition ? expr1 : expr2
but this was different.
This one-liner is the equivalent of saying:
var prefix;
if(options && options.prefix){
prefix = options.prefix;
} else{
prefix = '';
}
The statement is setting the variable "prefix" to either the value of "options.prefix", or an empty string, in such a way that if "options" does not exist, it does not throw an error.
The reason this works is in Javascript logical operators evaluate to the value of the last operand.
So is options object exist, the && part of the expression will be evaulated to options.prefix.
If that is not set, the left part of the || expression will be false and the right part = the '' string - will be returned.
Its similar to following:
var prefix;
if(options){ // or for better understanding, its if(options != undefined)
prefix = options.prefix;
}
else
prefix = '';
Try the following fiddle for better understanding:
http://jsfiddle.net/n41tfnh4/1/
Translated into human language
If variable optionsis defined with some non-falsey value
and it also has a property options.prefix whose value is also non-falsey
then set the variable prefix with this options.prefix value.
Otherwise, our prefix is set to empty string by default.
PS. Quickly check the complete list of falsey values in JavaScript by google "javascript falsy values"
Quicker explanation
This is a quick value check (and get) of options.prefix which is empty string by default.
(without throwing an exception when options is undefined)
It means, it options is an object, use options.prefix. If options.prefix is undefined or null or other falsy value, return empty string.
Nearly same meaning of options ? options.prefix : ''.
If prefix is available on options, set it to var prefix. Otherwise, set it to an empty string.

JavaScript if statement not behaving as expected

Just learning to code JavaScript, trying to learn if statements but my code isn't working:
var car = 8;
if (car = 9) {
document.write("your code is not working")
}
This executes the write command and I have no idea why. I'm using the tab button for indents, is that not allowed?
= is called assignment operator in JavaScript, it assigns the value of the right hand side expression to the variable on the left hand side.
You have to use comparison operator instead of assignment operator like this
if (car === 9)
We have two comparison operators in JavaScript, == and ===. The difference between them is that,
== checks if the values are the same, but === checks if the type and the value is also the same.
Go through the wonderful answers, to know more about == and ===
This line assigns car to the value of 9 and check if it is truthy (which 9 is).
if (car=9)
I think you want to use a comparison operator, like this:
if(car == 9)
use this code
var car = 8;
if (car==9)
{
document.write("your code is not working")
}
you need to understand about operators '=' is an assignment operator whereas '==' is a comparision operator.
See Tutorial
If you want
to compare if car is equal to 9, then you have to use code
if(car === 9){
/*Your code goes here*/
}

Proper use of a comma in javascript ternary operator

Rather than use an if else statement, I'm trying to use the ternary operator but have a syntax error somewhere in my statement.
Can someone tell me where I am going wrong?
Statement is:
my_alert(status ? ('Accepted', 'alert-success') : ('Declined', 'alert-info'))
my_alert is a function which has 2 parameters.
Status just evaluates to true or false.
When I pass more than 1 parameter into the above expression, it doesn't like the use of the comma.
In chrome and firefox when the function runs it displays 'alert-success' or 'alert-info'. It misses out the first parameter.
I've looked on stackoverflow for the answer but by all means it's telling me that what i'm doing is correct.
Any help would be great.
Well, the comma operator does the following:
The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.
That means, ('Accepted', 'alert-success') evaluates to 'alert-success' (as you already noticed). The comma here is different than the comma that separates function arguments. You cannot use it to pass two arguments to a function.
What you can do is store both arguments in an array and use .apply to pass them to the function:
// this is not the comma operator either, this is array literal syntax.
var args = status ? ['Accepted', 'alert-success'] : ['Declined', 'alert-info'];
my_alert.apply(null, args);
I don't think ternary operators can be used to control two values like that:
How about separating them:
my_alert(($status?"Accepted":"Declined"),($status?"alert-success":"alert-info"));
Alternatively, you could just wrap the function call in the ternary statement...
status ? my_alert("Accepted", "alert-success") : my_alert("Declined", "alert-info");
UPDATE:
Robin van Baalen makes a good suggestion...
my_alert.apply(this, status ? ["Accepted", "alert-success"] : ["Declined", "alert-info"]);
You can't use the comma like that. If you want to pass 2 parameters, you need to use 2 ternary statements.
my_alert((status ? 'Accepted' : 'Declined'), (status ? 'alert-success' : 'alert-info'));
In your case, the comma is read a the comma operator, which evaluates both operands and returns the last one. So, your ternary statement was equivalent to:
my_alert(status ? 'alert-success' : 'alert-info')

is there any function like string.isnullorempty() in javascript

I always (thing != undefined || thing != null)?...:...; check. Is there any method will return bool after this check in javascript or jquery ?
And how would you add this check in jquery as a function?
if (thing)
{
//your code
}
Is that what you are looking for?
In Javascript, the values null, undefined, "", 0, NaN, and false are all "falsy" and will fail a conditional.
All other values are "truthy" and will pass a conditional.
Therefore, you can simply write thing ? ... : ....
Try this
function SringisEmpty(str) {
str=str.trim();
return (!str || 0 === str.length);
}
As the others here have mentioned, several things evaluate as "falsy" that you might not want to (such as empty strings or zero). The simplest way I've found in JavaScript to check for both null and undefined in one statement is:
thing != null
This is using type coercion (double equals instead of triple equals), so undefined values are coerced to null here, while empty strings, zero, etc. do not.

How do you read this JavaScript code? (var1 ? var2:var3)

I've seen this format used in JavaScript code, but can't find a good source for the meaning.
Edit for a follow-up:
Thanks for all the quick answers! I figured it was something like that. Now, for bonus points:
can you use
(var1 ? var2)
to do the same thing as
if (var1) {
var2
}
?
It's known as a ternary (because it has three operands) conditional (because it's an if/else/then) operator.
It is evaluated to a value, so you would usually use it to assign a value, such as:
var result = condition ? value1 : value2;
Which is equivalent to:
var result;
if (condition == true) {
result = value1;
} else {
result = value2;
}
An example:
var message = "Length is " + len + " " + (len==1 ? "foot" : "feet");
Note ?: is the full operator. It's not a ? and : operator, so ? by itself is meaningless in Javascript.
Its a conditional operator.
It is
if var1 then var2 else var3
Read more here
Conditional Operator
The conditional operator is the only
JavaScript operator that takes three
operands. This operator is frequently
used as a shortcut for the if
statement.
if(var1) {
var2;
else {
var3;
}
The expression var1 ? var2 : var3 returns the value of var2 if var1 is considered to have a value equivalent to true else it returns teh value of var3.
Note this is not quite the same as:-
if (var1)
varX = var2
else
varX = var3
Since the above construct can not itself appear as part of a larger expression.
In ternery expression, as ? : is known, one should avoid allowing the component expressions to have side effects other than perhaps the side-effects of ++ or -- operators. For example this isn't a good idea:-
varX = var1 ? doSomethingSignificant() : doSomethingElseSignificant();
In this case it would be better to use the if else construct. On the hand:-
varX = var1 ? calcSomething(var2) : someOtherCalc(var2);
this is acceptable assuming the called functions don't themselves modify the program state significantly.
Edit:
I think I need to re-enforce this point. Do not use the ternary operator as means to short cut on if statements. The two have different purposes. If your code is full of ? : that should be if else it will be difficult to read. We expect logical flow to appear in if statements. We expect ? : when there is a simple logical component to an expression. Note expressions do not modify things only the results of them when assigned should modify things.
As an addendum for the first question, you can alternatively use
var result = (condition) && var1 || var2;
and obtain the same result
For the second question, in C the following works too :
(condition) && someinstruction;
but that does not seem to work in javascript (at least with my version of firefox).
This seems to be sort of a ternary operation. Short form of an if else operation, so to say. check here for details...

Categories

Resources