With ES6: This is now part of the language:

function myFunc(a, b = 0) {
   // function body
}

Please keep in mind that ES6 checks the values against undefined and not against truthy-ness (so only real undefined values get the default value - falsy values like null will not default).


With ES5:

function myFunc(a,b) {
  b = b || 0;

  // b will be set either to b or to 0.
}

This works as long as all values you explicitly pass in are truthy. Values that are not truthy as per MiniGod's comment: null, undefined, 0, false, ''

It's pretty common to see JavaScript libraries to do a bunch of checks on optional inputs before the function actually starts.

Answer from Tigraine on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Functions › Default_parameters
Default parameters - JavaScript | MDN
Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.
Top answer
1 of 2
657

With ES6: This is now part of the language:

function myFunc(a, b = 0) {
   // function body
}

Please keep in mind that ES6 checks the values against undefined and not against truthy-ness (so only real undefined values get the default value - falsy values like null will not default).


With ES5:

function myFunc(a,b) {
  b = b || 0;

  // b will be set either to b or to 0.
}

This works as long as all values you explicitly pass in are truthy. Values that are not truthy as per MiniGod's comment: null, undefined, 0, false, ''

It's pretty common to see JavaScript libraries to do a bunch of checks on optional inputs before the function actually starts.

2 of 2
110

Update

With ES6, this is possible in exactly the manner you have described; a detailed description can be found in the documentation.

Old answer

Default parameters in JavaScript can be implemented in mainly two ways:

function myfunc(a, b)
{
    // use this if you specifically want to know if b was passed
    if (b === undefined) {
        // b was not passed
    }
    // use this if you know that a truthy value comparison will be enough
    if (b) {
        // b was passed and has truthy value
    } else {
        // b was not passed or has falsy value
    }
    // use this to set b to a default value (using truthy comparison)
    b = b || "default value";
}

The expression b || "default value" evaluates the value AND existence of b and returns the value of "default value" if b either doesn't exist or is falsy.

Alternative declaration:

function myfunc(a)
{
    var b;

    // use this to determine whether b was passed or not
    if (arguments.length == 1) {
        // b was not passed
    } else {
        b = arguments[1]; // take second argument
    }
}

The special "array" arguments is available inside the function; it contains all the arguments, starting from index 0 to N - 1 (where N is the number of arguments passed).

This is typically used to support an unknown number of optional parameters (of the same type); however, stating the expected arguments is preferred!

Further considerations

Although undefined is not writable since ES5, some browsers are known to not enforce this. There are two alternatives you could use if you're worried about this:

b === void 0;
typeof b === 'undefined'; // also works for undeclared variables
Discussions

