Show List

Default Function Parameters

Default function parameters allow you to initialize function parameters with default values if no value or undefined is passed for that parameter. This feature was introduced in ES6 (ECMAScript 2015). Here's how it works:


// Example without default parameters function multiply(x, y) { return x * y; } console.log(multiply(3, 4)); // Output: 12 console.log(multiply(3)); // Output: NaN (Not a Number) because y is undefined

In the example above, if you don't pass a value for y, it becomes undefined, and the function returns NaN because you're trying to multiply a number with undefined.

Now, let's see how default parameters can help:


// Example with default parameters function multiply(x, y = 1) { return x * y; } console.log(multiply(3, 4)); // Output: 12 console.log(multiply(3)); // Output: 3 (because y defaults to 1 when not provided)

In this updated example, the y parameter has a default value of 1. So if you don't pass a value for y, it automatically takes the default value of 1, ensuring the function won't return NaN.

You can also have default parameters based on the value of other parameters:


// Example with default parameters based on other parameters function greet(name, greeting = "Hello") { return `${greeting}, ${name}!`; } console.log(greet("John")); // Output: Hello, John! console.log(greet("Jane", "Good morning")); // Output: Good morning, Jane!

In this example, if you don't provide a value for greeting, it defaults to "Hello". Otherwise, you can specify a different greeting when calling the function.

Default parameters provide a convenient way to handle cases where certain function parameters might commonly take the same value or when you want to ensure a default behavior if a parameter is not provided.


    Leave a Comment


  • captcha text