[JavaScript] Understanding Default Parameter - Explained with Examples.

default parameter, JavaScript, function, input validation


Introduction

This article introduces a default parameter.

The default parameter basically prevents a situation where users enter nothing in the parameter when they are supposed to.


Default Parameter

Syntax:

function myFunction(parameter1 = value) {
    console.log(value);
}

myFUnction(); // value

Example:

let defaultUserName = "strongjohn";
function myFunction(userName = defaultUserName) {
    console.log("Hello,", userName);
}

myFunction(); // Hello, strongjohn
myFunction("strawberry lover"); // Hello, strawberry lover

Do you notice that defaultUserName variable is printed even though the function received no parameter?

You can make your program better if you can use the default parameter correctly.