{{jsSidebar("Statements")}}
The default keyword can be used in two situations in JavaScript:
- within a {{jsxref("Statements/switch", "switch")}} statement, or
- with an {{jsxref("Statements/export", "export")}} statement.
Syntax
Within a {{jsxref("Statements/switch", "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 {{jsxref("Statements/export", "export")}} statement:
export default nameN
Description
For more details see the
- {{jsxref("Statements/switch", "switch")}} statement and
- {{jsxref("Statements/export", "export")}} statement pages.
Examples
Using default
in switch
statements
In the following example, if expr
evaluates to "Bananas" or "Apples", the program matches the values with either the case "Bananas" 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 "my-module.js" import myFunction from 'my-module'; console.log(myFunction(3)); // 9
Specifications
Specification | Status | Comment |
---|---|---|
{{SpecName('ES6', '#sec-switch-statement', 'switch statement')}} | {{Spec2('ES6')}} | |
{{SpecName('ES6', '#sec-exports', 'Exports')}} | {{Spec2('ES6')}} |
Browser compatibility
{{CompatibilityTable}}
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Switch default | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} |
Export default | {{CompatNo}} | {{CompatNo}} | {{CompatNo}} | {{CompatNo}} | {{CompatNo}} |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Switch default | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} |
Export default | {{CompatNo}} | {{CompatNo}} | {{CompatNo}} | {{CompatNo}} | {{CompatNo}} | {{CompatNo}} |
See also
- {{jsxref("Statements/export", "export")}}
- {{jsxref("Statements/switch", "switch")}}