DEV Community

Cover image for JavaScript Default Function Parameters.
Syed Mohsin Raza
Syed Mohsin Raza

Posted on • Edited on

JavaScript Default Function Parameters.

In JavaScript when we call a function which expects some data to be passed in if you call that without passing in that data JavaScript will use undefined.

Let's understand this practically ⚙️

What the following function does is that it takes a name as an input and console logs it.

function printName(name) {
  console.log(name);
}
Enter fullscreen mode Exit fullscreen mode

Now if we call the printName function by passing in a name as shown below:

printName("frontendenthusiast");  
Enter fullscreen mode Exit fullscreen mode

We'll get the following output.

frontendenthusiast
Enter fullscreen mode Exit fullscreen mode

Now lets call the same function without passing anything in

printName();  
Enter fullscreen mode Exit fullscreen mode

We will get undefined as the output in the console.

undefined
Enter fullscreen mode Exit fullscreen mode

undefined isn't that useful in most situations what if we can use a fallback if no name is passed into the function. Well for that we can use the || operator in JavaScript as shown below:

function printName(name) {
  name = name || `Anonymous`;
  console.log(name);
}
Enter fullscreen mode Exit fullscreen mode

The Logical OR (||) operator returns the very first truthy value and undefined is a falsy value so in the printName function it will return Anonymous which is a truthy value.

Now with the above addition of || operator if we call the function by passing in no value as shown:

printName();

Enter fullscreen mode Exit fullscreen mode

We will get Anonymous as the output.

Anonymous

Enter fullscreen mode Exit fullscreen mode

In ES6 we have a more compact way of doing the above which is to set up default parameters directly using the assignment operator = as shown:

function printName(name = `Anonymous`) {
  console.log(name);
}
Enter fullscreen mode Exit fullscreen mode

this returns default value we set using = operator in case no value was passed in.

function printName(name = `frontendenthusiast`) {
  console.log(name);
}

printName(undefined);
Enter fullscreen mode Exit fullscreen mode

The output of the above function will be frontendenthusiast

Happy coding! 🥰

Top comments (1)

Collapse
 
emptyother profile image
emptyother

Note that when passing the value null, it is not replaced with a default value. I've stopped using null entirely but some libraries return it instead of undefined.