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]
Related
In my app, I need to check if a div container is empty before appending certain text elements to it (the innerHTML is created and removed many times in my app, hence the need to check for emptiness). The div is created very simply as below in the beginning. Why doesn't checking for an empty string as below work? I am expecting the alert to show the text Nothing, but it does not.
let targetContainer = document.getElementById("container")
let containerText = targetContainer.innerHTML
alert("Text: " + containerText == "" ? "Nothing" : containerText)
#container {
background-color: #0f2e0c;
}
<div id="container"></div>
Your main issue is with operator precedence. Currently, you code is evaluating like so:
("Text: " + containerText) == "" ? "Nothing" : containerText
in your code + has higher operator precedence than ==, meaning that the concatenation occurs before the == occurs. You can force the evaluation of the equality and the ternary to occur before the addition concatenation occurs by wrapping it in parenthesis to group your ternary operation. Since grouping has the highest operator precedence it will occur before your concatenation occurs:
"Text: " + (containerText == "" ? "Nothing" : containerText)
let targetContainer = document.getElementById("container")
let containerText = targetContainer.innerHTML
alert("Text: " + (containerText == "" ? "Nothing" : containerText));
#container {
background-color: #0f2e0c;
}
<div id="container"></div>
Usually I use this:
myVar = "myString is" + 1 === 1 ? " really true" : " false, I think";
Maybe I need just the true part, let's say:
myVar = "myString is" + 1 === 1 ? " really true" : "";
I don't like this part: : "" because is useless.
Is there a way to use something like the below?
myVar = "myString is" + 1 === 1 && " really true";
It works but there is a problem when is false because it writes "false"!
You could always go with a good old if statement
var myVar = 'myString is';
if (1===1){myVar+=' really true';}
I think that makes it more readable than a one line boolean test
To be pragmatic the best pattern and best way to write this is to rely on a helper:
myVar = "my string is"+myHelper(...myParams);
Then in the helper we'll have a case/switch that is made exactly with this purpose and is really readable.
You can just use ||
myVar = (1 === 1 && "myString is really true") || "";
Wrap the 1 === 1 && " really true" inside parentheses () and add || '' like below (also wrapped in parentheses), or could use template literals to save you some time from typing those +s
let myString = "myString is" + ((1 === 1 && " really true") || '');
let myFalseString = "myString is" + ((1 === 0 && " really true") || '');
let onlyFalse = "myString is" + 1 === 1 && " really true";
let myTL = `myString is ${(1 === 1 && "really true") || ''}`;
console.log('My String:', myString);
console.log('False String:', myFalseString);
console.log('Only false:', onlyFalse);
console.log('My Template Literal:', myTL);
Looks much worse than having the extra : "" though so I would still recommend doing it like that:
myVar = "myString is" + 1 === 1 ? " really true" : "";
another way to achieve something like this could be to use an Array, and concat the values if they are not false. Not that it is any shorter than adding the : '', but as far as i know there is no way to get rid of the : ''
console.log( ["my string is", 1 === 1 && "really true"].filter(Boolean).join(" ") );
console.log( ["my string is", 1 === 2 && "really true"].filter(Boolean).join(" ") );
i would prob stick with the : '' or write a helper function that could look something like this.
function concat(){
let str = "";
for(let s of arguments){
str += s ? s : '';
}
return str;
}
console.log( concat("my string is", 1 === 1 && "really true") );
console.log( concat("my string is", 1 === 2 && "really true") );
Analysing the ternary operator we conclude that it's something like this:
// Example: 1 === 1 ? ' is really true' : ''
if (1 === 1) {
return ' is really true';
} else {
return '';
}
So the solution would be simply to remove the 'else' from the ternary operator, generating a 'binary'. Use a lone IF:
if (1 === 1) {
myVar += 'is really true';
}
The best solution to use the logic operator inline is the ternary operator itself. It's not a problem to have the 'false' part of it as a empty string "". But if you're really annoyed by it you could create a function and use the template literals like this:
function myFunction(evaluation) {
if (evaluation) {
return ' really true';
}
return '';
}
let myVar = `My String is ${myFunction(1 === 1)}`;
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>
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 ''.
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.