Home > front end >  How to check if value is undefined and if it is, set it to null
How to check if value is undefined and if it is, set it to null

Time:10-12

value = value ? value : null;

I want to set value to null if it is undefined. Beside what I already have written, what else I can do with less repeating and more clean?

CodePudding user response:

Nullish coalescing operator (??)

You can use the nullish coalescing operator, which is a "[...] logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand":

value = value ?? null;

This best fits your requirements to assign null when value is undefined. In combination with the assignment, this can be made even more concise by using the logical nullish assignment operator (??=):

value ??= null;

This should meet all your requirements, but let's also look at some possible alternatives:

Logical OR operator (||)

Another alternative could be the || operator:

value = value || null;

Or in its assignment form:

value ||= null;

The difference here is that null will be assigned for any falsy value, including 0, false, and ''.

Ternary operator (?:)

This is the original implementation from your question:

value = value ? value : null;

Essentially, this exhibits the same problem as the logical OR operator implementation in the sense that null will be assigned for any falsy value. In this case, however, this can be mitigated by including a stricter comparison in the ternary condition (making it even more verbose):

value = value != null ? value : null;

CodePudding user response:

undefined, null, 0, Nan and '' are considered as a falsy statement, so if you want to make sure that you update your variable only if it holds an undefined value you should consider using an if statement like this if(value==undefined) value =null;

  • Related