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 || {};

🚀 I just relaunched my Vanilla JS Pocket Guides with new code examples and real projects to help tie everything you’ll learn together. Check it out.

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

Get Daily Developer Tips