0% found this document useful (0 votes)
6 views73 pages

Javascript Notes

JavaScript is a versatile programming language used for creating interactive websites, supporting both client-side and server-side development. It includes features such as variables, data types, operators, and control structures, along with methods for debugging and user interaction. Additionally, JavaScript supports object-oriented programming through the use of objects and arrays, and can be enhanced with TypeScript for better type safety.

Uploaded by

hadikhan134000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views73 pages

Javascript Notes

JavaScript is a versatile programming language used for creating interactive websites, supporting both client-side and server-side development. It includes features such as variables, data types, operators, and control structures, along with methods for debugging and user interaction. Additionally, JavaScript supports object-oriented programming through the use of objects and arrays, and can be enhanced with TypeScript for better type safety.

Uploaded by

hadikhan134000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

Java Script

JavaScript is a programming language used to make websites


interactive. It allows you to add features like buttons that respond to
clicks, animations, or dynamic updates without reloading the page.
JavaScript is a client side and server side programming language.
Example: - Flipkart, Amazon, Lenskart etc.

console.log(); : is a function in JavaScript that outputs messages


to the browser's console. It is often used by developers to debug and
check values or code behavior while developing.

ctrl+shift+i is used to open console windows on any browser.

ctrl+shift+l is used to clear console windows output.


Creating our first javascript program to print Hello World on console.
console.log("Hello World");

Multiple ways to add javascript:-


●​ Inline
●​ Internal in head and body
●​ External in body
Note : always add javascript just before the body end tag.

Variable: a variable is a container used to store data values. It acts like


a labeled box where you can keep information that can be used and
changed later in the program.
Variable Rules:

●​ Names can contain letters, digits, underscores, and dollar signs.


●​ Names must begin with a letter.
●​ Names can also begin with $ and..
●​ Names are case sensitive (y and Y are different variables).
●​ Reserved words (like JavaScript keywords) CANNOT be used as
names
Data Types: are used to define what kind of data a variable is holding.

●​ Number: Numbers, like 5, 3.14, or -10.


●​ Boolean: true or false (true or false).
●​ String: Text, like "hello" or 'JavaScript'.
●​ Undefined: A variable with no assigned value (var x;).
●​ Null: An empty value (var y = null;).
●​ BigInt: Very large numbers (123n).
●​ Symbol: Unique identifiers (used rarely).

With the help of the typeof operator we can find the type of data a
variable is holding.

Non primitive data types : object and array.


Difference Between Primitive and Non-Primitive Data Types in
JavaScript

Keywords : reserved words are known as keywords.


In JavaScript, let, var, and const are used for variable declaration,
but they have key differences in scope, hoisting, and mutability:

1. Scope

●​ var: Function-scoped (accessible throughout the function it is


declared in).
●​ let: Block-scoped (only accessible within the block {} it is
declared in).
●​ const: Block-scoped (same as let, but with additional
restrictions).

2. Hoisting

●​ var: Hoisted with undefined as its initial value.


●​ let & const: Hoisted but not initialized (accessing them before
declaration results in a ReferenceError).
3. Reassignment & Mutability

●​ var: Can be reassigned and re-declared.


●​ let: Can be reassigned but cannot be redeclared in the same
scope.
●​ const: Cannot be reassigned or re-declared.

Difference in Chart

Two types of language: -

●​ Static Typed → Variables have fixed types (must be declared).


●​ Dynamic Typed → Variables can hold any type and change
dynamically
Naming Convention : In JavaScript, naming conventions are guidelines
for how to name variables, functions, classes, and other identifiers to
make code easier to read and maintain.

1. Camel Case (camelCase)

●​ Looks like: firstName, getUserInfo


●​ Used for:
○​ Variables
○​ Functions
○​ Object properties

let userName = "John"; // Variable

