Best practice using null in a ternary operator in JavaScript - javascript

Hey first time poster/user, I have been working through some coding exercises. I wrote a piece of code that passed tests but I am unsure if this is best practice
In this sample I am iterating over an array using the filter function. I am using a call back function that will return words with length greater than 5.
sample code
const words = ['unique', 'uncanny', 'pique', 'oxymoron', 'guise'];
const interestingWords = words.filter(word => {
return word ? word.length > 5 : null
})
In my head if the condition isn't met it shouldn't even try to return. What is happening when I return a null? or is this a case where I wouldn't use ternary at all.
The best I got was from MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null
The value null is written with a literal: null. null is not an identifier for a property of the global object, like undefined can be. Instead, null expresses a lack of identification, indicating that a variable points to no object. In APIs, null is often retrieved in a place where an object can be expected but no object is relevant.
So should I refrain from returning a null in this context?

All .filter's callback cares about is the truthy or falsey value returned inside it. Here, it'd be better to return that comparison directly, no conditional operator needed:
const interestingWords = words.filter(word => word.length > 5);
A construction like
return word ? word.length > 5 : null
could make sense if you needed to check a sub-property, but only if the array element existed first, eg:
const objects = [
null,
{ word: 'foo' },
{ word: 'barbar' },
null
];
const interestingObjects = objects.filter(
obj => obj ? obj.word.length > 5 : null
);
console.log(interestingObjects);

If elements of the array might be null or undefined, you can use the optional chaining operator.
const interestingWords = words.filter(word => {
return word?.length > 5
})

Related

Exception for null fetched data React

