r/learnjavascript • • Mar 23 '21

Assigning default value

Post image
278 Upvotes

24 comments sorted by

View all comments

74

u/CarsonMcKinstry Mar 23 '21

This isn’t quite correct, at least not anymore. This will also catch false and 0 since || will check for falsy values on the left hand side. You can use ?? nowadays to guard against only null and undefined

25

u/fukitol- Mar 23 '21

Been using js for years and didn't know about ??. Thanks for that.

18

u/madspillage Mar 23 '21

It was only added in javascript a couple of years ago.

9

u/fukitol- Mar 23 '21

For anyone reading this, maybe doubting their ability, let this be a reminder. Even the graybeards get rusty.

3

u/CarsonMcKinstry Mar 23 '21

Honestly, JS changes so quickly nowadays it can be difficult to keep up. Not so quickly that it's difficult to learn, but quick enough that you can see version boundaries in code sometimes :D