Wednesday, August 13, 2025

Javascript Module 50

  Module 50 : Template Literals and Enhanced Object Literals. 

Section 1: Template Literals in JavaScript

✅ What are Template Literals?

Template literals are string literals enclosed by backticks ( ) instead of quotes.



               

They provide:

String interpolation

Multiline strings

Expression embedding

Tagged templates (advanced)


 Syntax:

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


 Features of Template Literals

Feature

Description

String Interpolation

Insert variables/expressions directly in strings

Multiline Strings

Write strings across multiple lines without \n

Expression Evaluation

Embed any valid expression inside ${}

Nesting Literals

Combine template literals within template literals



Example 1: Interpolation and Multiline

const name = "Reh"; const age = 25; const greeting = `Hello, my name is ${name}. I am ${age} years old.`; console.log(greeting);

 Explanation:

${name} and ${age} are dynamically evaluated

No need for concatenation (+)


1: Dynamic HTML Template

Create a function that generates HTML dynamically using template literals.

function createCard(name, age, city) { return ` <div class="card"> <h2>${name}</h2> <p>Age: ${age}</p> <p>City: ${city}</p> </div> `; } console.log(createCard("Rehana", 25, "Mumbai"));

Explanation:

Useful for creating HTML in frontend frameworks like React, Vue

Reduces the need for long string concatenation

Keeps HTML readable and dynamic


 Section 2 : Enhanced Object Literals

✅ What are Enhanced Object Literals?

Enhanced object literals in ES6+ allow for:

               


Property shorthand

Method shorthand

Computed property names


🧠 Syntax and Features:

1. Property Shorthand

const name = "Reh"; const age = 25; const person = { name, age }; // Instead of name: name, age: age console.log(person);

2. Method Shorthand

const person = { greet() { console.log("Hello!"); } }; person.greet();

 3. Computed Property Names

const key = "city"; const value = "Delhi"; const location = { [key]: value }; console.log(location); // { city: 'Delhi' }


Example 2: Dynamic Object with Computed Key

function createUser(name, email, dynamicKey, dynamicValue) { return { name, email, [dynamicKey]: dynamicValue, info() { return `${name} can be contacted at ${email}`; } }; } const user = createUser("Reh", "reh@email.com", "role", "admin"); console.log(user); console.log(user.info());


  Exercises 

Exercise 1: Convert concatenated strings to template literals

Input Code:

let user = "Reh"; let msg = "Hello " + user + "! Welcome to JavaScript.";

✅ Convert it using template literals:

let user = "Reh"; let msg = `Hello ${user}! Welcome to JavaScript.`;

✅ Why is this better?

Clean and readable

Easy to maintain and scale


 Exercise 2: Use property and method shorthand

                










Given:

let name = "Ali"; let age = 30; let user = { name: name, age: age, greet: function () { return "Hi!"; } };

✅ Convert it:

let user = { name, age, greet() { return "Hi!"; } };


Build a User Profile Generator

Use template literals and enhanced object literals to build a user profile card system.

function createProfile(name, age, email, key, value) { return { name, age, email, [key]: value, summary() { return ` Name: ${this.name} Age: ${this.age} Email: ${this.email} ${key}: ${this[key]} `; } }; } const profile = createProfile("Reh", 25, "reh@example.com", "role", "Developer"); console.log(profile.summary());

🔍 Result Output:

Name: Reh

Age: 20

Email: rehana@example.com

role: Developer


Research Insights

 JavaScript Engine Optimizations

                  

Template literals are optimized in modern JavaScript engines (V8, SpiderMonkey) for performance.

Object literal enhancements reduce boilerplate, which minimizes bugs and improves maintainability.

  Best Use

Use template literals for any dynamic string construction

Use object shorthand to improve readability and reduce redundancy

Use computed property names when dynamic key assignment is required


   Summary

Concept

Benefits

Template Literals

Clean syntax, multiline support, dynamic string creation

Enhanced Object Literals

Cleaner object creation, dynamic property keys, method shorthand



 Build a Dynamic Blog Post Object

Create a function createBlogPost(title, author, content, dateFieldName, dateValue) that:

               










Uses template literals for summary

Uses enhanced object literal features

Returns an object with a method getSummary()

 Example:

function createBlogPost(title, author, content, dateFieldName, dateValue) { return { title, author, content, [dateFieldName]: dateValue, getSummary() { return `Blog: ${this.title} by ${this.author}\nPublished on: ${this[dateFieldName]}`; } }; } const post = createBlogPost("Modern JS", "Reh", "Deep dive into JS", "publishedDate", "2025-07-25"); console.log(post.getSummary());



No comments:

Post a Comment

Javascript Module 52

  Javascript   Module 52 If You want To Earn Certificate For My  All   Course Then Contact Me At My  Contact  Page   then I Will Take A Test...