Home > Blockchain >  JavaScript code golf: Shortest way to check if a variable contained a number
JavaScript code golf: Shortest way to check if a variable contained a number

Time:06-19

Unfortunately in this case 0 is false, so I can’t simply say if (x)

I’m hoping for something shorter than this to improve my code golf answer that’s shorter than these options

// check explicitly for 0
x||x==0

// isNaN
!isNaN(x)

I could remove the ! in isNaN by inverting the if else logic but the former is shorter anyway. Anything better?

UPDATE: It can be assumed that x is either undefined or a number. It by definition won’t be other truthy values such as the empty string.

To give a little more context I’m saving numbers (which will for certain be numbers do to problem restrictions) to an object than later checking that object at specified indices to see if it contains a number or undefined at the specified index.

CodePudding user response:

You could check if it's nullish (null or undefined) using the ?? operator.

For example these two are equivalent:

if (x != null) {
  /* statement */
}
x ?? /* statement */

In your specific case, you can also use it when assigning a value (x) onto your object (o) if the property (z) is not nullish.

o.z ??= x;

CodePudding user response:

Got it! I can loosy compare against null on an object I have elsewhere.

i.e.

/// some object o I happened to have declared
/// Some random property I don't have on it such as z
x!=o.z
/// compiles to the following
x!=null
/// which will be false for numbers and true for undefined
  • Related