JavaScript Interview Question #22

What are default parameters in JavaScript?

JavaScript Fundamentals, Types, Scope & Functions Junior Beginner

Quick Interview Answer

Default parameters allow a function parameter to receive a predefined value when the corresponding argument is omitted or explicitly passed as undefined.

Detailed Explanation

Default parameters allow a function parameter to receive a predefined value when the corresponding argument is omitted or explicitly passed as undefined.

Defaults are evaluated when the function is called. Passing null does not activate a default because null is an explicit value. Default parameters reduce manual checks and make function contracts easier to read.

Code Example

function greet(name = "Guest") {
    return `Hello, ${name}`;
}

console.log(greet());          // Hello, Guest
console.log(greet(undefined)); // Hello, Guest
console.log(greet("Asif"));    // Hello, Asif
console.log(greet(null));      // Hello, null