JS CodeLab
functionsbeginner

JavaScript Default Parameters: ES6 Syntax Guide

•
Updated

Direct Answer & Overview

JavaScript default parameters allow formal function parameters to be initialized with default values if no value or undefined is passed during invocation, preventing unexpected errors from missing arguments without defensive boilerplate.

#default-parameters#es6#functions#arguments

JavaScript Source Code

example.js
function greet(name = "World") {
  return `Hello, ${name}!`;
}

console.log(greet());
console.log(greet("Suresh"));

How does this JavaScript code work?

Prior to ES6, developers had to write manual defensive checks like `name = name || 'World'` inside function bodies, which erroneously overwrote legitimate falsy values such as `0` or `""`. ECMAScript 2015 default parameters (`function greet(name = 'World')`) evaluate fallback values strictly when the passed argument is either omitted or explicitly `undefined`. Default parameter expressions are evaluated at run time, meaning subsequent parameters can even reference preceding ones.

What is the expected terminal output?

Executing this code in JS CodeLab produces the following stdout sequence in the developer console:

Console Standard Output
Hello, World!
Hello, Suresh!

Common mistakes to avoid

  • !Placing default parameters before required parameters, forcing callers to pass undefined explicitly to access subsequent positional arguments.
  • !Assuming passing null triggers a default parameter; null is a deliberate value and will NOT trigger the default fallback (only undefined does).
  • !Referencing subsequent parameters within an earlier default parameter expression, causing a ReferenceError due to the Temporal Dead Zone.
  • !Mutating default object or array arguments in a way that creates unexpected state leakage across invocations.

Frequently Asked Questions

Does passing null trigger a default parameter in JavaScript?

No. Only undefined (or omitting the argument completely) triggers default parameter initialization. Passing null explicitly passes the null value.

Can default parameters be dynamic expressions or function calls?

Yes. Default parameter values are evaluated at call time, allowing you to use math expressions, variables from the outer scope, or helper function calls as defaults.

Can an earlier parameter be used in a later default parameter definition?

Yes. Later parameters have access to earlier parameters (e.g., function rect(width, height = width * 2)), but earlier parameters cannot access later ones.

How do default parameters affect the function.length property?

The function.length property only counts parameters declared before the first parameter with a default value, ignoring parameters that have default initializers.

Comprehensive Tutorial

Want an in-depth understanding of this topic?

Read our complete, interactive tutorial covering memory management, edge cases, and best practices.

Read the full functions tutorial →