Why default.parameters ?
The default parameters of the JavaScript functions are undefined. If we do not enter a parameter, it is equal to “undefined“. As you can see in the previous lessons, javascript functions can take many identical or different parameters. If we do not enter these parameters, the “undefined” value returns as I said above.
For example; We have a 2-parameter function. In this function, the first parameter is x, the second parameter name is y. Let’s define this function as follows.
let sum = function (x , y) {
return x + y
}
If we call this function as follows, we have no problems:
console.log(sum(3, 6)); // 9
If we don’t even enter a parameter. We encounter this problem:
console.log(sum( 6)); // NaN
We can solve this problem as follows:
function sum(x, y) {
if (y === undefined) {
y = 0;
}
return x + y;
}
console.log( sum(3) )
output:
3
or;
function sum(x, y=2) {
return x + y;
}
console.log( sum(3) )
output:
5
JavaScript Default Parameters
Example 1
function myFunction(example = "example"){
console.log(typeof example);
}
myFunction();
myFunction(undefined);
myFunction("");
myFunction(null);
output:
string
string
string
object
Example 2
function arrayFunction(arr, list=[]){
list.push(arr);
return list;
}
console.log(arrayFunction(5))
console.log(arrayFunction(3))
output:
[5]
[3]
Browser Support
| Chrome | 49 |
| Edge | 15 |
| Firefox | 14 |
| Internet Explorer | no |
| Opera | 36 |
| Safari | 10 |
| Android webview | 49 |
| Chrome for Android | 49 |
| Edge mobile | 14 |
| Firefox for Android | 15 |
| Opera Android | 36 |
Leave a comment