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