Javascript - Notes Ashok It
Javascript - Notes Ashok It
Introduction to JavaScript
a). What is JavaScript?
Definition:
JavaScript is a powerful, lightweight, and interpreted programming language used to make web
pages interactive. It allows developers to create dynamic content, handle events, and perform
various operations on web pages.
Syntax Example:
console.log("Hello, JavaScript!");
Examples:
alert("Welcome to JavaScript!");
● Creating Interactive Web Pages: Adding animations, form validations, and dynamic
elements.
● Handling Events: Performing actions based on user interactions like clicks or key
presses.
● Asynchronous Operations: Fetching data from servers without reloading pages.
● Server-Side Development: Using frameworks like Node.js to build backend
applications.
Syntax Example:
function greet(name) {
return "Hello, " + name;
}
console.log(greet("Alice"));
Examples:
function validateAge(age) {
if (age >= 18) {
return "Eligible";
} else {
return "Not Eligible";
}
}
console.log(validateAge(20));
Syntax Example:
Examples:
document.getElementById("btn").addEventListener("click", function() {
alert("Button Clicked!");
});
2. Looping through an array:
<script>
document.write("Hello from JavaScript!");
</script>
Examples:
1. In an HTML file:
<script>
console.log("JavaScript inside HTML!");
</script>
2. Using Node.js:
2. Installation of Node.js
console.log("Welcome to Node.js");
Examples:
3.Variables
a). Declaration
Syntax:
var x;
let y;
const z = 10;
b). Assignment
Syntax:
x = 5;
y = "Hello";
c). Initialization
Syntax:
Examples:
var a = 10;
var a = 20; // Redeclaration is allowed
console.log(a); // Output: 20
function example() {
if (true) {
var test = "Hello";
}
console.log(test); // Output: Hello (accessible outside the block)
}
example();
Definition: let is block-scoped, meaning it is accessible only within the block where it is
declared. It cannot be redeclared within the same scope but can be updated.
Examples:
let b = 10;
b = 20; // Allowed (reassignment)
console.log(b); // Output: 20
if (true) {
let name = "Alice";
console.log(name); // Output: Alice
}
// console.log(name); // Error: name is not defined outside block
3. const (Block-scoped, cannot be changed)
Definition: const is block-scoped and used to declare variables with constant values that
cannot be reassigned after initialization.
Examples:
const c = 10;
// c = 20; // Error: Assignment to constant variable
console.log(c); // Output: 10
const person = { name: "John" };
person.name = "Doe"; // Allowed (modifying object properties)
console.log(person.name); // Output: Doe
4. Data Types
JavaScript provides several data types:
a). Number
Example:
b). Boolean
Example:
c). String
d). Null
Example:
e). Undefined
Example:
let notAssigned;
f). BigInt
Example:
g). Symbol
Example:
8. Object
let person = {
name: "John",
age: 30
};
5. Functions
a). What is a Function?
Example:
function greet() {
console.log("Hello, World!");
}
greet();
● Code reusability
● Modular structure
● Improved readability
● Easier debugging and maintenance
A function is defined using the function keyword, followed by the function name and
parentheses.
e). Function Scope
Functions can have local scope (variables declared inside) or global scope (accessible
everywhere).
The function block is enclosed within curly braces {} containing the code to be executed.
Example:
function sayHello() {
console.log("Hello!");
}
sayHello();
1. Normal Function
function add(a, b) {
return a + b;
}
console.log(add(5, 3));
Parameters are placeholders used in function definition, while arguments are actual values
passed when calling the function.
function multiply(x, y) {
return x * y;
}
console.log(multiply(4, 2));
3. Return Statement
function square(num) {
return num * num;
}
console.log(square(6));
4. Callback Function
function process(callback) {
callback();
}
process(() => console.log("Callback executed"));
5. Function Expression
6. Anonymous Function
setTimeout(function() {
console.log("This is an anonymous function");
}, 1000);
7. Arrow Function
A concise way to write functions using => syntax.
const sum = (a, b) => a + b;
console.log(sum(3, 5));
8. Async Function
9. Higher-Order Function
function operate(operation, x, y) {
return operation(x, y);
}
console.log(operate((a, b) => a + b, 5, 10));
6. Object
a). What is an Object?
An object is a collection of key-value pairs that represent data and behavior. Objects allow you
to store and manage related data efficiently.
Example:
const person = {
name: "Alice",
age: 25,
greet: function() {
console.log("Hello, " + this.name);
}
};
person.greet();
Objects can be created using object literals or the new Object() constructor.
const car = {
brand: "Toyota",
model: "Corolla",
year: 2022
};
Example 2 (Constructor):
d). Properties
Example:
i). Read
ii). Insert
iii). Update
person.age = 30;
console.log(person);
iv). Delete
delete person.city;
console.log(person);
i). Object.seal()
Prevents new properties from being added to an object but allows modification of existing
properties.
ii). Object.assign()
iii). Object.keys()
7. Array
a). Syntax
An array in JavaScript is a special type of object used for storing ordered collections of values.
Syntax:
b). Purpose
Arrays allow you to store multiple values in a single variable and are used when you need to
store a list of items like numbers, strings, objects, etc.
Syntax:
d). Index
Example 1:
Example 2:
Adds one or more elements to the end of an array and returns the new length of the array.
Syntax:
Example 1:
Example 2:
b). Pop
Removes the last element from an array and returns that element.
Syntax:
array.pop();
Example 1:
c). Shift
Removes the first element from an array and returns that element.
Syntax:
array.shift();
Example 1:
Example 2:
d). Unshift
Adds one or more elements to the beginning of an array and returns the new length of the array.
Syntax:
array.unshift(element1, element2, ...);
Example 1:
e). ForEach
Syntax:
Example 1:
Example 2:
f). Map
Creates a new array populated with the results of calling a provided function on every element
in the array.
Syntax:
Example 2:
h). Filter
Creates a new array with all elements that pass the test implemented by the provided function.
Syntax:
Example 1:
Example 2:
i). Splice
Changes the contents of an array by removing or replacing existing elements and/or adding new
elements in place.
Syntax:
Example 2:
j). Slice
Returns a shallow copy of a portion of an array into a new array object selected from the start to
the end (end not included).
Syntax:
Example 1:
Example 2:
k). Includes
array.includes(element, start);
Example 1:
Example 2:
l). indexOf
Returns the first index at which a given element can be found in the array, or -1 if it is not
present.
Syntax:
array.indexOf(element, start);
Example 1:
Example 2:
Syntax:
if (condition) {
// code to be executed if condition is true
}
Example 1:
Example 2
b). Else
The else statement provides an alternative code block to be executed if the condition in the if
statement is false.
Syntax:
if (condition) {
// code if condition is true
} else {
// code if condition is false
}
Example 1:
Example 2:
c). Else If
The else if statement allows multiple conditions to be checked in a sequence. If the first
condition is false, it checks the next condition.
Syntax:
if (condition1) {
// code if condition1 is true
} else if (condition2) {
// code if condition2 is true
} else {
// code if all conditions are false
}
Example 1:
Example 2:
d). Switch
The switch statement evaluates an expression and executes the corresponding case block if it
matches one of the cases.
Syntax:
switch (expression) {
case value1:
// code if expression === value1
break;
case value2:
// code if expression === value2
break;
default:
// code if no match is found
}
Example 1:
Example 2:
f). Loops
i). For
The for loop is used for repeating a block of code a specific number of times, based on a
condition.
Syntax:
Example 1:
Example 2:
ii). For...of
The for...of loop is used to iterate over iterable objects like arrays, strings, etc.
Syntax:
Example 1:
iii). For...in
The for...in loop is used to iterate over the properties (keys) of an object.
Syntax:
Example 1:
Example 2:
The spread syntax (...) is used to create a shallow copy of an object or merge multiple
objects.
Syntax:
Example 1:
Example 2:
ii). How to Copy Elements from One Array into Another Array
The spread syntax can also be used to copy elements from one array into another array.
Syntax:
Example 1:
11. Rest
a). Rules of Parameter
The rest syntax (...) is used to collect all remaining arguments into an array. It can only be
used as the last parameter in a function.
Syntax:
function myFunction(...params) {
// params is an array containing all passed arguments
}
Example 1:
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3)); // Output: 6
Example 2:
function logNames(...names) {
console.log(names);
}
logNames('Alice', 'Bob', 'Charlie'); // Output: ['Alice', 'Bob', 'Charlie']
The rest parameter must always be the last parameter in the function definition.
Syntax:
Example 1:
Example 2:
12. Destructuring
a). Object Destructuring
Object destructuring allows you to unpack values from objects into distinct variables.
Syntax:
Example 2:
Array destructuring allows you to unpack values from arrays into distinct variables.
Syntax:
Example 1:
Example 2:
A variable has global scope if it is declared outside of any function or block, meaning it is
accessible anywhere in the code.
Example 1:
Example 2:
A variable has function scope if it is declared inside a function. It is only accessible within that
function.
Example 1:
function myFunction() {
let localVar = 'I am local';
console.log(localVar); // Output: I am local
}
myFunction();
console.log(localVar); // Error: localVar is not defined
Example 2:
function add() {
var sum = 10 + 5;
console.log(sum); // Output: 15
}
add();
console.log(sum); // Error: sum is not defined
c). Block Scope
Variables declared with let and const have block scope. They are only accessible within the
block (e.g., within curly braces {}).
Example 1:
if (true) {
let blockVar = 'Inside block';
console.log(blockVar); // Output: Inside block
}
console.log(blockVar); // Error: blockVar is not defined
Example 2:
Lexical scope refers to the location where a variable is declared within the code and
determines its accessibility.
Example 1:
function outer() {
let outerVar = 'Outer variable';
function inner() {
console.log(outerVar); // Output: Outer variable
}
inner();
}
outer();
e). Var
Variables declared with var have function scope (if declared inside a function) or global
scope (if declared outside any function).
Example 1:
var x = 10;
if (true) {
var x = 20; // Reassigns the global variable
}
console.log(x); // Output: 20
Example 2:
function myFunc() {
var x = 30;
console.log(x); // Output: 30
}
myFunc();
f). Let
Example 1:
let x = 10;
if (true) {
let x = 20; // Declares a new variable in the block
console.log(x); // Output: 20
}
console.log(x); // Output: 10
Example 2:
let a = 100;
if (true) {
let a = 200; // Block scoped
console.log(a); // Output: 200
}
console.log(a); // Output: 100
g). Const
Variables declared with const have block scope and cannot be reassigned after initialization.
Example 1:
const x = 10;
// x = 20; // Error: Assignment to constant variable
Example 2:
14.this Keyword
a). Browser Context
● Definition: In the browser context, this refers to the global object (usually window), or
to the object invoking a method.
● Syntax:
○ this refers to the current context, which is determined by how the function is
called.
Definition: In an arrow function, this is lexically inherited from the surrounding context (does
not have its own this).
Syntax:
Example 1:
const obj = {
name: 'Alice',
greet: () => {
console.log(this.name); // Output: undefined (inherited from global
context)
}
};
obj.greet();
Example 2:
const obj = {
name: 'Bob',
greet: function() {
const inner = () => {
console.log(this.name); // Output: Bob (inherited from outer
function's `this`)
};
inner();
}
};
obj.greet();
Definition: In a regular function (named), this refers to the object invoking the method.
Syntax:
function func() {
console.log(this);
}
Example 1:
const obj = {
name: 'Charlie',
greet: function() {
console.log(this.name); // Output: Charlie
}
};
obj.greet();
Example 2:
function showName() {
console.log(this.name); // Output: undefined (global `this` in browser)
}
showName();
Definition: Arrow functions in Node inherit this from the surrounding lexical context, just
like in the browser.
Example 1:
const obj = {
name: 'Node',
greet: () => {
console.log(this.name); // Output: undefined (lexical this, from global
context)
}
};
obj.greet();
Example 2:
const obj = {
name: 'Express',
greet: function() {
const inner = () => {
console.log(this.name); // Output: Express (inherited from outer
function's `this`)
};
inner();
}
};
obj.greet();
Definition: In a named function in Node.js, this can refer to the global object or the
object invoking the function, depending on the context.
Example 1:
const person = {
name: 'Alice',
greet: function() {
console.log(this.name); // Output: Alice
}
};
person.greet();
Example 2:
function showContext() {
console.log(this); // Output: global object in Node.js (not `window` like
in the browser)
}
showContext();
15. Call
a). What is Call
Definition: The call() method allows you to invoke a function with a specific this value and
arguments passed individually.
Syntax:
b). Purpose
Purpose: It is used to invoke a function with a specific context (this) and can pass any number
of arguments.
You use call() to invoke a function and specify its this context and arguments.
Example 1:
function greet() {
console.log('Hello, ' + this.name);
}
const person = { name: 'Alice' };
greet.call(person); // Output: Hello, Alice
Example 2:
function sum(a, b) {
console.log(a + b);
}
sum.call(null, 5, 3); // Output: 8
16. Apply
a). What is Apply
Definition: The apply() method is similar to call(), but it takes an array or array-like object of
arguments instead of individual arguments.
Syntax:
b). Purpose
Purpose: It is used to invoke a function with a specific this context and an array of
arguments.
You use apply() when you want to pass an array of arguments to the function.
Example 1:
function greet(message) {
console.log(message + ', ' + this.name);
}
const person = { name: 'Bob' };
greet.apply(person, ['Hello']); // Output: Hello, Bob
Example 2:
function sum(a, b, c) {
console.log(a + b + c);
}
sum.apply(null, [1, 2, 3]); // Output: 6
17. Bind
a). What is Bind
Definition: The bind() method creates a new function that, when invoked, has a specific this
value and any number of arguments pre-set.
Syntax:
b). Purpose
Purpose: It is used to set a fixed this context for a function, and it returns a new function
with that this context.
You use bind() when you need to create a new function that can be invoked later, with a
fixed this value and pre-defined arguments.
Example 1:
function greet() {
console.log('Hello, ' + this.name);
}
const person = { name: 'Charlie' };
const greetPerson = greet.bind(person);
greetPerson(); // Output: Hello, Charlie
Example 2:
function add(a, b) {
console.log(a + b);
}
const addFive = add.bind(null, 5);
addFive(3); // Output: 8
18. Difference Between call(), apply(), and bind()
Execution Invokes the function Invokes the function Returns a new function
immediately immediately (no execution)
Return Value Result of the function Result of the function A new bound function
a). Call
Definition: The call() method invokes a function immediately with a specified this context and
arguments passed individually.
Syntax:
Example 1:
function greet(message) {
console.log(message + ', ' + this.name);
}
const person = { name: 'Alice' };
greet.call(person, 'Hello'); // Output: Hello, Alice
Example 2:
function sum(a, b) {
console.log(a + b);
}
sum.call(null, 5, 3); // Output: 8
2. Apply
● Definition: The apply() method is similar to call(), but it takes an array (or array-like
object) of arguments instead of individual arguments.
Syntax:
javascript
CopyEdit
functionName.apply(thisContext, [arg1, arg2, ...]);
●
Example 1:
javascript
CopyEdit
function greet(message) {
●
Example 2:
javascript
CopyEdit
function sum(a, b, c) {
console.log(a + b + c);
}
sum.apply(null, [1, 2, 3]); // Output: 6
●
3. Bind
● Definition: The bind() method creates a new function with a specified this context and
pre-defined arguments, but does not invoke the function immediately.
Syntax:
javascript
CopyEdit
let boundFunction = functionName.bind(thisContext, arg1, arg2, ...);
●
Example 1:
javascript
CopyEdit
function greet() {
●
Example 2:
javascript
CopyEdit
function add(a, b) {
console.log(a + b);
●
Closures
1. What is Closures
● Definition: A closure is a function that remembers and has access to its lexical scope,
even when the function is executed outside that scope.
● Definition: Closures are created when a function is defined inside another function, and
the inner function accesses variables from the outer function.
3. Syntax
javascript
CopyEdit
function outerFunction() {
function innerFunction() {
console.log(outerVar); // Closure
return innerFunction;
4. Purpose
● Purpose: Closures are useful for maintaining state, data encapsulation, and
implementing function factories.
Example 1:
javascript
CopyEdit
function outer() {
let counter = 0;
function increment() {
counter++;
console.log(counter);
return increment;
counterClosure(); // Output: 1
counterClosure(); // Output: 2
●
Example 2:
javascript
CopyEdit
function greeting(message) {
return function(name) {
●
Promises
1. Creation of Promise
● Definition: A promise is an object that represents the eventual completion (or failure) of
an asynchronous operation and its resulting value.
Syntax:
javascript
CopyEdit
const promise = new Promise((resolve, reject) => {
});
●
Example 1:
javascript
CopyEdit
const promise = new Promise((resolve, reject) => {
if (success) {
resolve('Operation succeeded!');
} else {
reject('Operation failed!');
});
●
Example 2:
javascript
CopyEdit
const promise = new Promise((resolve, reject) => {
if (data) {
resolve(data);
} else {
});
●
2. Resolve
Syntax:
javascript
CopyEdit
resolve(value);
●
Example 1:
javascript
CopyEdit
const promise = new Promise((resolve) => {
resolve('Data received');
});
●
Example 2:
javascript
CopyEdit
const promise = new Promise((resolve) => {
resolve('Task completed');
});
3. Reject
● Definition: reject() is called when the asynchronous operation fails, and it provides the
error message or reason for failure.
Syntax:
javascript
CopyEdit
reject(error);
●
Example 1:
javascript
CopyEdit
const promise = new Promise((_, reject) => {
reject('Error occurred');
});
●
Example 2:
javascript
CopyEdit
const promise = new Promise((_, reject) => {
});
●
4. States of Promise
if (success) {
resolve('Operation successful');
} else {
reject('Operation failed');
});
●
Example 2:
javascript
CopyEdit
const promise = new Promise((resolve, reject) => {
if (success) {
resolve('Data fetched');
} else {
});
Syntax:
javascript
CopyEdit
promise.then(result => {
// handle success
}).catch(error => {
// handle error
});
●
Example 1:
javascript
CopyEdit
const promise = new Promise((resolve, reject) => {
resolve('Success!');
});
promise.then(result => {
}).catch(error => {
console.log(error);
});
●
Example 2:
javascript
CopyEdit
const promise = new Promise((_, reject) => {
reject('Failed to fetch data');
});
promise.then(result => {
console.log(result);
}).catch(error => {
});
●
Async/Await
Syntax:
javascript
CopyEdit
async function fetchData() {
try {
console.log(result);
} catch (error) {
console.log(error);
●
Example 1:
javascript
CopyEdit
const fetchData = async () => {
const promise = new Promise((resolve, reject) => {
resolve('Data received');
});
try {
} catch (error) {
console.log(error);
};
fetchData();
●
Example 2:
javascript
CopyEdit
async function fetchData() {
});
try {
console.log(result);
} catch (error) {
console.log(error); // Output: Failed to fetch data
fetchData();
●
Syntax:
javascript
CopyEdit
async function fetchData() {
try {
console.log(result);
} catch (error) {
console.log(error);
●
Example 1:
javascript
CopyEdit
async function fetchData() {
resolve('Task completed');
});
try {
const result = await promise;
} catch (error) {
console.log(error);
fetchData();
●
Example 2:
javascript
CopyEdit
async function fetchData() {
reject('Error encountered');
});
try {
console.log(result);
} catch (error) {
● fetchData();
● Definition: The Document Object Model (DOM) represents the structure of an HTML
document as an object-oriented tree structure, where each node is an object
representing part of the page (e.g., elements, attributes, and text).
● Purpose: It allows programs and scripts to dynamically access and update the content,
structure, and style of web pages.
Example 1:
javascript
CopyEdit
// Accessing an element using DOM
●
Example 2:
javascript
CopyEdit
const divElement = document.createElement('div');
document.body.appendChild(divElement);
●
2. DOM Objects
● Definition: DOM objects are the elements, attributes, and text nodes within an HTML
document that are represented as objects in the DOM.
Example 1:
javascript
CopyEdit
const titleElement = document.getElementById('title');
●
Example 2:
javascript
CopyEdit
const paragraphs = document.getElementsByClassName('para');
console.log(paragraphs); // DOM collection of all elements with class 'para'
●
Example 1:
javascript
CopyEdit
const heading = document.getElementById('heading');
●
Example 2:
javascript
CopyEdit
const listItems = document.querySelectorAll('.list-item');
●
● Definition: The DOM provides methods for modifying HTML elements, adding new
content, changing styles, and handling events.
Example 1:
javascript
CopyEdit
const header = document.getElementById('header');
●
Example 2:
javascript
CopyEdit
const button = document.querySelector('button');
DOM Methods
5. getElementById
● Definition: The getElementById() method returns a reference to the first object with the
specified id.
Syntax:
javascript
CopyEdit
document.getElementById('id');
●
Example 1:
javascript
CopyEdit
const element = document.getElementById('uniqueId');
●
Example 2:
javascript
CopyEdit
const button = document.getElementById('submitButton');
●
6. getElementsByClassName
Syntax:
javascript
CopyEdit
document.getElementsByClassName('className');
●
Example 1:
javascript
CopyEdit
const paragraphs = document.getElementsByClassName('para');
●
Example 2:
javascript
CopyEdit
const listItems = document.getElementsByClassName('list');
●
7. querySelector
● Definition: The querySelector() method returns the first element that matches a
specified CSS selector.
Syntax:
javascript
CopyEdit
document.querySelector('selector');
●
Example 1:
javascript
CopyEdit
const firstButton = document.querySelector('button');
●
Example 2:
javascript
CopyEdit
const header = document.querySelector('#header');
●
8. innerText
● Definition: innerText is a property that gets or sets the text content of an element,
excluding HTML tags.
Syntax:
javascript
CopyEdit
element.innerText;
●
Example 1:
javascript
CopyEdit
const paragraph = document.getElementById('para');
●
Example 2:
javascript
CopyEdit
const header = document.getElementById('header');
●
9. innerHTML
● Definition: innerHTML is a property that gets or sets the HTML content inside an
element.
Syntax:
javascript
CopyEdit
element.innerHTML;
●
Example 1:
javascript
CopyEdit
const contentDiv = document.getElementById('content');
●
Example 2:
javascript
CopyEdit
const footer = document.getElementById('footer');
●
10. append
● Definition: The append() method adds a new element or text to the end of an element's
content.
Syntax:
javascript
CopyEdit
parentElement.append(childElement);
●
Example 1:
javascript
CopyEdit
const div = document.createElement('div');
●
Example 2:
javascript
CopyEdit
const paragraph = document.createElement('p');
●
11. appendChild
● Definition: The appendChild() method appends a child element to the specified parent
node.
Syntax:
javascript
CopyEdit
parentElement.appendChild(childElement);
●
Example 1:
javascript
CopyEdit
const li = document.createElement('li');
●
Example 2:
javascript
CopyEdit
const span = document.createElement('span');
●
CreateElement
●
Example 1:
javascript
CopyEdit
const divElement = document.createElement('div');
●
Example 2:
javascript
CopyEdit
const h2 = document.createElement('h2');
●
● Definition: After creating a DOM element, content can be added using properties like
textContent or innerHTML.
Example 1:
javascript
CopyEdit
const pElement = document.createElement('p');
●
Example 2:
javascript
CopyEdit
const anchor = document.createElement('a');
anchor.href = 'https://example.com';
●
● Definition: A newly created DOM element is added to the DOM tree using
appendChild(), insertBefore(), or other methods.
Example 1:
javascript
CopyEdit
const newDiv = document.createElement('div');
●
Example 2:
javascript
CopyEdit
const newSection = document.createElement('section');
●
Example 1:
javascript
CopyEdit
const divToRemove = document.getElementById('removeMe');
divToRemove.remove(); // Removing an element by calling remove()
●
Example 2:
javascript
CopyEdit
const parent = document.getElementById('parent');
●
Fetch API
1. Get Request
● Definition: The Fetch API provides an easy-to-use interface for making HTTP requests.
The GET request is used to retrieve data from the server.
Syntax:
javascript
CopyEdit
fetch(url)
●
Example 1:
javascript
CopyEdit
fetch('https://jsonplaceholder.typicode.com/posts')
Example 2:
javascript
CopyEdit
fetch('https://api.example.com/users')
●
1. Class
● Definition: A class is a blueprint for creating objects, providing initial values for state
(member variables) and implementations of behavior (methods or functions).
Syntax:
javascript
CopyEdit
class ClassName {
constructor() {
// constructor body
●
Example 1:
javascript
CopyEdit
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
greet() {
●
Example 2:
javascript
CopyEdit
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
start() {
●
2. Object
Syntax:
javascript
CopyEdit
const objectName = new ClassName();
●
Example 1:
javascript
CopyEdit
const person = new Person('John', 30);
●
Example 2:
javascript
CopyEdit
const car = new Car('Honda', 'Civic');
●
3. Constructor
● Definition: The constructor is a special method in a class that is called when a new
object of the class is created. It is used to initialize properties of the object.
Syntax:
javascript
CopyEdit
constructor(parameters) {
// initialization code
}
●
Example 1:
javascript
CopyEdit
class Animal {
constructor(name, sound) {
this.name = name;
this.sound = sound;
makeSound() {
●
Example 2:
javascript
CopyEdit
class Book {
constructor(title, author) {
this.title = title;
this.author = author;
}
getBookInfo() {
●
4. Inheritance
● Definition: Inheritance is a mechanism where one class can inherit properties and
methods from another class, allowing for code reuse.
Syntax:
javascript
CopyEdit
class ChildClass extends ParentClass {
●
Example 1:
javascript
CopyEdit
class Animal {
constructor(name) {
this.name = name;
speak() {
constructor(name) {
speak() {
console.log(`${this.name} barks.`);
●
Example 2:
javascript
CopyEdit
class Shape {
constructor(type) {
this.type = type;
describe() {
console.log(`This is a ${this.type}`);
}
constructor(radius) {
super('Circle');
this.radius = radius;
area() {
console.log(circle.area()); // 78.53981633974483
●
Syntax:
javascript
CopyEdit
class ChildClass extends ParentClass {
methodName() {
// Overriding parent method
Example 1:
javascript
CopyEdit
class Animal {
speak() {
speak() {
console.log('Dog barks');
Example 2:
javascript
CopyEdit
class Vehicle {
start() {
console.log('Vehicle is starting');
start() {
console.log('Car is starting');
Module Concept in JS
Definition: In JavaScript, modules are reusable pieces of code that can be imported and
exported to avoid polluting the global namespace. Modules help in organizing code into
smaller, manageable units.
Example 1:
javascript
CopyEdit
// In math.js (module)
console.log(add(2, 3)); // 5
console.log(subtract(5, 3)); // 2
Example 2:
javascript
CopyEdit
// In greetings.js
javascript
CopyEdit
// In app.js
2. Why We Use It
Definition: Modules are used to split code into smaller parts, making it easier to
maintain, debug, and test. It also helps in code reuse and modularity.
Example 1:
javascript
CopyEdit
// utils.js
return date.toISOString().split('T')[0];
}
javascript
CopyEdit
// app.js
Example 2:
javascript
CopyEdit
// calculate.js
javascript
CopyEdit
// app.js
console.log(multiply(3, 4)); // 12
3. Named Export
Definition: Named exports allow you to export multiple values from a module by their
names, which must be imported using the same names.
Syntax:
javascript
CopyEdit
export const name = value;
Example 1:
javascript
CopyEdit
// module.js
console.log(square(3)); // 9
console.log(cube(3)); // 27
Example 2:
javascript
CopyEdit
// util.js
javascript
CopyEdit
// app.js
console.log(double(4)); // 8
4. Default Export
Definition: Default exports allow you to export a single value from a module. The value
can be imported without specifying the name.
Syntax:
javascript
CopyEdit
export default value;
Example 1:
javascript
CopyEdit
// math.js
javascript
CopyEdit
// app.js
console.log(add(2, 3)); // 5
Example 2:
javascript
CopyEdit
// logger.js
console.log(message);
javascript
CopyEdit
// app.js
Definition: Named exports are imported by specifying the exact names of the variables
or functions you want to use.
Syntax:
javascript
CopyEdit
import { name1, name2 } from 'module';
Example 1:
javascript
CopyEdit
// math.js
javascript
CopyEdit
// app.js
console.log(sum(1, 2)); // 3
console.log(subtract(5, 3)); // 2
Example 2:
javascript
CopyEdit
// colors.js
javascript
CopyEdit
// app.js
console.log(red); // #FF0000
console.log(blue); // #0000FF
Definition: A default export is imported without the need for curly braces.
Syntax:
javascript
CopyEdit
import variable from 'module';
Example 1:
javascript
CopyEdit
// math.js
return a * b;
javascript
CopyEdit
// app.js
console.log(multiply(2, 3)); // 6
Example 2:
javascript
CopyEdit
// greeting.js
javascript
CopyEdit
// app.js