Whats the best way to skip optional parameters?
You can pass 'undefined' instead of the parameter you want to skip. More details here https://stackoverflow.com/questions/8356227/skipping-optional-function-parameters-in-javascript . Also a good practice is to group your parameters in an object and pass just one parameter as an object. In this case you don't need to worry about the order of parameters passed More on reddit.com
🌐 r/learnjavascript
25
6
July 4, 2022
With a functin that has two arguments with default values, what is the best way to call this function with the default value for the first argument but with a new value for the second argument?
Using undefined as an argument value is the correct way to let the parameter get its default. Alternatively you can use an object for your optional parameters (similar to what InTheAtticToTheLeft suggested) which is a little more verbose - in a nice, named parameter kind of way - but doesn't require undefineds in place of unspecified parameters. function myFunc({argOne = 'one', argTwo = 'two'} = {}) { console.log(argOne, argTwo); } myFunc({argOne: 'newOne'}) // newOne two myFunc({argTwo: 'newTwo'}) // one newTwo The example above uses destructuring to allow the properties of the object to be seen as individual variables within the function body. The default empty object accounts for the case when no arguments are provided. myFunc() // one two More on reddit.com
🌐 r/learnjavascript
15
4
April 18, 2024
Interface separation or use optional parameters
The first one is usually more strict, better imo. In the second, you have to do checks in attributes and throws in runtime. The first is also more complex to work with, but if you do everything that way from the start, it shouldn't be a problem. A typical, more como example between create and update, is that update requires an id (specially when talking about DB updates), but create doesn't. So it's common to see an "Update extends Create". More on reddit.com
🌐 r/typescript
13
3
January 17, 2024
How to skip optional parameters in JS (and other questions too)?
My friend also requested me to make a tool like create react app which can generate a PWA You realise this is r/learnjavascript right? Not r/buildmea100kprogram More on reddit.com
🌐 r/learnjavascript
5
1
October 22, 2022
🌐
W3Schools
w3schools.com › js › js_function_parameters.asp
JavaScript Function Parameters
Parameters are the names listed in the function definition. Arguments are the real values passed to, and received by the function. ... JavaScript function definitions do not specify data types for parameters.
🌐
CoreUI
coreui.io › blog › how-to-declare-the-optional-functions-parameters-in-javascript
How to declare the optional function parameters in JavaScript? · CoreUI
March 5, 2024 - Optional parameters allow functions to be called with fewer arguments than defined in the function’s declaration. This feature can significantly simplify your code, making it more readable and maintainable. Let’s explore the various methods to achieve this in JavaScript.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-declare-the-optional-function-parameters-in-javascript
Declare Optional Function Parameters in JavaScript - GeeksforGeeks
November 3, 2025 - The assignment operator (`=`) approach allows you to set default values directly in the function's parameter list. If an argument is not provided, the parameter automatically takes the default value, simplifying the handling of optional parameters in functions.
🌐
Leaflet
leafletjs.com › reference.html
Documentation - Leaflet - a JavaScript library for interactive maps
Some of the Map methods which modify the center of the map take in an options parameter. This is a plain javascript object with the following optional components:
Find elsewhere
🌐
Reddit
reddit.com › r/learnjavascript › whats the best way to skip optional parameters?
r/learnjavascript on Reddit: Whats the best way to skip optional parameters?
July 4, 2022 -

Like here I'm trying to skip the options parameter and use the callback function parameter.

https://i.imgur.com/v70j3av.png

I could have sworn you just use a comma but it's not working. Do you just write a function and it will know and recognize it's the third parameter and not the second?

And I don't mean for this function in the screenshot specifically, I mean all functions with optional parameters. Whats the best method for skipping them?

