JavaScript
Template Literals and Default Parameters



Understanding Template Literals

Template literals are a new way to work with strings in JavaScript, introduced in ES6. They allow for easier string interpolation and multiline strings without the need for concatenation or escape characters.

Template literals use backticks (``) instead of quotes, and variables can be embedded using ${expression}.

Example 1: Simple Interpolation


    const name = "Alice";
    const greeting = `Hello, ${name}!`;
    console.log(greeting);
    

Output:

    Hello, Alice!
    

Why not use regular strings?

In older JavaScript versions, you'd write:


    const greeting = "Hello, " + name + "!";
    

This can become messy with more variables. Template literals simplify this.

Example 2: Multiline Strings


    const poem = `
    Roses are red,
    Violets are blue,
    JavaScript is fun,
    And so are you!
    `;
    console.log(poem);
    

Output:

    Roses are red,
    Violets are blue,
    JavaScript is fun,
    And so are you!
    

Question:

Can we use expressions inside template literals?

Yes! You can evaluate any expression inside ${}.

Example 3: Using Expressions


    const a = 5;
    const b = 10;
    const result = `${a} + ${b} = ${a + b}`;
    console.log(result);
    

Output:

    5 + 10 = 15
    

Understanding Default Parameters

Default parameters allow you to initialize function parameters with default values if no value or undefined is passed.

Example 4: Default Parameters in Action


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

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

Output:

    Hello, Bob!
    Hello, Guest!
    

Question:

What happens if we pass undefined?

The default value is used only if the argument is undefined or not provided.

Example 5: Skipping a Parameter


    function multiply(x, y = 2) {
      return x * y;
    }

    console.log(multiply(5));        // y takes default value 2
    console.log(multiply(5, 3));     // y = 3 overrides default
    console.log(multiply(5, undefined)); // y takes default value
    

Output:

    10
    15
    10
    

Tip:

You can also use expressions or function calls as default values!

Example 6: Dynamic Defaults


    function getDefaultAge() {
      return 18;
    }

    function createUser(name = "Anonymous", age = getDefaultAge()) {
      return `${name} is ${age} years old.`;
    }

    console.log(createUser("John", 25));
    console.log(createUser());
    

Output:

    John is 25 years old.
    Anonymous is 18 years old.
    

Summary



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M