Default parameters

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

Chrome49
Edge15
Firefox14
Internet Explorerno
Opera36
Safari10
Android webview49
Chrome for Android49
Edge mobile14
Firefox for Android15
Opera Android36

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Create a website or blog at WordPress.com

Up ↑

Design a site like this with WordPress.com
Get started