Evaluating 'Falsey' Values

Here’s a bit of code I’ve been looking at as part of an exercise. It works if x is left undefined as presented below (value === 100), it works if x is set to say 10 (value === 10), but if I purposely set var x = null, I end up with value set to null also, where it should be 100.

// JavaScript exercise
var x, value;
if( x === undefined || null ) {
  value = 100;
}
else {
  value = x;
}
console.log( 'X is ' + x );
console.log( 'Value is ' + value );
// end of exercise

I’ve tried altering the evaluation step in a couple of ways

if( x === (undefined || null) )

and…

if( typeof(x) === undefined || null )

but both neither of those worked either, and broke the parts that had previously worked into the bargain. What am I missing?

typeof isn’t a function, it’s an “operator”. And it returns a String.

NULL is considered an “object”.

So you don’t need the parentheses around the variable x and you need quotes around the type. eg. more like.

if(typeof x === ‘undefined’ || ‘null’) {`

Though the string “null” won’t happen as a typeof

1 Like

Could you modify it to read as follows then, to take account of null not happening as a typeof?

if(typeof x === 'undefined' || x === 'null') {

Yes, that would work well when the quotes around null are removed (from a later post).

If any kind of falsy value is okay to assign to 100, even zero, you could alternatively go with the following:

if (!x) {
    value = 100;
} else {
    value = x;

Which could then be condensed to:

value = (x ? x : 100);

Or even:

value = x || 100;

But that might be getting too compact and difficult to easily understand.

1 Like

I hear you… :wink:

Interestingly, the prepared solution is literally shown as

x || 100

But there is nothing I can see in the material leading up to the exercise that would lead you to reduce things down to that level…

One minor amendment, it turns out the quotes need to be removed from around null, as…

if(typeof x === 'undefined' || x === null) {

That works

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.