function getUserInfo() { // Function

return userName;

let person = { firstName: "John", lastName: "Doe" };


// Object properties

2. Pascal Case (PascalCase)

●​ Looks like: UserAccount, ProductManager


●​ Used for:
○​ Class names
○​ Constructor functions

class UserAccount {

constructor(name) {

this.name = name;

}
3. Snake Case (snake_case)

●​ Looks like: first_name, last_name


●​ Used for:
○​ Rarely in JavaScript
○​ Sometimes for constants or filenames

const MAX_SPEED = 120; // Constant (usually in


uppercase)

4. Kebab Case (kebab-case)

●​ Looks like: user-profile, background-color


●​ Used for:
○​ HTML IDs and classes
○​ File and folder names

<!-- HTML/CSS -->

<div id="user-profile" class="card"></div>

5. Screaming Snake Case (SCREAMING_SNAKE_CASE)

●​ Looks like: MAX_VALUE, API_KEY


●​ Used for:
○​ Constants (values that don’t change)

const API_KEY = "123456"; // Constant

const MAX_RETRIES = 5; // Constant


prompt: is used to display a dialog box that allows the user to input
some data. The prompt() function is part of the Window object.By
default prompt function takes input as a string.

let userInput = prompt(message, defaultValue);

Type casting in JavaScript refers to converting a value from one data


type to another. JavaScript supports two types of type casting:

1.​ Explicit Type Casting: You manually convert a value to another


type using built-in methods.
2.​ Implicit Type Casting (Type Coercion): JavaScript automatically
converts types during certain operations.

1. Explicit Type Casting

You use functions to explicitly convert data types. Here's how:

String Conversion

Convert a value to a string using:

●​ String()
●​ .toString() (only works for non-null and non-undefined
values)
●​ Template literals

2. Number Conversion

Convert a value to a number using:

●​ Number()
●​ parseInt() (for integers)
●​ parseFloat() (for decimals)
3. Boolean Conversion

Convert a value to a boolean using Boolean().

●​ Truthy values: Non-zero numbers, non-empty strings, objects,


true.
●​ Falsy values: 0, "", null, undefined, NaN, false.

2. Implicit Type Casting (Type Coercion)

JavaScript automatically converts types in certain scenarios:

String Coercion

Occurs when a non-string is concatenated with a string.

let result = "Value: " + 42; // "Value: 42"

let result = "5" - 2; // 3 (String "5" coerced to


Number)
let result2 = "5" * 2; // 10 (String "5" coerced to
Number)
Operators: are used to perform operation of operands.

Assignment operator: is used to perform arithmetic operations.

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Divide
% Modulus (Reminder)
** Exponentiation (Power Operator)

Nan: stands for "Not-a-Number". It is a special value that represents


something that is not a valid number. Example 0/0
Operator Precedence: This is the general order of solving an
expression. Like BODMAS in math.

Note: If the operators are on the same level , it will solve from left to
right.
Assignment Operator: The assignment operator works by taking the
value on the right-hand side (called the right operand) and storing it in
the variable on the left-hand side (called the left operand).

Operator Description
= Assign
+= Addition Assign
-= Subtraction Assign
*= Multiplication Assign
/= Divide Assign
%= Modulus (Reminder) Assign
**= Exponentiation (Power Operator)
Assign

Unary Operator: is used to increase or decrease value by 1.

Operator Description
++ Increment Operator
– Decrement Operator

Pre increment or Pre decrement: ++a / –a


Post increment or Pre decrement: a++ / a–

Boolean: represents a true or false / yes or no


Typescript: TypeScript is a programming language that builds on
JavaScript by adding types. Think of it as a "smarter" version of
JavaScript that helps catch mistakes and makes your code easier to
understand and maintain.

In short: TypeScript = JavaScript + Types for better safety and


readability.

Comments: are used to add notes or explanations in your code. They


help other developers (or your future self) understand the code better.
Comments are ignored by the JavaScript engine when the code runs.
Types of comments:-
1.​ Single line : //
2.​ Multi line comment : /* this is example of multiline comment */
Template Literals: they are used to add embedded expressions in a
string.With the help of backtick ``.
var pencilPrice=10;
var eraserPrice=5;
console.log(`the price of ${pencilPrice} +
${eraserPrice} is ${pencilPrice+eraserPrice} rupees.`);

Constant : a constant variable is a variable whose value cannot be


changed after it is assigned. This is done using the const keyword.

const PI = 3.14; // pi cannot be changed


Comparison operators: are symbols used to compare two values. They
help determine the relationship between them.They return boolean values
true or false.

Unicode : Unicode is a system that assigns a unique number (called a


code point) to every character, symbol, or emoji, no matter the language or
platform. This makes it possible to work with text in different languages and
scripts. Unicode Sheet
Conditional statement: are used to perform different actions based on
whether a condition is true or false.

Logical operators: are used to combine expressions. && , || , !

1. if Statement

