Simplify simple ternary expression - javascript

I want to validate undefined attributes from an object so I use ternary like this
item.subitem ? item.subitem.toString() : ''
Is there any way to simplify this expression using || or && ?

It's simple:
item.subitem && item.subitem.toString() || ''
Or simply like:
(item.subitem || '').toString()
OR,
''+(item.subitem || '')
If you can use optional chaining, then it can be even more simple:
item.subitem?.toString()
See this post for more detail.
As #Thomas mentioned in comment, you can also use an array and convert to a string:
[item.subitem].toString();
This should clear how it will work:
[].toString(); // ''
[undefined].toString(); // ''
['foo'].toString(); // 'foo'
['foo', 'bar'].toString(); 'foo,bar'

Yes you can
(item.subitem || '').toString()

Related

JavaScript Ternary with Logical OR

var a = '1';
console.log(a == ('2'||'1')?'hi':'hello');
Doing so the condition get failed as a = 1 .
It is comparing a's value 1 with 2 as this condition failed. so it always print hello.
Is there any way to check for value('1') also which is after "||" so that it print hi?
Either list the different possibilities out separately:
a === '2' || a === '1' ? 'hi' : 'hello'
Or use an array and .includes:
['2', '1'].includes(a) ? 'hi' : 'hello'
The problem with ('2'||'1') is that the whole section there gets evaluated to a single expression before the comparison against a is made, and || will evaluate to the initial value if it's truthy. So ('2' || '1') resolves to '2'.
var a = 1;
a == '2'?'hi': a=='1'?'hello' :'';
i Found this is also working.... Thanks to everyone who answered using different ways..

How to write Or values in ternary operator Javascript?

How to write below code in ternary operator?
if(data){
data;
}
else{
"" || anotherData;
}
I am trying to do : data ? data : ""|| anotherData but it always take second value i.e. anotherData when else condition true
Plz suggest.
It's the other way for the second parameter: data ? data : (anotherData || '')
Not exactly clear what you want. What you posted is equivalent to:
data || anotherData
since "" || anotherdata will always evaluate to anotherData.
If you meant anotherData || "" then you can simply do:
data || anotherData || ""
The problem is in the if-else code itself. Switch the "" || anotherData to anotherData || "". According to my understanding of your task, it should get "" only when both data and anotherData are null.

Javascript - is there a better way to check an string instead of indexOf

I use this code and My question would be if there is a better way to check a string than indexOf:
if(documentFile.ending.indexOf('pdf') > -1 || documentFile.ending.indexOf('PDF') > -1 || documentFile.ending.indexOf('docx') > -1)
ES6 has boolean function. Use:
if ( documentFile.ending.includes('pdf') ) { }
Or for regex:
if ( documentFile.ending.match(/your-regex/) { }
Example spec: https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/String/includes
If you are using ES6 then you may want to look at String.prototype.includes
var str = 'To be, or not to be, that is the question.';
console.log(str.includes('To be')); // true
In ES6 you have better option to use "includes"
otherwise use regex
if(/pdf/i.test(documentFile.ending))
Well, indexOf is really fast, a lot faster than using a regular expression. But something like /pdf$/i.test(str) lets you test the end as well as giving you case-insensitivity. But you could be more precise:
function endsWith(str, ending) {
return str != null
&& ending != null
&& ending.length <= str.length
&& str.lastIndexOf(ending) === str.length - ending.length;
}
Note the ending.length <= str.length which is there so that you don't do something like endsWith("", "a") and get true. :)

Conditionally add string to HTML with Angular expression

I have the following :
<div>{{animalType}}</div>
which evaluates to dog.
Can I conditionally add an sif animalTypeevaluates to anything other than dog?
Something like this : which doesn't work
<div>{{animalType}} {{'s' : !animalType == 'dog'}}</div>
So I would getcats
Use ternary operator in expression as follow:
<div>{{animalType}}{{animalType != 'dog' ? 's' : '' }}</div>
Alternatively
<div>{{animalType}}<span ng-show="animalType!='dog'">s</span></div>
Not tested, but try this simple snippet:
<div>{{animalType === "dog" ? animalType : "s"}}</div>
By the way, if you want to switch only between two values, from my point of view, logically appealing would be something like that:
<div>{{isDog ? "dog" : "s"}}</div>
$scope.isDog = true/false
You could also use ng-if
<div>{{animalType}}<div ng-if="animalType !== 'dog'">s</div></div>

How to use OR condition in a JavaScript IF statement?

I understand that in JavaScript you can write:
if (A && B) { do something }
But how do I implement an OR such as:
if (A OR B) { do something }
Use the logical "OR" operator, that is ||.
if (A || B)
Note that if you use string comparisons in the conditions, you need to perform a comparison for each condition:
if ( var1 == "A" || var1 == "B" )
If you only do it in the first one, then it will always return true:
if ( var1 == "A" || "B" ) //don't do this; it is equivalent to if ("B"), which is always true
The official ECMAScript documentation can be found here
Worth noting that || will also return true if BOTH A and B are true.
In JavaScript, if you're looking for A or B, but not both, you'll need to do something similar to:
if( (A && !B) || (B && !A) ) { ... }
if (A || B) { do something }
Use the || operator.
|| is the or operator.
if(A || B){ do something }
here is my example:
if(userAnswer==="Yes"||"yes"||"YeS"){
console.log("Too Bad!");
}
This says that if the answer is Yes yes or YeS than the same thing will happen
One can use regular expressions, too:
var thingToTest = "B";
if (/A|B/.test(thingToTest)) alert("Do something!")
Here's an example of regular expressions in general:
var myString = "This is my search subject"
if (/my/.test(myString)) alert("Do something here!")
This will look for "my" within the variable "myString". You can substitute a string directly in place of the "myString" variable.
As an added bonus you can add the case insensitive "i" and the global "g" to the search as well.
var myString = "This is my search subject"
if (/my/ig.test(myString)) alert("Do something here");
You may also want to filter an IF statement when condition1 equals 'something' AND condition2 equals 'another thing' OR 'something else'. You can do this by placing condition2 in another set of brackets eg...
if (condition1 === 'x' && (condition2 === 'y' || condition2 === 'z')) {
console.log('do whatever')
}
If condition2 is NOT in it's own brackets then condition1 has to be x AND condition2 has to be y for the function to trigger...
... but it will also trigger if condition2 is z, regardless of what condition1 is. Which may be okay depending on your use case, but something to be mindful of.

Categories

Resources