Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Replace undefined with 0

I have a variable that gets defined by user input. I want to replace its value only if it's undefined. But not if it's NaN. How can I do it?

I tried doing x || 0 but that also replaces NaN values.

like image 1000
user3312508 Avatar asked May 08 '26 13:05

user3312508


1 Answers

For ES6 users you can simply do:

x ?? 0

?? is a Nullish coalescing operator:

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.

like image 60
Sam Avatar answered May 11 '26 02:05

Sam