Top answer
1 of 7
3
You can pass 'undefined' instead of the parameter you want to skip. More details here https://stackoverflow.com/questions/8356227/skipping-optional-function-parameters-in-javascript . Also a good practice is to group your parameters in an object and pass just one parameter as an object. In this case you don't need to worry about the order of parameters passed
2 of 7
3
Technically, in JavaScript, all arguments are optional. However, if a function defines argument names, either every argument must be supplied or the first n parameters passed in the call will be assigned to the first n labels in the definition. So function test(a,b,c) { } May be called like so test(); // a, b and c are undefined test(1,2) // a = 1, b = 2, c = undefined test(1,2,3) // a = 1, b = 2, c = 3 There are also default values for arguments and the spread operator, but you get the gist. The implication is that if the function defines argument names, you must supply the parameters in the correct position (and, no, you cannot just put a comma to indicate an empty value - use undefined or null). Now, there is another way of defining functions which is to do this function test(){ let a = arguments[0]; let b = arguments[1]; } That is, every function has a special variable names arguments that allows for extracting args on a positional basis. This can be used to simulate "overloads" (by relying on the type of each positional argument, for instance). It's the sort of thing that allows jQuery to accept the URL as the first argument or inside the options argument. So, short answer after a long preamble - you really have to play nicely with the way the function is defined... RTFM!
🌐
Flexiple
flexiple.com › javascript › optional-parameter-javascript
How to declare optional function parameters in javascript - Flexiple
March 10, 2022 - There are several methods to achieve this. One common approach is to assign a default value to the parameter. This ensures that if the parameter is not provided, the function will still execute using the default value.
🌐
React Native
reactnative.dev › docs › intro-react
React Fundamentals · React Native
3 days ago - React and React Native use JSX, a syntax that lets you write elements inside JavaScript like so: <Text>Hello, I am your cat!</Text>. The React docs have a comprehensive guide to JSX you can refer to learn even more. Because JSX is JavaScript, you can use variables inside it.
🌐
Supabase
supabase.com › docs › reference › javascript › select
JavaScript API Reference | Supabase Docs
1 day ago - When using in a browser, this function is synchronized across all tabs using the LockManager API. In other environments make sure you've defined a proper lock property, if necessary, to make sure there are no race conditions while the session is being refreshed. ... Returns a new session, regardless of expiry status. Takes in an optional current session.
🌐
TypeScript Tutorial
typescripttutorial.net › home › typescript tutorial › typescript optional parameters
TypeScript Optional Parameters
July 11, 2024 - Summary: in this tutorial, you will learn how to use the TypeScript optional parameters for functions. In JavaScript, you can call a function without passing any arguments even though the function specifies parameters.
🌐
Medium
bagusbudicahyono.medium.com › a-better-approach-to-organize-optional-function-parameter-in-javascript-6c8fc516d593
A Better Approach to Organize Optional Function Parameter in Javascript | by Bagus Budi Cahyono | Medium
July 20, 2021 - Are these really optional parameters? Why do I still have to give a value for sugarLevel and topping? This is just a sample case to show you the problem you might face if you write code similar to the sample. Let’s solve the problem. In order to solve the problem, we can follow these rules: If the function only has 1 optional parameter, put it in the very last after all required parameters
🌐
MSR
rajamsr.com › home › the ultimate guide to javascript optional parameters
The Ultimate Guide To JavaScript Optional Parameters | MSR - Web Dev Simplified
February 11, 2024 - They let you write functions that can adapt to different situations and needs. They make your code more concise and flexible. But they also have some rules and pitfalls that you need to know. Otherwise, you may end up with errors, bugs, or surprises in your code. ... How to use objects as optional parameters in JavaScript to group related values and avoid order dependency
🌐
Angular
angular.dev › guide › components › inputs
Accepting data with input properties • Angular
You can explicitly declare a type for the input by specifying a generic parameter to the function.
🌐
Sequelize
sequelize.org › getting started
Getting Started | Sequelize
The options.logging option can be used to customize this behavior, by defining the function that gets executed every time Sequelize logs something. The default value is console.log and when using that only the first log parameter of a log function call is displayed.
🌐
Mozilla
developer.mozilla.org › en-US › docs › Web › JavaScript › Guide › Data_structures
JavaScript data types and data structures - JavaScript | MDN
For example, the Number object provides methods like toExponential(). When a property is accessed on a primitive value, JavaScript automatically wraps the value into the corresponding wrapper object and accesses the property on the object instead. However, accessing a property on null or undefined throws a TypeError exception, which necessitates the introduction of the optional chaining operator.
🌐
Stackify
stackify.com › display-php-errors
How to Display All PHP Errors: A Detailed Guide - Stackify
September 1, 2024 - On the JavaScript side, you can check for these errors and handle them appropriately. To avoid changing parameters in the .htaccess or adding some lines in the PHP code to show errors, then the best way to log errors is defining it in the web server configuration file.
🌐
scikit-learn
scikit-learn.org › stable › modules › generated › sklearn.preprocessing.StandardScaler.html
StandardScaler — scikit-learn 1.8.0 documentation
Added in version 0.24: parameter sample_weight support to StandardScaler. ... Fitted scaler. ... Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
🌐
TypeScript
typescriptlang.org › docs › handbook › 2 › functions.html
TypeScript: Documentation - More on Functions
What people usually intend when writing index? as an optional parameter is that they want both of these calls to be legal: ... What this actually means is that callback might get invoked with one argument. In other words, the function definition says that the implementation might look like this: ... In JavaScript, if you call a function with more arguments than there are parameters, the extra arguments are simply ignored.
🌐
Mimo
mimo.org › glossary › typescript › optional-parameter
TypeScript Optional Parameter: Syntax, Usage, and Examples
Add type safety to JavaScript. Learn types, interfaces, generics, and TypeScript best practices ... This marks the parameter as optional. If it's not provided, its value inside the function will be undefined.