re: Create A Dark/Light Mode Switch with CSS Variables VIEW POST


Instead of using the following instruction you used, which forces two calls to localStorage (which is pretty slow),

const currentTheme = localStorage.getItem('theme') ? localStorage.getItem('theme') : null;

you could use an or operator.

// Value at right-hand side of || is the default
const currentTheme = localStorage.getItem('theme') || null;

or, in this case, as the default is null, even simpler,

const currentTheme = localStorage.getItem('theme');

by taking the property of localStorage.getItem to return null on unknown key to directly return the expected value/default.


Yes, this makes more sense. Thanks! 🙂
I'll update the demo.

Code of Conduct Report abuse