Module 1
Module 1
Fundamentals-II
JavaScript Concepts
• Better Variable Handling: Replacing the unpredictable var with let and const.
• Enhanced Features: Introduction of arrow functions, template literals, and destructuring.
• Improved Performance: Optimizations for faster execution.
• Modern Development Support: Meeting the demands of powerful web applications.
ES6 part I and II
1. let and const
Say goodbye to the quirks of var! With let and const, you can declare variables with block scope,
preventing sneaky bugs.
2. Arrow Functions
No more verbose anonymous functions! Arrow functions make your code concise and bind this
automatically. EX: let hello=(name)=>console.log(name); hello(svyasa);
3. Template Literals
Creating dynamic strings has never been easier! Use backticks and embed variables or expressions
directly: EX console.log(`hello ${name}`);
ES6 part I and II
4. De-structuring:
Simplify your code by extracting values from arrays or objects, and we can store in variables. 1.
• The Spread Operator (...) allows you to "spread out" elements from arrays or objects.
• The Rest Operator (...) lets you group multiple elements into an array.
• Spread Example:
Spread & Rest Operators (...)
console.log(allNumbers); // [1, 2, 3, 4, 5, 6]
Let [a,b,c,…rest]=[1,2,3,4,5];
Console.log(a); // 1
Console.log(rest); // [4,5]
Why it’s useful: Spread helps combine or copy arrays/objects. Rest helps handle unlimited
arguments easily.
ES6 part I and II
6.Default Parameters
Default parameters let you set a default value for a function argument , in case it’s not provided.
7.Method:
Methods are functions that are associated with objects. They are used to perform actions or
operations on the object's data. Methods can be defined as part of an object or added to an object
later. Below is a detailed explanation of methods in JavaScript,
7.Method:
const person = {
name: 'John',
age: 30,
greet: function() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
};
9.Constructor:
• Constructor is a special function used to create and initialize objects. Constructors are typically
used in conjunction with classes or function constructors to set up new instances of objects with
specific properties and methods.
• The constructor function returns the new object
Class, Constructor, This keyword
// Define a class
class Person {
// Constructor method
constructor(name, age) {
this.name = name;
this.age = age;
}
// Method
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
• When you access a property or method on an object, JavaScript first checks the object
itself. If the property or method isn’t found, it moves up the prototype chain until it finds
the property or reaches the end of the chain (null).
• Enables code reusability and efficiency
CONSTRUCTOR FUNCTION
Function Definition:
The function Person is defined with two parameters: name and age.
These parameters represent the properties that every object created from this constructor will have.
this.name = name; → Assigns the value of name to the name property of the object.
this.age = age; → Assigns the value of age to the age property of the object.
The this keyword inside a constructor function refers to the newly created object.
The new keyword is used to create a new instance of the Person object.
How the new Keyword Works
Creating an Object Using new Keyword (instance):
When new Person("Alice", 25); is executed, the following happens
The new keyword is used to create a new instance of internally:
the Person object. • A new empty object {} is created.
• The constructor function is called with this set to the new object.
.
• The properties (name and age) are added to the new object.
Example:
let person1 = new Person("Alice", 25);
let person2 = new Person("Bob", 30);
This creates two objects:
"Alice", age: 25 }
person2 = { name: "Bob", age: 30 }
The new object is returned
11️⃣Global Context (this in the global scope)
• In a browser, when this is used in the global scope, it refers to the window object.
"use strict";
console.log(this); // undefined
2️⃣Inside a Function
🔹 Object Method
🔹 Regular Function
• If a function is called as a method of an object,
• When this is used inside a regular function, it
refers to: this refers to that object.
👉 Unlike regular functions, this inside an arrow function does not refer to the calling object. Instead,
it inherits this from the parent scope.
What is a Prototype?
• In JavaScript, every function and object has a
prototype, which is an object from which other
objects inherit properties and methods. This forms
the basis of prototypal inheritance, allowing
objects to share functionality efficiently.
2. Controls Access (Encapsulation) → Variables inside a function/block cannot be accessed outside, keeping data
secure.
3. Saves Memory → Local variables are removed from memory after function execution, improving performance.
4. Supports Closures → Inner functions remember variables from their outer functions, even after execution.
5. Organizes Code → Helps structure code properly by defining where variables and functions should be accessible.
6. Prevents Unwanted Changes → Protects variables from accidental modifications by limiting their scope.
• Prototypal inheritance is a feature in JavaScript where objects can inherit properties and methods
from another object. Instead of using class-based inheritance (like in Java, C++, or Python),
JavaScript uses prototype chains to enable inheritance.
• Every JavaScript object has a hidden [[Prototype]] property (accessible via __proto__) that points to
another object, forming a prototype chain.
1 Creating Prototypal Inheritance using Object.create()
1️⃣
The Object.create() method allows you to create an object that directly inherits from another object.
const animal = {
eats: true,
🔹 Prototype Chain in Action
sleep() {
When accessing dog.eats, JavaScript:
console.log("Sleeping...");
} • Checks if eats exists in dog → ❌ Not found
}; • Looks up dog.__proto__ (which is animal) → ✅
// Creating a new object that inherits from `animal`
Found
const dog = Object.create(animal);
dog.barks = true;
console.log(dog.eats); // true (inherited from `animal`)
console.log(dog.barks); // true (own property)
dog.sleep(); // "Sleeping..." (inherited)
function Student(name, age, major) {
Person.call(this, name, age);
this.major = major;
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
const student1 = new Student("Bob", 20, "Computer Science");
console.log(student1.name); // Output: "Bob"
console.log(student1.age); // Output: 20
console.log(student1.major); // Output: "Computer Science"
student1.greet(); // Output: "Hello, my name is Bob"
function Student(name, age, major) {
This example demonstrates **prototypal inheritance** in JavaScript using Person.call(this, name, age);
this.major = major;
constructor functions. }
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
The `Student` function inherits from `Person` by calling `Person.call(this, name, const student1 = new Student("Bob", 20, "Computer
Science");
age)`, ensuring `Student` instances get `name` and `age` properties. console.log(student1.name); // Output: "Bob"
console.log(student1.age); // Output: 20
console.log(student1.major); // Output: "Computer Science"
To establish inheritance, `Student.prototype = Object.create(Person.prototype)` sets student1.greet(); // Output: "Hello, my name is Bob"
`Student`'s prototype to inherit from `Person`. The `constructor` is then restored with
`Student.prototype.constructor = Student`.
When `student1.greet()` is called, JavaScript looks up the prototype chain and finds
`greet()` in `Person.prototype`.
This approach enables code reusability and method sharing between objects.
JS Async
By the end of this lesson, you will:
• Understand setTimeout() and setInterval().
• Differentiate between Asynchronous and Synchronous Programming.
JavaScript Asynchronous Programming (JS Async)
JavaScript is single-threaded, meaning it executes one operation at a time.
Asynchronous programming allows JavaScript to handle tasks like fetching data,
reading files, or waiting for user input without blocking the execution of other
code.
🎡 Amusement Park Ride Analogy 🎢
1. Synchronous Approach (One Ride at a Time)
Imagine you’re at an amusement park, and there’s only one roller coaster. Here's how it works:
• You get in line for the ride.
• You wait until the ride finishes before anyone else can board.
• Once the ride is done, the next person in line can enter.
🔴 Problem? Everyone has to wait in line doing nothing until the previous ride finishes!
2. Asynchronous Approach (Multiple Rides Running)
Now, imagine the amusement park has multiple rides running at the same time:
• You get in line for one ride and get a ticket.
• While you wait for your turn, you can explore the park, buy snacks, or go on another ride.
• When it’s your turn, the park sends you a notification (callback), and you go enjoy the ride.
✅ Advantage? You don’t waste time standing in line—you can do other things while waiting!
How This Relates to JavaScript
• Synchronous: Tasks execute one at a time, and JavaScript waits for each task to complete
before moving to the next.
• Asynchronous: JavaScript can handle multiple tasks simultaneously, like fetching data from an
API while allowing the user to interact with a webpage.
Just like in an amusement park, asynchronous programming makes sure that JavaScript doesn’t
block the main flow and efficiently handles multiple tasks at once!
1. Synchronous Programming
• Code is executed line by line in a blocking manner.
• Each operation waits for the previous one to complete before executing the next.
• If a task takes time (e.g., fetching data), it halts further execution.
Example: Synchronous Code
console.log("Start");
console.log(“Middle");
console.log(“lower middle");
console.log("End");
Imagine you're at a restaurant, and you place an order for a dish that takes 20 minutes to prepare. Here's how
it relates to setTimeout:
console.log(time); }, 1000); }
displayClock(); // Starts the digital clock
How It Works:
• setInterval() runs every 1000ms (1 second).
• Gets the current time using new Date().
• Converts time to human-readable format using .toLocaleTimeString().
• Logs the updated time every second.
JS Callbacks
• A callback function is a function that is passed as an argument to another
function and is executed after that function has completed its task.
• Callbacks are commonly used in asynchronous programming to ensure that
code executes in the correct order.
JS Callbacks
• A callback function is a function that is passed as an argument to another
function and is executed after that function has completed its task.
function myfunc(val){
console.log(val(),"first function"); function myfunc(val){
}; console.log(val(),"first function");
};
function callback(){
return "i am callback";
} myfunc(function callback(){
return "i am callback";
myfunc(callback); // i am callback first function }); // i am callback first function
JS Callbacks
• A callback function is a function that is passed as an argument to another
function and is executed after that function has completed its task.
function sayGoodbye() {
console.log("Goodbye!");
}
const promise = new Promise((resolve, reject) => { const promise = new Promise((resolve, reject) => {
setTimeout(() => { setTimeout(() => {
resolve('Hello, World!'); reject('Error!');
}, 1000); }, 1000);
}); });
Promises in JavaScript provide a way to handle asynchronous operations in a more structured way. They are a powerful tool for
managing the async flow and the new syntax of Async & Await makes it even more readable and easy to understand.
Async & Await
Here's an example of a simple promise:
• Async & Await is a more modern approach to handle promises. It makes the code more readable
and less verbose.
• In this example, the function getData is declared as async. Inside the function, we use the await
keyword to wait for the promise returned by fetch to resolve. If the promise is fulfilled, the
resolved value (the response object) is assigned to the variable response. If the promise is
rejected, the control jumps to the catch block and the error is logged
Async & Await
async function getData() {
try {
const response = await
fetch('https://jsonplaceholder.typicode.com/todos/1');
const data = await response.json();
console.log(data);
} catch (error) {
console.log(error);
}
}
getData();