Sunday, August 17, 2025

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 And  Give You  certificate  . Go My Contant Page And Fill Your Details Then I Will Contact You Click Here And Go To My Contact Page 

https://onlinecourses2024for.blogspot.com/p/contact-us.html/

Javascript Module 52

  Module 52 : Iterators and Generators

  

1.Introduction

What is an Iterator?

An iterator is an object that allows you to traverse through a collection (like arrays, strings, etc.) one item at a time. It follows the iterator protocol, which requires:

                










A next() method

That returns an object: { value: any, done: boolean }

const myIterator = { next: function() { return { value: ..., done: false }; // Until done is true } };


What is Iterable?

An iterable is any object that has a method Symbol.iterator which returns an iterator.

Built-in iterables: Arrays, Strings, Maps, Sets


2. Creating a Custom Iterator

Let’s build a simple iterator that counts from 1 to 5:

function createCounter(limit) { let count = 1; return { next: function() { if (count <= limit) { return { value: count++, done: false }; } else { return { done: true }; } } }; } const counter = createCounter(5); console.log(counter.next()); // { value: 1, done: false } console.log(counter.next()); // { value: 2, done: false } console.log(counter.next()); // { value: 3, done: false }


 3. Making an Object Iterable

const range = { start: 1, end: 5, [Symbol.iterator]() { let current = this.start; let end = this.end; return { next() { if (current <= end) { return { value: current++, done: false }; } else { return { done: true }; } } }; } }; for (let num of range) { console.log(num); // 1 2 3 4 5 }

}

Explanation:

We defined [Symbol.iterator]() method

It returns an object with next() function

The for...of loop uses that protocol behind the scenes


4. Generators – Simplifying Iterators

📖 Definition:

Generators are special functions defined with function* and use the yield keyword to produce a sequence of values on demand.

             










function* simpleGenerator() { yield 1; yield 2; yield 3; } const gen = simpleGenerator(); console.log(gen.next()); // { value: 1, done: false } console.log(gen.next()); // { value: 2, done: false }


Advantages of Generators

Feature

Benefit

yield

Pause and resume execution

Lazy Evaluation

Save memory, load values only when needed

Clean Syntax

Avoid boilerplate in iterator construction



 5. Generator Example: Fibonacci Sequence

function* fibonacci(limit) { let a = 0, b = 1; let count = 0; while (count < limit) { yield a; [a, b] = [b, a + b]; count++; } } for (let num of fibonacci(7)) { console.log(num); // 0 1 1 2 3 5 8 }


6. Use Cases

Use Case

Explanation

Pagination

Load results page by page using generators

Stream Reading

Lazy read large files using generators

Game States

Generators for state-based game logic

Infinite Scroll

Use iterators to stream content on demand



7. Exercises 

🔹 Exercise 1: Custom Iterable Object

                  










Create an object that iterates over even numbers from 2 to 10.

const evens = { [Symbol.iterator]() { let num = 2; return { next() { if (num <= 10) { return { value: num++, done: false }; } else { return { done: true }; } } }; } }; for (let val of evens) { if (val % 2 === 0) console.log(val); // 2 4 6 8 10 }


🔹 Exercise 2: Generator to Yield Square Numbers

function* squareGenerator(n) { for (let i = 1; i <= n; i++) { yield i * i; } } for (let square of squareGenerator(5)) { console.log(square); // 1 4 9 16 25 }


🔹 Exercise 3: Infinite Generator

function* infiniteCounter() { let count = 1; while (true) { yield count++; } } const counter = infiniteCounter(); console.log(counter.next().value); // 1 console.log(counter.next().value); // 2


8. Deep Dive 

 Under the Hood

When you use a for...of loop:

               










for (let value of iterable) {}

JavaScript does:

let iterator = iterable[Symbol.iterator](); let result = iterator.next(); while (!result.done) { let value = result.value; result = iterator.next(); }


 9. Research 

From ES6 Specification:

Introduced the Symbol.iterator to formalize custom iteration

Generators based on coroutines pattern (inspired from Python, Lua)

Industry Usage:

Company

Use Case

Netflix

Streams video content chunk by chunk using generators

React

Uses iterables in virtual DOM diffing logic

Node.js

Uses generators in libraries like co for async flow before async/await



10. Summary 

Iterators define how to traverse a data structure

The Symbol.iterator protocol makes any object iterable

                


Generators simplify writing iterators using yield

They allow lazy execution and are powerful for sequences

Ideal for streaming, pagination, state machines


11. Work

Create a generator that yields a multiplication table of a given number up to 10.

Make a custom iterable for a deck of cards.

Write a generator to simulate turns in a two-player game (alternate yields).


Friday, August 15, 2025

Javascript Module 51

 


Javascript  Module 51

If You want To Earn Certificate For My  All   Course Then Contact Me At My  Contact  Page   then I Will Take A Test And  Give You  certificate  . Go My Contant Page And Fill Your Details Then I Will Contact You Click Here And Go To My Contact Page 

https://onlinecourses2024for.blogspot.com/p/contact-us.html/

Javascript Module 51

  Module 51 : Optional Chaining & Nullish Coalescing

1. Introduction to Optional Chaining (?.)

✅ What is Optional Chaining?

Optional Chaining (?.) is a safe way to access nested object properties without worrying if the intermediate properties exist.


















               

 Problem It Solves:

Traditionally, accessing a  nested property required multiple checks:

let user = {}; let city = user && user.address && user.address.city; // undefined

If any intermediate property (user.address) is undefined, it throws an error:

let city = user.address.city; // ❌ TypeError: Cannot read properties of undefined

✅ Solution with Optional Chaining:

let city = user?.address?.city; // ✅ Safely returns undefined instead of throwing an error

✅ Syntax:

object?.property object?.[expression] array?.[index] function?.()


2. Optional Chaining

 Example 1: Accessing Nested Properties

const person = { name: 'John', address: { city: 'New York', }, }; console.log(person?.address?.city); // New York console.log(person?.job?.title); // undefined (no error)

 Example 2: Optional Chaining with Arrays

const users = [{ name: 'Alice' }, null, { name: 'Bob' }]; console.log(users[1]?.name); // undefined (no error) console.log(users[2]?.name); // Bob

Example 3: Optional Chaining with Functions

const user = { greet: () => 'Hello!', }; console.log(user.greet?.()); // Hello! console.log(user.nonExistent?.()); // undefined (no error)


 3. Introduction to Nullish Coalescing (??)

✅ What is Nullish Coalescing?

It provides a default value if the left-hand side is null or undefined.

               










 Difference from Logical OR (||)


|| treats falsy values like 0, "", or false as false. ?? only checks for null or undefined.

✅ Syntax:

let value = possiblyNullOrUndefined ?? defaultValue;

 Example:

let userInput = ""; let name = userInput || "Guest"; // "Guest" (because "" is falsy) let name2 = userInput ?? "Guest"; // "" (because it's not null/undefined) console.log(name); // Guest console.log(name2); // ""


4. Use Cases

 Example 1: Default Values in Settings

const settings = { theme: null, fontSize: 0, }; let theme = settings.theme ?? "light"; // "light" let fontSize = settings.fontSize ?? 14; // 0 (not replaced by 14) console.log(theme, fontSize); // light 0

 Example 2: Safe Access with Defaults

const config = { database: { retryCount: undefined, }, }; const retry = config?.database?.retryCount ?? 3; console.log(retry); // 3


 5. Exercises

✅ Exercise 1: Safe Property Access

const car = { model: 'Tesla', engine: { type: 'Electric', }, }; console.log(car?.engine?.type); // Electric console.log(car?.wheels?.count); // undefined

✅ Exercise 2: Using Nullish Coalescing

let speed = undefined; let defaultSpeed = speed ?? 60; console.log(defaultSpeed); // 60

✅ Exercise 3: Combine Both

const user = { profile: { avatar: null, }, }; const avatar = user?.profile?.avatar ?? "default.png"; console.log(avatar); // default.png


 6. Research  

  ECMAScript 2020

Both ?. and ?? were introduced in ECMAScript 2020 to reduce code complexity and improve safety when accessing potentially missing or undefined values.











                 

✅ Why Optional Chaining is Better than :

Less verbose: Reduces the need for if statements.

More readable: Easier to follow logic.

Safer: Prevents runtime crashes from accessing undefined properties.

✅ Why Nullish Coalescing is Better than ||:

|| can misinterpret falsy values (like 0, "").

?? accurately checks for absence (null/undefined) and respects valid falsy values.


  7. Tips

nested properties can crash code.

Ask output with || vs. ??.

     Visual Demos:

Use browser console or online JS playgrounds like JSFiddle, CodeSandbox.

     Discussion

 if a property doesn't exist.

 the difference between undefined and null.

 would || give unexpected results.


8. Quiz & Assignments

✅  Quiz:

What does obj?.prop do if obj is null?

What’s the output of false ?? "default"?

Difference between || and ???

✅ Mini Assignment:

    Given the following object.

Access the email safely.

Set a default profile picture if avatar is missing.

const user = { profile: { name: 'Reh', avatar: null, }, }; const email = user?.profile?.email ?? 'No email'; const avatar = user?.profile?.avatar ?? 'default.jpg'; console.log(email, avatar); // No email default.jpg


   Summary

                


Feature

Optional Chaining (?.)

Nullish Coalescing (??)

Purpose

Safe access to properties/methods

Provide default values

Handles

undefined, null

Only undefined, null

Example

obj?.prop

value ?? default



Combine Both

               










let user = { profile: null, }; let profileName = user?.profile?.name ?? "Guest"; console.log(profileName); // Guest


  References

 Optional Chaining

 Nullish Coalescing

ECMAScript 2020 Language Specification


Wednesday, August 13, 2025

Javascript Module 50

 


Javascript  Module 50

If You want To Earn Certificate For My  All   Course Then Contact Me At My  Contact  Page   then I Will Take A Test And  Give You  certificate  . Go My Contant Page And Fill Your Details Then I Will Contact You Click Here And Go To My Contact Page 

https://onlinecourses2024for.blogspot.com/p/contact-us.html/

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());



Monday, August 11, 2025

Javascript Module 49


 Javascript  Module 49

If You want To Earn Certificate For My  All   Course Then Contact Me At My  Contact  Page   then I Will Take A Test And  Give You  certificate  . Go My Contant Page And Fill Your Details Then I Will Contact You Click Here And Go To My Contact Page 

https://onlinecourses2024for.blogspot.com/p/contact-us.html/

Javascript Module 49

   Module 49 : Default Parameters. 

What Are Default Parameters?

In JavaScript, default parameters allow you to set default values for function parameters if no value is provided or if the value is undefined.

               










 Why Use Default Parameters?

Makes your code cleaner and more robust

Prevents undefined values in function logic

Eliminates the need for manual checks like if (param === undefined)


 Syntax and Explanation

function greet(name = "Guest") { console.log("Hello, " + name + "!"); } greet(); // Output: Hello, Guest! greet("Rehana"); // Output: Hello, Rehana!

🔍 Explanation:

name = "Guest" sets a default value.

If greet() is called without an argument, name becomes "Guest".


Internal

Mechanism & Behavior

JavaScript checks function parameters in this order:

Was an argument passed?

Is it explicitly undefined?

If yes to either, use default value.

function test(a = 1) { console.log(a); } test(undefined); // Uses default → 1 test(null); // null is a value → prints null

Key Point:

undefined triggers default value, but null, 0, false, or "" do NOT.


Examples

✅ Example 1: API Request Defaults

                 










function fetchData(url, method = "GET") { console.log(`Fetching ${url} using ${method}`); } fetchData("https://api.example.com"); // method defaults to "GET"

✅ Example 2: Mathematical Operation with Defaults

function multiply(a, b = 1) { return a * b; } console.log(multiply(5)); // 5 (uses b = 1) console.log(multiply(5, 2)); // 10


 Exercises 

 Exercise 1:

Create a function createUser(name, role = "User") that logs a welcome message.

function createUser(name, role = "User") { console.log(`Welcome ${name}! Your role is ${role}.`); } createUser("Ali"); // Welcome Ali! Your role is User. createUser("Sara", "Admin"); // Welcome Sara! Your role is Admin.

💡 Exercise 2:

Fix the code:

function calculateTotal(price, tax) { tax = tax || 0.1; return price + price * tax; }

🔧 Update using default parameters:

function calculateTotal(price, tax = 0.1) { return price + price * tax; }

Why better?

Because || will override tax = 0 as false and change behavior.


Compare Old vs Modern Approach

 Objective:

Show difference between manual default handling and ES6 default parameters.

 Step 1: Old Manual Defaults

function legacyGreet(name) { name = typeof name !== "undefined" ? name : "Guest"; console.log("Hi, " + name); }

Step 2: Modern Default Parameters

function modernGreet(name = "Guest") { console.log("Hi, " + name); }


 

 

Code length


Readability

Edge cases like undefined, null, or ""


 Research 

 Research Insight 1: Evaluation Order

                 










let counter = 0; function log(a = counter += 1) { console.log(a); } log(); // 1 log(); // 2

Default parameters are evaluated at call time, not function definition time.


Research Insight 2: Default with Destructuring

function showProfile({name = "Anonymous", age = 0} = {}) { console.log(`${name} is ${age} years old.`); } showProfile(); // Anonymous is 0 years old. showProfile({name: "Zara"}); // Zara is 0 years old.


  Common Mistakes to Avoid


Mistake

Fix

Relying on `



Using default parameters before required ones

Always place default params at the end

Expecting default to apply for null, 0, or false

Only undefined triggers default

Write a function registerUser(email, password = "123456", isAdmin = false) and test the following cases:

               












registerUser("user@example.com"); registerUser("admin@example.com", "securepass", true); registerUser("guest@example.com", "", true);

Expected Results:

Default values must apply only when not passed or undefined, not when passed as "" or false.


📘 Summary

Feature

Description

Introduced in

ES6

Triggered when

Argument is undefined

Not triggered when

Argument is null, false, "", 0

Benefits

Cleaner code, safer defaults, better readability



   Checklist

             










✅ Understood default parameter syntax

✅ Applied in use cases

✅ Compared old vs modern approach

✅ Completed challenge


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...