Skip to main content Accessibility Feedback

Default values for JavaScript variables

Sometimes in JavaScript you want to provide a default value for a variable that can be overridden. That’s super easy to do with the || operator.

var elem = document.querySelector('#some-element') || document.createElement('div');

In the example above, elem will be set to the element on the page with the ID some-element if such an element exists. If not, an empty div will be created.

I use this all the time in my plugins, where users can pass in options, but don’t have to.

var userOptions = options || {};

🚀 Make 2018 the year you master JavaScript! My pocket guides and mini courses are short, focused, and made for beginners. You can do this!

Have any questions or comments about this post? Email me at or contact me on Twitter at @ChrisFerdinandi.

Get Daily Developer Tips