Executes a block of code if the condition is true.

if (condition) {
// Code to execute if condition is true
}

2. if-else Statement

Adds an alternative block of code to execute if the condition is false.

if (condition) {
// Code to execute if condition is true }
else {
// Code to execute if condition is false
}

3. if-else if-else Statement

Checks multiple conditions in sequence.

if (condition1) {
// Code to execute if condition1 is true
}
else if (condition2) {
// Code to execute if condition2 is true
}
else {
//execute if none of the above conditions are true
}
4. switch Statement

Checks a value against multiple cases and executes matching code.

switch (expression) {

case value1:

// Code if expression === value1

break;

case value2:

// Code if expression === value2

break;

default:

// Code if no case matches

truthy & falsy : Everything in JS is true or false (in boolean context). This
doesn't mean their value itself is false or true, but they are treated as false
or true if taken in a boolean context.
alert() : is used to show a small popup message to the user. This popup
stops the rest of the webpage until the user clicks "OK." It’s often used to
give quick information or warnings.

console.error() : is used to display error messages in the browser's


developer console. It's a way to indicate that something went wrong or
needs attention in your code.

console.warn() : is used to display a warning message in the browser's


developer console. It’s usually shown in yellow to highlight that something
might be wrong or needs attention, but it doesn't stop the rest of the code
from running.

for loop: a for loop is used to repeatedly execute a block of code as long
as a specified condition is true.

Syntax:-

for (initialization; condition; increment/decrement) {

// Code to execute in each iteration

Infinite for loop is a loop which is never ending.

break keyword : is used to terminate a loop.

continue keyboard : is used to skip some part of a loop.


Nested loop : loop inside loop is called nested loop.

for (initialization; condition; increment) {

for (initialization; condition; increment) {

While Loop : A while loop in JavaScript repeatedly executes a block of


code as long as a specified condition is true.

let i = 1; // Initialization

while (i < 6) { // Condition

console.log(i);

i++; // Iteration (Increment/Decrement)

// Output: 1, 2, 3, 4 ,5
methods : a method in JavaScript is a function that is associated with an
object. Methods are used to perform actions on data or to interact with
objects in your code.

String: are text or sequence of characters.

let firstName="Tony";

let lastName='Stark';

String index

Length property: the length property is used to find the length of a


string.Length property returns an integer number.
Syntax:-
myString.length
undefined: a variable that has not been assigned a value is of type
undefined.
var a;

Null : the null value represents the intentional absence of any object
value.
var a = null;
String all Methods

Note: String method channing is also possible


Array: An array in JavaScript is a special type of object that can store a list
of items, like numbers, strings, or other values, all in one place. Think of it
like a container with multiple slots, where each slot holds a value.

Note:- Array is mutable.

Creating an array:-

1.​ var arr=[];


2.​ var arr= new Array();

var fruits = ["apple", "banana", "cherry"];

Array can be accessed by its index values, the array index starts from 0
and ends at size-1.
Array methods
Array constant: arr is a constant reference, but you can still modify the
array's contents (e.g., adding elements). However, you cannot reassign
arr itself to a new array.

const arr = [1, 2, 3]; // You can modify the contents


of the array

arr.push(4); // This is allowed

console.log(arr); // Output: [1, 2, 3, 4]

arr=[1,2,3,4] // Not Allowed

Object literals : An object literal in JavaScript is a way to define and


create objects using curly braces {}. It allows you to store data as
key-value pairs, where each key (also called a property) is associated with
a value.keys are written without double quotes.

let person = {

name: "John",

age: 30

};

Key Points

●​ Object literals are used to define and create objects in JavaScript.


●​ Objects are collections of key-value pairs.
●​ Methods can be added as functions inside an object.
●​ Object keys can be dynamic using computed property names.
Objects in JavaScript are incredibly useful and allow you to structure and
organize data effectively.

Two way to access object literals Value’s :

let person={

myname : "Shubham Patel",

id : 101

};

console.log(person["myname"]);

console.log(person.name);

Add/ Update/Delete Value :

let person={

myname : "Shubham Patel",

id : 101,

city : "indore"

};

person["city"]="mumbai"; // updating value

person.country="india"; // adding new key with value

delete person.country; // delete key and value

console.log(person);
Note : We can’t use dot operators with variables to access object literals
values.

let person={

myname : "Shubham Patel",

id : 101

};

let oid = "id";

console.log(person[oid]); // possible like this

console.log(person.oid); // not possible with dot operator

Note : JS automatically converts objects keys to strings.Even if we made


the number as a key, the number will be converted to string.

Note : compare object literals with arrays.

Const : if we use const keyword with object literals , we can’t reassign the
same object name , but values can be changed using key name.
nested objects: object literals inside object literals is called nesting of
objects.

let person = {

name: "John",

age: 30,

address: {

street: "123 Main St",

city: "New York",

country: "USA"

},

hobbies: ["reading", "traveling"],

education: {

degree: "Bachelor's",

field: "Computer Science",

graduationYear: 2015

};
Math object : The Math object in JavaScript provides built-in properties
and methods for mathematical constants and functions.

Math object methods and properties:-

Rounding Methods

1.​ Math.round(x)​
Rounds x to the nearest integer.
2.​ Math.floor(x)​
Rounds x down to the nearest integer.
3.​ Math.ceil(x)​
Rounds x up to the nearest integer.
4.​ Math.trunc(x)​
Truncates the decimal part of x (removes fractional digits).

Arithmetic and Exponentiation

5.​ Math.abs(x)​
Returns the absolute value of x.
6.​ Math.pow(base, exponent)​
Returns base raised to the power of exponent.
7.​ Math.sqrt(x)​
Returns the square root of x.
8.​ Math.cbrt(x)​
Returns the cube root of x.
9.​ Math.hypot(...values)​
Returns the square root of the sum of squares of its arguments.
Logarithmic and Exponential

10.​ Math.exp(x)​
Returns exe^xex, where eee is Euler's number.
11.​Math.expm1(x)​
Returns ex−1e^x - 1ex−1.
12.​ Math.log(x)​
Returns the natural logarithm (base eee) of x.
13.​ Math.log10(x)​
Returns the base-10 logarithm of x.
14.​ Math.log2(x)​
Returns the base-2 logarithm of x.
15.​ Math.log1p(x)​
Returns the natural logarithm of 1+x1 + x1+x.

Trigonometric

16.​ Math.sin(x)​
Returns the sine of x (in radians).
17.​ Math.cos(x)​
Returns the cosine of x (in radians).
18.​ Math.tan(x)​
Returns the tangent of x (in radians).
19.​ Math.asin(x)​
Returns the arcsine of x.
20.​ Math.acos(x)​
Returns the arccosine of x.
21.​ Math.atan(x)​
Returns the arctangent of x.
22.​ Math.atan2(y, x)​
Returns the angle between the positive x-axis and the point (x, y).

Hyperbolic Trigonometry

23.​ Math.sinh(x)​
Returns the hyperbolic sine of x.
24.​ Math.cosh(x)​
Returns the hyperbolic cosine of x.
25.​ Math.tanh(x)​
Returns the hyperbolic tangent of x.
26.​ Math.asinh(x)​
Returns the hyperbolic arcsine of x.
27.​ Math.acosh(x)​
Returns the hyperbolic arccosine of x.
28.​ Math.atanh(x)​
Returns the hyperbolic arctangent of x.

Miscellaneous

29.​ Math.max(...values)​
Returns the largest value from a list of numbers.
30.​ Math.min(...values)​
Returns the smallest value from a list of numbers.
31.​ Math.random()​
Returns a pseudo-random number between 0 (inclusive) and 1
(exclusive).
32.​ Math.sign(x)​
Returns the sign of x:
○​ 111 if positive
○​ −1-1−1 if negative
○​ 000 if zero
33.​ Math.clz32(x)​
Returns the number of leading zero bits in the 32-bit binary
representation of x.
34.​ Math.imul(a, b)​
Performs 32-bit integer multiplication of a and b.
35.​ Math.fround(x)​
Returns the nearest 32-bit single precision float representation of x.

Constants

While not methods, these constants are available in the Math object:

●​ Math.PI (π)(\pi)(π)
●​ Math.E (Euler's number)
●​ Math.LN2 (Natural logarithm of 2)
●​ Math.LN10 (Natural logarithm of 10)
●​ Math.LOG2E (Base-2 logarithm of eee)
●​ Math.LOG10E (Base-10 logarithm of eee)
●​ Math.SQRT1_2 (Square root of 1/2)
●​ Math.SQRT2 (Square root of 2)
Random Number Generator 1 to 10 :-

Task for student write four digit OTP verification program using
HTML,CSS and JS.

Task for student’s Guess the number game.


Function

In JavaScript, a function is a block of code designed to perform a specific


task. You can think of it as a reusable piece of code that you can "call"
whenever you need it.

Key Features:

1.​ Reusable: You can use the same function multiple times with
different inputs.
2.​ Organized: It makes your code easier to read and maintain.
3.​ Customizable: Functions can accept inputs (parameters) and give
back results (return values).

function greet() {

console.log("Welcome to india");

Function with argument

function greet(name) {

console.log("Welcome to india : ",name);

greet("Vishal Jain");
return keyword : In JavaScript, the return keyword is used inside a
function to send a value back to where the function was called. When
return is executed, the function stops running, and the specified value is
returned.

function add(a, b) {

return a + b; // The function returns the sum of a


and b

let result = add(3, 5); // Calling the function

console.log(result); // Output: 8
Scope : the scope determines the accessibility of variables, objects and
functions from different parts of the code.

●​ Function scope : variables defined inside a function are not


accessible(visible) from outside the function.

function sumOfN(n)

let sum=0; // function scope

for(let i=1;i<=n;i++){

sum+=i;

return sum;

console.log(sumOfN(10));

console.log(sum); // this is not accessible because it


is written in function
●​ Global Scope: Variables declared outside of any function or block
are in the global scope. They can be accessed from anywhere in
your code.

let sum = 33; // Global Scope

function sumOfN(n)

let sum=0;

for(let i=1;i<=n;i++){

sum+=i;

return sum;

console.log(sumOfN(10));

console.log(sum); // yes this is accessible


●​ Block Scope : variable declared inside a { } block cannot be
accessed from outside the block. Variables declared with let or
const inside a block {} are only accessible inside that block.

let name1 = "shubham";

console.log(name1);

●​ Lexical Scope : a variable defined outside a function can be


accessible inside another function defined after the variable
declaration.The opposite is not true.

function outerFunction() {

let outerVariable = "I'm from the outer scope";

function innerFunction() {

console.log(outerVariable); // Can access outerVariable

innerFunction();

outerFunction(); // Output: I'm from the outer scope


Hoisting : in JavaScript means that variable and function declarations are
moved (or "hoisted") to the top of their containing scope (global, function, or
block) during the compilation phase. This allows you to use variables and
functions before they are declared in the code.

Note :- However, only the declarations are hoisted, not the


initializations.

console.log(myVar); // Output: undefined

var myVar = "Hello!";

var myVar; // Declaration is hoisted

console.log(myVar); // Undefined because it's declared but not


initialized yet

myVar = "Hello!"; // Initialization happens here

greet(); // Output: Hello!

function greet() {

console.log("Hello!");

Note : difference between not defined and undefined.


Function Expression : a function expression is a way to define a function
as part of an expression rather than as a standalone declaration. It can be
assigned to a variable, passed as an argument to other functions, or
returned from another function.

const myFunction = function(parameter1, parameter2) {

// function body

return parameter1 + parameter2;

};

Characteristics:

1.​ Anonymous Functions: Function expressions can be anonymous


(no name given to the function).

const greet = function() {

console.log("Hello!");

};

greet(); // Output: Hello!

2. Named Function Expressions: Function expressions can also be


named, which is helpful for debugging.

const factorial = function fact(n) {

if (n === 0) return 1;

return n * fact(n - 1);

};

console.log(factorial(5)); // Output: 120


3. Hoisting: Function expressions are not hoisted to the top of their
scope, unlike function declarations. You cannot use them before defining
them.

sayHello(); // Error: Cannot access 'sayHello' before


initialization

const sayHello = function() {

console.log("Hello!");

};

4. Can Be Used Inline: Function expressions are often used as arguments


for higher-order functions (e.g., in callbacks).

setTimeout(function() {

console.log("This runs after 2 seconds.");

}, 2000);
High order functions : A function that does one or both:

●​ Takes one or multiple functions as arguments.


●​ Returns a function.

function hello(myFunc,count){

for(let i=1;i<=count;i++){

myFunc();

function myFunc() {

console.log("namaste");

hello(myFunc,5);

IIFE

An IIFE (Immediately Invoked Function Expression) is a function that


runs immediately after it is defined.
Methods : actions that can be performed on an object. In Simple definition
those functions which are defined in objects are called methods.

let calc ={

add : function(a,b){

return a+b;

},

sub : function(a,b){

return a-b;

},

mul : function(a,b){

return a*b;

},

console.log(calc.add(3,5));

console.log(calc.sub(20,5));

console.log(calc.mul(5,5));
Methods shorthand way to write

let calc ={

add(a,b){

return a+b;

},

sub(a,b){

return a-b;

},

console.log(calc.add(3,5));

console.log(calc.sub(20,5));
This keyword : The this keyword in JavaScript refers to the object that
is currently executing the code. Its value changes depending on where
and how it is used.

let student ={

name : "Shubham Patel",

subject : "PCM",

physics : 75,

math : 75,

chemistry : 75,

totalMarks(){

console.log(this);

console.log("Total Marks
:",this.physics+this.math+this.chemistry);

student.totalMarks();

Global Context If this is used in the global scope (outside of any function
or class), it refers to the global object. In a browser environment, the global
object is the window.Which is automatically created when the browser is
opened.Higher level is window object.

console.log(this);
Try and catch

The try statement allows you to define a block of code to be tested for errors
while it is being executed.

The catch statement allows you to define a block code to be executed, if an


error occurs in the try block.

The finally block is always executed, whether an error occurs or not. It is


typically used for cleanup operations like closing files, releasing resources, or
logging information.

The throw statement is used to manually create and throw errors in


JavaScript. This allows us to handle custom errors and control program flow.

JavaScript provides the Error object to create error messages. It has


built-in types like:

●​ Error → General error


●​ TypeError → Wrong type used (e.g., calling a number as a function)
●​ ReferenceError → Accessing an undefined variable
●​ SyntaxError → Code syntax is incorrect
●​ RangeError → Number out of range
Miscellaneous Topics

Arrow functions

An arrow function is a shorter way to write a function in JavaScript. It


uses the => (arrow) symbol.

Arrow function Implicit return

In JavaScript, implicit return means that the function automatically


returns the result without using the return keyword.
serTimeout

setTimeout is a function that runs code after a delay.


clearTimeout() cancels a scheduled timeout before it runs.

setInterval

setInterval runs a function again and again after a fixed time


interval.

clearInterval is used to stop a repeating action started by


setInterval.
Array Methods

forEach
In JavaScript, the forEach loop is a concise way to iterate over arrays.
Here's the syntax:

Map

This iterates over nums, applying the function (n => n * 2) to each


element, and returns a new array.
Filter

The .filter() method in JavaScript creates a new array with elements that
pass a given test.It doesn’t modify the original array, only returns a new
filtered one.

every

The .every() method in JavaScript checks if all elements in an array


pass a test (return true). If all elements satisfy the condition, it returns
true; otherwise, false.
some

The .some() method checks if at least one element in an array passes


a test. It returns true or false.

reduce
The .reduce() method in JavaScript executes a reducer function on
each element of an array, returning a single value.
Default Parameters

Giving a default value to the arguments

Spread Operator

The spread (...) operator in JavaScript expands elements of an array or


object.
Spread object literals

The spread operator (...) copies properties from one object to another.

Rest Parameters

In JavaScript, the rest parameter (...) allows a function to accept an


indefinite number of arguments as an array. It is useful when you want to
handle multiple arguments without explicitly defining them in the function
signature.
Destructuring : storing values of arrays into multiple variables.

Object Destructuring
Extract properties from an object into variables.
OOPS in JS

Object literal : An object literal is the simplest way to create


an object in JavaScript using curly braces {}. It allows you to
store key-value pairs.

Without using this keyword

With using this keyword

This keyword refers to the object that is currently executing the


function. Its value depends on how and where the function is
called.this refers to the current context or scope in which code
is being executed.
Adding own prototype method

When prototype and object has same method


Class : classes are a blueprint for creating objects. They make
it easier to create and manage multiple objects with the same
properties and methods.

Example if there is a phone company named Apple, it builds


many phones every day so it will first create a blueprint like a
phone should have a name, release year, features that are
properties and a phone must have some functionality like
calling, recording video, capturing a photo, texting etc.

Class is just a template for creating objects.

Those objects will have some states (variables) & some


behaviours (functions) inside it.
Methods in class & assigning values to a properties

constructor : A constructor is a special method inside a class


or function that initializes object properties when an object is
created.

Automatically invoked by new and initialised objects.


Inheritance : is passing down properties and methods from
parent class to child class.We use extends keyword.

Benefits of Inheritance

●​ Code Reusability → Avoids writing the same code


multiple times.
●​ Better Organization → Groups related functionality in a
structured way.
●​ Easier Maintenance → Changes in the parent class apply
to child classes automatically.
●​ Extensibility → Allows adding specialized features to
child classes without modifying the parent.
Single Inheritance (Most Common)

One child class inherits from one parent class.

Multilevel Inheritance

A child class inherits from another child class.


Multiple Inheritance (Indirectly Using Mixins)

JavaScript does not support multiple inheritance directly, but you


can use mixins (combining multiple objects).
Hierarchical Inheritance

One parent class has multiple child classes.

Note: if child & parent have same method, child’s method will
be used. [Method overriding]
Super keyword : the super keyword is used to call the
constructor of its parent class to access the parent properties
and methods.
Error
Calling parent class constructor
Calling Parent class method using super keyword
Encapsulation : Encapsulation in Object-Oriented
Programming (OOP) is the concept of hiding data and
restricting direct access to it. Instead, we use getter and setter
methods to control how the data is accessed and modified.
Abstraction : Abstraction is an Object-Oriented Programming
(OOP) principle that hides complex implementation details and
only exposes necessary functionalities. This makes the code
simpler to use and maintain.
Polymorphism : Polymorphism is an OOP concept that allows
multiple classes to have methods with the same name but
different behaviors.

In JavaScript, polymorphism is implemented using method


overriding and method overloading (partially supported).
DOM : stands for document object model . The DOM
represents a document with a logical tree.It allows us to
manipulate / change webpage content (HTML elements).

Node : A Node in the DOM (Document Object Model) is any


part of an HTML document, such as an element, text, or
comment. It forms the building blocks of the document's
structure in a tree-like hierarchy.

Document is an object which is automatically generated.


console.dir(document)
Selecting elements

document.getElementById()

Returns the element as an object or null (if not found)

document.getElementByClassName()

Returns the elements as an HTML collection or empty


collection (if not found)

document.getElementByTagName()

Returns the elements as an HTML collection or empty


collection (if not found)

Query Selectors : allows us to any CSS selector


Using properties and methods

innerText : shows the visible text contained in a node.


textContent : shows all the full text
innerHTML : shows the full markup

Attribute manipulating

obj.getAttribute(‘attr’);
obj.setAttribute(‘attr’,’value’);

Styling manipulating

obj.style.backgroundColor=”Orange”;

Note : css properties come in camel case.


Class list properties

obj.classList : In JavaScript, obj.classList is a property that


provides access to an element's list of CSS classes as a
DOMTokenList. This allows you to easily manipulate classes
without having to manually modify the className string.
Navigation : we can go from one element to another element.

parentElement : The parentElement property returns the


parent of an element or null if there is no parent.

children : The children property returns an HTMLCollection


(like an array) of an element's child elements (excluding text
nodes and comments).

previousElementSibling : The previousElementSibling


property returns the previous sibling element (ignoring text
nodes and comments). If there is no previous element, it
returns null.

nextElementSibling : The nextElementSibling property


returns the next sibling element (ignoring text nodes and
comments). If there is no next element, it returns null.

Adding elements

Creating an Element
document.createElement(‘p’)

appendChild() : is used to add any element in the last.

append : The append() function in JavaScript is a DOM


method used to add elements or text nodes to a specific parent
element. It can append multiple elements or text content at
once.

prepend() : is used to add any element at the first.


insertAdjacent(where,element) : This method in JavaScript is
used to insert an HTML element at a specified position relative
to another element.

Parameters:
position (string) – Specifies where to insert the element. The
possible values are:

"beforebegin" – Inserts newElement before the element itself.

"afterbegin" – Inserts newElement inside, before the first child


of element.

"beforeend" – Inserts newElement inside, after the last child of


the element.

"afterend" – Inserts newElement after the element itself.

newElement – The element to be inserted.

Removing Elements

removeChild() : The removeChild() method in JavaScript is


used to remove a specific child element from its parent in the
DOM.

remove() : The remove() method in JavaScript is used to


delete an element directly from the DOM without needing to
reference its parent. It is a simpler alternative to
removeChild().

You might also like