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

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>

Related

Default beginning value of innerHTML of a div

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>

How to delete return value if variable is blank in javascript

I have written one function :
function abcd(gg,hh,ii,jj){
return "Hi,\n\nBelow is alert."\n\n"+gg+"\n"+hh+"\n"+ii+"\n"+jj+";
}
where 4 variables gg,hh,ii,jj has written globally and calling dynamically. where 'gg' containg 'Approval is done', 'hh' containg 'Approval is done', 'ii' containg 'Approval is done', 'jj' containg 'Approval is done'. My concern is sometime i have value for gg , hh, ii or jj and sometime not and i am getting output as below if i have value for all variable by mentioned above Function code:
Hi,
Below is alert.
Approval is done.
Approval is done.
Approval is done.
Approval is done.
So If 'ii' is blank then i need as below, but my code is returning line space if 'ii' is blank:
Hi,
Below is alert.
Approval is done.
Approval is done.
Approval is done.
Probably the cleanest, with how you have it, would be something like this:
function abcd(gg,hh,ii,jj){
return "Hi,\n\nBelow is alert.\n\n"
+ (gg ? gg + "\n" : '')
+ (hh ? hh + "\n" : '')
+ (ii ? ii + "\n" : '')
+ jj;
}
The ternary operator (?:) is in the format condition ? if_true : if_false. You can check for a "falsy" value on the string (null and '' both count as false), so it'll only output stuff if it's not falsey.
If ii will be an empty string, here is a quick fix:
function abcd(gg,hh,ii,jj){
return "Hi,\n\nBelow is alert.\n\n" + [gg,hh,ii,jj].filter(Boolean).join("\n");
}
.filter(Boolean) basicaly filters empty strings, (since those will return false, which is a boolean).
.join("\n") converts your array to a string, But with using \n rather than ,
You can use Array.filter to filter out the blank ones, and then join them:
function getNonBlanks(array) {
return array.filter(function (i) {
// we only want items with a length
return i.length > 0;
});
}
function abcd(gg,hh,ii,jj){
return "Hi,\n\nBelow is alert.\n\n" + getNonBlanks([gg,hh,ii,jj]).join("\n");
}

Understanding ternary operators with concatenated strings

I am using JavaScript examples, however, it is not meant to be a JavaScript only question as the results are the same for PHP and I expect many languages. I've "dealt" with my lack of understanding by using a multitude of parentheses, however, it is time to deal with it.
Given the script below (and also at https://jsfiddle.net/5z4paegb/)..
function testTernary(isjane) {
var str = 'hello ' + isjane ? 'Jane' : 'Mary';
console.log(isjane, str);
}
testTernary(true);
testTernary(false);
testTernary(1);
testTernary(0);
testTernary(null);
I would have expected:
true hello Jane
false hello Mary
1 hello Jane
0 hello Mary
null hello Mary
But I get:
true Jane
false Jane
1 Jane
0 Jane
null Jane
According to JavaScript's precedence table,
'hello ' + isjane ? 'Jane' : 'Mary';
is equivalent to:
('hello ' + isjane) ? 'Jane' : 'Mary';
This is because the + operator has a higher precedence than the ?: ternary operator. (The ?: operator is actually quite low on JavaScript's precedence table, higher only than assignment operations, yield, ..., and ,.)
You can get your desired effect with:
'hello ' + (isjane ? 'Jane' : 'Mary');
In general, when dealing with the ternary operator, it's best to put parenthesis around the ternary operator and its operands so that it's explicitly clear what is part of the conditional operation.
This is also the case in PHP's operator precedence table as well.
Your ternary operator will evaluate to true because you are evaluating a concatenated string,
you could do this instead:
isJane = isJane ? "Jane" : "Mary";
var str = "hello" + isJane;
or:
var str = "hello" + (isJane ? "Jane" : "Mary");

conditional short hand doesn't work?

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

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!

Categories

Resources