DEV Community

Discussion on: The Difference Between Null and Undefined in JavaScript

Collapse
 
michaelcurrin profile image
Michael Currin • Edited

Note that var and let keywords let you make undefined but const does not

let x

// syntax error
const y
Enter fullscreen mode Exit fullscreen mode

For bonus points, add a fallback for undefined or null or falsy (zero, empty string)

let x

const y = x || "default"
console.log(y.toUpperCase())
Enter fullscreen mode Exit fullscreen mode

Or in newer versions of JS, you can use this to handle null and undefined, but it won't replace zero or empty string.

let y

const x = y ?? "default"
Enter fullscreen mode Exit fullscreen mode

michaelcurrin.github.io/dev-cheats...

TypeScript can enforce missing values for you so you don't have to throw errors or use a fallback.

Collapse
 
za-h-ra profile image
Zahra Khan

I didn't even consider const. Thank you for pointing that out!