I am mapping fetched data like this in React.
I am printing name, column and row to the paragraph so whenever it is null, it prints just null null null, but if warehouse_name is null I need to transfer all values to some String like "Undefined" instead of these tree null.
There can be maybe better solution with using some string method for paragraph instead of this?
const transformedData = data.order_items.map((invoiceData) => {
return {
alternative_warehouse_position: invoiceData.alternative_warehouse_position,
warehouse_column: invoiceData.warehouse_column,
warehouse_name: invoiceData.warehouse_name,
warehouse_row: invoiceData.warehouse_row,
};
3 ways to do it:
Using the "?" to check if its null. Example: ${Condition} ? ${is true} : ${is false}.
Using the new null-checking syntax. Example: ${Value} ?? ${the replacement if its null}
Using the OR operator, which enhances backwards capabilities. Example: ${first condition} || ${Second to replace if the first is false}
Note: Null counts as false
You could use the nullish coalescing operator ??.
const FALLBACK_STRING = "(not set)";
return {
alternative_warehouse_position: invoiceData.alternative_warehouse_position ?? FALLBACK_STRING,
warehouse_column: invoiceData.warehouse_column ?? FALLBACK_STRING,
warehouse_name: invoiceData.warehouse_name ?? FALLBACK_STRING,
warehouse_row: invoiceData.warehouse_row ?? FALLBACK_STRING,
};
If I understand you correctly, you want to replace all three values with one string if invoiceData.warehouse_name is null. You can use the ternary operator (?:) for that.
const transformedData = data.order_items.map(
invoiceData => !!invoiceData.warehouse_name ?
{
alternative_warehouse_position: invoiceData.alternative_warehouse_position,
warehouse_column: invoiceData.warehouse_column,
warehouse_name: invoiceData.warehouse_name,
warehouse_row: invoiceData.warehouse_row
} :
"No data"
);
If what you want to do is to return the "Undefined" string instead of null, then you could try the following code instead:
const transformedData = data.order_items.map((invoiceData) => {
return {
alternative_warehouse_position: invoiceData.alternative_warehouse_position || "Undefined",
warehouse_column: invoiceData.warehouse_column || "Undefined",
warehouse_name: invoiceData.warehouse_name || "Undefined",
warehouse_row: invoiceData.warehouse_row || "Undefined",
}});
If this isn't what you mean, could you elaborate further, especially on the "...but if warehouse_name is null I need to transfer all values to some String like "Undefined" instead of these tree null." part of the problem statement?

Best way to get a decent result from this Array check?

I am trying to get a decent result that I can do something with, but feel the way I am it at the moment in the 'check' function isn't actually returning other than an expression:
validate = () => {
const items = this.state.data;
const check = e => {
!e.error === undefined ? true : false;
};
const checkFields = items.some(check);
if (!checkFields) {
alert('form valid');
}
};
Is the 'check' function any good?
The check function does not return anything. Either:
Remove the braces so that it no longer is a code block, but an expression whose value is returned, or
Add a return before the expression.
Secondly:
The ! operator has precedence over ===, so !e.error === undefined is not doing what you think. You can use parentheses, like !(e.error === undefined), but why not just e.error !== undefined?
And it really is not necessary to apply the ternary operator on that. It is already a boolean expression, so just use it without that ? true : false.
In short:
const check = e => e.error !== undefined;
Concerning the overall function validate: Using alert is quite primitive, and not the most user-friendly thing to do. You should consider applying CSS styling to the input that does not pass validation.

!! used in node ? will this check undefined in node and array length and empty Object in what all cases can this be used for

i came across this code recently in node. but i cant find a good understanding on where to use this.
I want data to be not undefined, not 0 and not empty array.
if(!!data){
do something ...
}
It proves working fine for empty array value = 0, etc can someone explain in detail about this.
if ( typeof data !== 'undefined'){ do something }
if ( data !== null ){ do something }
I have tried to implement this and it failed when i send an undefined variable.
the feature can be used to full extend if it can be shared to everyone.
this is just pure js. Double NOT operator "!!". So the first ! coerce the value to a boolean and inverse it, then the second ! reverses it to the original boolean equivalent. So basically converts nonboolean to boolean
Array length will not be considered. Empty arrays will be avoided. Empty String will be checked. Any value 0 will be considered false and other integers will be considered true. Lets look at all these examples and figure out the usage.
let a = 0 ;
console.log(!!a) //false
a = "";
console.log(!!a) //false
a = " ";
console.log(!!a) // true since a has a space value
console.log(!!a.trim())//false
a = undefined
console.log(!!a) //false
a= {}
console.log(a) // true Use Object.keys(a).length > 0 to check empty object or
// use _.isEmpty(a) for checking empty object
a = { name:"Rahul"}
console.log(a) // true
a = []
console.log(a) // true Use array.length > 0 to check empty array
a = [1,2,3]
console.log(a) // true

What is Simpler Way to Write Code That Sums Up Length of Strings including nulls and undefineds in JavaScript

I want to add some defensive coding to the following check. I have 3 strings and I want to know if any of them have anything in them (for my purposes, null or undefined means they do not have anything in them).
if (twitterUrl.length + facebookUrl.length + linkedInUrl.length > 0) {
This works, but feels like very bulky. I use TypeScript and not sure if there is anything there that can help me with this.
if ((twitterUrl ? twitterUrl.length : 0) +
(facebookUrl ? facebookUrl.length : 0) +
(linkedInUrl ? linkedInUrl.length : 0) > 0) {
You can use the fact that empty strings are falsy¹. If you know they'll be strings or null or undefined and you don't need to worry about strings with just whitespace in them (" " is truthy¹), then:
if (twitterUrl || facebookUrl || linkedInUrl) {
If you need to worry about trimming, then a helper function is probably in order:
function present(s) {
return s && (typeof s !== "string" || s.trim());
}
and
if (present(twitterUrl) || present(facebookUrl) || present(linkedInUrl)) {
or
if ([twitterUrl, facebookUrl, linkedInUrl].some(present)) {
¹ falsy and truthy: When you use a value in a condition (like an if), JavaScript will implicitly coerce the value to a boolean. A value that coerces to false is falsy; one that coerces to true is truthy. The falsy values are "", null, undefined, 0, NaN, and of course, false. All other values (including " ") are truthy.
You could define a function as the following one:
function getLength(s){
if(typeof s !== "string") return 0;
return s.length;
}
and then use it like below:
if (getLength(twitterUrl) > 0 || getLenght(facebookUrr) > 0 || getLength(linkedInUrl){
// code
}
Essentially, getLength check if the value you pass when you call the function is a string and if so it returns its length. Otherwise, it returns 0. So in order to achieve that you want, (I want to know if any of them have anything in them), you have to check one by one the strings you have, if the first string has a length greater than zero, there isn't any need to continue the check for the other two strings. Otherwise you call the function on the second string and so on and so forth.
Try like this, normal if statement also works
const socialLinks = [twitterUrl, facebookUrl, linkedInUrl];
const hasSomething = socialLinks.some(social => social);
Here is falsy value like null, undefined, '' and etc., https://developer.mozilla.org/en-US/docs/Glossary/Falsy
if social are empty string('') or null or undefined then it's return false. We omitted return keyword because arrow function has implicit return behaviour.
This is a solution using some(), which checks whether at least one element in the array passes the test implemented by the provided function.
var twitterUrl, facebookUrl, linkedInUrl;
linkedInUrl = 'nonEmpty';
result = [twitterUrl, facebookUrl, linkedInUrl].some(arrVal => arrVal);
console.log(result);

How can I test whether a variable has a value in JavaScript?

I want to test whether a JavaScript variable has a value.
var splitarr = mystring.split( " " );
aparam = splitarr [0]
anotherparam = splitarr [1]
//.... etc
However the string might not have enough entries so later I want to test it.
if ( anotherparm /* contains a value */ )
How do I do this?
if (typeof anotherparm == "undefined")
An empty string evaluates to FALSE in JavaScript so you can just do:
if (anotherparam) {...}
In general it's sort of a gray area... what do you mean by "has a value"? The values null and undefined are legitimate values you can assign to a variable...
The String function split() always returns an array so use the length property of the result to figure out which indices are present. Indices out of range will have the value undefined.
But technically (outside the context of String.split()) you could do this:
js>z = ['a','b','c',undefined,null,1,2,3]
a,b,c,,,1,2,3
js>typeof z[3]
undefined
js>z[3] === undefined
true
js>z[3] === null
false
js>typeof z[4]
object
js>z[4] === undefined
false
js>z[4] === null
true
you can check the number of charactors in a string by:
var string_length = anotherparm.length;
One trick is to use the or operator to define a value if the variable does not exist. Don't use this if you're looking for boolean "true" or "false"
var splitarr = mystring.split( " " );
aparam = splitarr [0]||''
anotherparam = splitarr [1]||''
This prevents throwing an error if the variable doesn't exist and allows you to set it to a default value, or whatever you choose.
So many answers above, and you would know how to check for value of variable so I won't repeat it.
But, the logic that you are trying to write, may be better written with different approach, i.e. by rather looking at the length of the split array than assigning to a variable the array's content and then checking.
i.e. if(splitarr.length < 2) then obviously anotherparam is surely 'not containing value'.
So, instead of doing,
if(anotherparam /* contains a value */ )
{
//dostuff
}
you can do,
if(splitarr.length >= 2)
{
//dostuff
}

Categories

Resources