Default parameters in Javascript | Lecture 6

 

In JavaScript, default parameters allow you to initialize function parameters with default values if no value or undefined is passed. This feature simplifies function definitions and eliminates the need for additional checks or fallback logic inside the function body.


Syntax

function functionName(param1 = defaultValue1, param2 = defaultValue2) {

  // Function body

}


Examples

1. Basic Default Parameters

function greet(name = "Guest") {

  console.log(`Hello, ${name}!`);

}

 

greet("Alice"); // Output: "Hello, Alice!"

greet();        // Output: "Hello, Guest!"


2. Using Expressions as Default Values

function calculateArea(length = 1, width = length * 2) {

  return length * width;

}

 

console.log(calculateArea(5));    // Output: 50 (5 * 10)

console.log(calculateArea());     // Output: 2 (1 * 2)


3. Default Parameters and undefined

If undefined is passed explicitly, the default value is used:

function sayHello(name = "World") {

  console.log(`Hello, ${name}!`);

}

 

sayHello(undefined); // Output: "Hello, World!"

sayHello(null);      // Output: "Hello, null!" (null overrides the default)


4. Functions as Default Values

You can use a function to compute the default value dynamically:

function getDefaultName() {

  return "Anonymous";

}

 

function welcome(user = getDefaultName()) {

  console.log(`Welcome, ${user}!`);

}

 

welcome("John"); // Output: "Welcome, John!"

welcome();       // Output: "Welcome, Anonymous!"


5. Default Parameters with Destructuring

Default parameters can work with object and array destructuring:

// Object Destructuring

function displayUser({ name = "User", age = 18 } = {}) {

  console.log(`Name: ${name}, Age: ${age}`);

}

 

displayUser({ name: "Alice", age: 25 }); // Output: "Name: Alice, Age: 25"

displayUser();                           // Output: "Name: User, Age: 18"

 

// Array Destructuring

function sum([a = 0, b = 0] = []) {

  return a + b;

}

 

console.log(sum([5, 10])); // Output: 15

console.log(sum());        // Output: 0


Notes

  • Default parameters are evaluated at call time, not at function definition time. This means the default value can depend on previous parameters:

function multiply(a, b = a * 2) {

  return a * b;

}

 

console.log(multiply(3)); // Output: 18 (3 * (3 * 2))

  • You cannot skip arguments when calling a function with default parameters; instead, explicitly pass undefined to use a default value:

function greet(first = "Hello", second = "World") {

  console.log(`${first}, ${second}!`);

}

 

greet("Hi", undefined); // Output: "Hi, World!"


Default parameters enhance function flexibility and improve code readability by reducing the need for manual checks and fallback logic.

 

Comments

Popular posts from this blog

Classes and Objects in Javascript | Lecture 10

Destructuring in JavaScript | Lecture 5

ECMA Script 6 Introduction of topics | Lecture 1