This page looks best with JavaScript enabled

Default Function Arguments in Javascript

 ·   ·  ☕ 1 min read

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

Consider this function -

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

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

1
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.

1
2
3
4
5
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.

1
2
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.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things