Default Function Arguments in Javascript

You can easily introduce default values for the arguments passed to a function.

Consider this function -

function sayHello(name) {
  return `hello ${name}`;
}

Calling this function without arguments will provide a not-so-pretty string.

console.log(sayHello()); // hello undefined

Even if someone had an existential crisis, I doubt they will like to be called ‘undefined’. So - let us change that.

function sayHello(name) {
  name = name || "world";

  return `hello ${name}`;
}

The ‘or’ statement will -

  • retain name value if provided
  • assign ‘world’ to name if name is falsy

The results are more pleasing.

console.log(sayHello()); // hello world
console.log(sayHello("Neo")); // hello Neo

You can also use a ternary operator or a full-fledged if statement, but the above code looks more to the point but at the same time readable.

comments powered by Disqus