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

🔥 Hot off the press! I just launched a new pocket guide. Learn how to build interactive web apps with vanilla JavaScript.

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

Get Daily Developer Tips