The default keyword can be used in two situations in JavaScript: within a switch statement, or with an export statement.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
Syntax
Within a switch statement:
switch (expression) {
case value1:
//Statements executed when the result of expression matches value1
[break;]
default:
//Statements executed when none of the values match the value of the expression
[break;]
}
With export statement:
export default nameN
Description
For more details see the
Examples
Using default in switch statements
In the following example, if expr evaluates to "Oranges" or "Apples", the program matches the values with either the case "Oranges" or "Apples" and executes the corresponding statement. The default keyword will help in any other case and executes the associated statement.
switch (expr) {
case 'Oranges':
console.log('Oranges are $0.59 a pound.');
break;
case 'Apples':
console.log('Apples are $0.32 a pound.');
break;
default:
console.log('Sorry, we are out of ' + expr + '.');
}
Using default with export
If you want to export a single value or need a fallback value for a module, a default export can be used:
// module "my-module.js"
let cube = function cube(x) {
return x * x * x;
};
export default cube;
Then, in another script, it will be straightforward to import the default export:
// module "another-module.js" import cube from 'my-module'; //default export gave us the liberty to say import cube, instead of import cube from 'my-module' console.log(cube(3)); // 27
Specifications
Browser compatibility
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
default keyword in switch | Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 4 | Opera Full support Yes | Safari Full support Yes | WebView Android Full support 1 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support 1.0 | nodejs Full support Yes |
default keyword with export | Chrome Full support 61 | Edge
Full support
16
| Firefox
Full support
60
| IE No support No | Opera Full support 47 | Safari Full support 10.1 | WebView Android No support No | Chrome Android Full support 61 | Firefox Android
Full support
60
| Opera Android Full support 44 | Safari iOS Full support 10.3 | Samsung Internet Android Full support 8.0 | nodejs ? |
Legend
- Full support
- Full support
- No support
- No support
- Compatibility unknown
- Compatibility unknown
- User must explicitly enable this feature.
- User must explicitly enable this feature.