conditional short hand doesn't work? - javascript

var countChecked = $('.member_checkbox:checked').length;
$('.email-btn').text('Email ' + countChecked + 'member' + countChecked > 1 ? 's');
What's wrong with my conditional short hand above? The logic I want is add 's' if the count is more than 1 to the string.

The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement.
You're not using it with correct syntax.
The syntax is
condition ? expr1 : expr2
You've missed the else part of the conditional/ternary operator.
$('.email-btn').text('Email ' + countChecked + 'member' + (countChecked > 1 ? 's' : ''));
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Also, wrap the conditional part inside parentheses.

The syntax of Conditional Short hand is
condition ? expr1 : expr2
In your expression,
Condition is $('.email-btn').text('Email ' + countChecked + 'member' + countChecked > 1
Expr 1 is 's'
Expr 2 is Not Given
Also,
What does 's' means, is it assigned to something?

var countChecked = $('.member_checkbox:checked').length;
$('.email-btn').text('Email ' + countChecked + 'member' + ((countChecked > 1) ? 's' : ''));
Conditional statement needs to be in the brackets and do provide the else part if you don't want to append anything in this case just append ''.

Related

Javascript plus operator not works with ternary if else

Hi this is my js code.
var a = '<span> and have </span>' + $('#module_product_review_star_1 .pdp-link')[1] ? $('#module_product_review_star_1 .pdp-link')[1].outerHTML : 'not have';
alert(a);
I'm using ternary operator to check the item exists in dom. But when the item is not in dom this code is failing.
this works,
if($('#module_product_review_star_1 .pdp-link')[1]){
questiones = '<span> and have </span>' + $('#module_product_review_star_1 .pdp-link')[1].outerHTML;
}
But I need to use ternary operator and do it in one line. Is there a way to do it?
+ has higher operator precedence (13) than the conditional operator (4), so your code is checking whether '<span> and have </span>' + $('#module_product_review_star_1 .pdp-link')[1] is truthy, which it always will be. Surround everything past the </span> in parentheses instead:
var a = '<span> and have </span>' + (
$('#module_product_review_star_1 .pdp-link')[1]
? $('#module_product_review_star_1 .pdp-link')[1].outerHTML
: 'not have'
);
That said, it would be better to write DRY code and put $('#module_product_review_star_1 .pdp-link')[1] into a variable first:
var possibleLink = $('#module_product_review_star_1 .pdp-link')[1];
var a = '<span> and have </span>' + (
possibleLink
? possibleLink.outerHTML
: 'not have'
);
Ternary has this pattern:
condition ? do if true : do if false;
so in your case condition is
'<span> and have </span>' + $('#module_product_review_star_1 .pdp-link')[1]

React. What is the wrong with my ternar operator in className?

So, I have a simple tag span with classNames that trigger on a special condition, but for some reason my class in the DOM does not appear. I got just class word without anything like <span class>...</span>.
My span tag:
<span key={total} className={'total' + ' ' + total === 0 ? 'total--empty' : ' '}>
{total ? total : 0}
</span>
It is parsed like a ternary* : (statement) ? whenTrue : whenFalse;
// Which, translated to your code makes:
{ ('total' + ' ' + total === 0) ? 'total--empty' : ' '}
A string is truthy, thus 'total--empty'. What you need:
{ 'total' + ' ' + (total === 0 ? 'total--empty' : ' ')}
* Most people call it the ternary operator, but it is actually called the conditional operator. It's a ternary operator (an operator accepting three operands), and currently JavaScript's only ternary operator, but that could change.
You should probably know about concept of Operator precedence.
In your case, you are using '+' operator (precedence of 13) and comparison '===' operator (precedence of 10).
Therefore, the expression:
{'total' + ' ' + total === 0 ? 'total--empty' : ' '}
...will always return falsy value i.e. space.
Lets say total value is 0, so your expression executes as 'total'+' '+0 which becomes a string "total 0" NOT EQUAL TO 0.
What you need to do is Grouping of expression using '()' round brackets (precedence of 20).
i.e.
{'total' + ' ' + (total === 0 ? 'total--empty' : ' ')}
which has possible truthy/falsy outcome i.e. "total " or "total total--empty"
You can try this below. We can make it with the help of curly braces and parenthesis.
Curly braces { } are special syntax in JSX. It is used to evaluate a JavaScript expression during compilation. A JavaScript expression can be a variable, function, an object, or any code that resolves into a value.
Parenthesis ( ) can be used to return something.
Curly braces versus parenthesis in ReactJS
<span className={"total "+(total !== 0 ? "total_empty": null )} />
{total ? total : 0}
</span>

What means '?' in Javascript?

Can anyone explain me this line of code and why we use the '?' in javascript?
return n > 0 ? ninja.yell(n-1) + "a" : "hiy";
This is a ternary operator which also present in other programming languages:
return n > 0 ? ninja.yell(n-1) + "a" : "hiy";
^^ ^^ ^^
if condition if true if false(else)
The above statement is equivalent to below:
if(n>0) {
return ninja.yell(n-1) + "a";
} else {
return "hiy";
}
For more read this tutorial.
The question mark is actually called Ternary Operator, usually in programming laguages it is used for a one line if statement and it has the following construct:
condition ? return if condition is True : return if condition is False
Think the ternary operator as "then" and the ":" as else. So your code will be:
return if( n > 0) then ninja.yell(n-1) + "a" else "hiy";
Hope you get it now!

Java Script syntax

options.domain ? '; domain=' + options.domain : '',
can some one explain me what is the purpose of putting ? after options.domain. I know it's simple. but i'm little new to JS.
This is called ternary operator ?: (single line if..else statement)
Syntax: var variableName = testCondition ? op1 : op2;
I guess you missed the assigned variable
var dom = options.domain ? '; domain=' + options.domain : '';
equivalent to
if (options.domain) {
dom = '; domain=' + options.domain
}
else {
dom = '';
}
It's known as a ternary operator, essentially these are equivalent:
// Item 1
var x = options.domain ? '; domain=' + options.domain : '';
// Item 2
var x;
if (options.domain) {
x = '; domain=' + options.domain;
} else {
x = '';
}
ternary operator is like simple if,else statement like:
condition ? option1 : option2 ;
is similar to
if(condition)
{
option1;
}
else
{
option2;
}
That's called ternary operator. It returns one of two expressions depending on a condition.
Syntax:
test ? expression1 : expression2
test :
Any Boolean expression.
expression1 :
An expression returned if test is true. May be a comma expression.
expression2 :
An expression returned if test is false. More than one expression may be a linked by a comma expression.
This is an similar type of if statement.
return condition ? x : y;
Ternary operator logic is the process of using "(condition) ? (true return value) : (false return value)" statements to shorten your if/else structures.

Jslint use '||' operator instead of conditional operator

I have jslint complaining me to use || operator for below code,
query = ['browser' + (ieVersion ? ieVersion : 'UNKNOWN')]
I tried using || operator but that ends up in wrong result,
query = ['browser' + ieVersion || 'UNKNOWN']
// => ['browserundefined']
Operator precedence is wrong, try this:
query = ['browser' + (ieVersion || 'UNKNOWN')]
without extra parentheses + operator is stronger and JavaScript engine evaluates it as:
query = [('browser' + ieVersion) || 'UNKNOWN']
Notice that 'browser' + ieVersion is never falsy so you'll never see 'UNKNOWN'.
brackets?
query = ['browser' + (ieVersion || 'UNKNOWN')]
You need to wrap the expression in parentheses:
query = ['browser' + (ieVersion || 'UNKNOWN')]

Categories

Resources