0% found this document useful (0 votes)
33 views132 pages

Js Mastery Notes by Tishant Agrawal

Uploaded by

cloudangelm2
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)
33 views132 pages

Js Mastery Notes by Tishant Agrawal

Uploaded by

cloudangelm2
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/ 132

WELCOME TO

JS MASTERY COURSE : THE ULTIMATE GUIDE !


HTML CSS JAVASCRIPT
AL
AW
GR
T A
AN
ISH
T
AL
AW
LEVELG1
R
T A
AN
ISH
T
L
What is Javascript ?
A
AW
JavaScript is a high-level, versatile, and interpreted

R
programming language primarily used for creating
G
A
interactive and dynamic content on websites. It is often

T
employed to enhance user experience by enabling client-

N
side scripts that run in web browsers. Developed by

A
Netscape, JavaScript has become one of the core

H
S
technologies for building web applications.

TI
AL
JavaScript is an essential component of web development alongside
HTML and CSS. It allows developers to manipulate the Document

W
Object Model (DOM) of a web page, enabling dynamic updates and

A
changes to the content displayed to users. JavaScript can be used for

GR
various purposes, including form validation, interactive user interfaces,
asynchronous communication with servers (Ajax), and more.

T A
It is important to note that JavaScript is distinct from Java,

N
despite the similarity in their names. JavaScript is mainly used on

A
the client side, while Java is typically used for server-side

H
development. Additionally, JavaScript has evolved over the years,

S
I
and with the introduction of technologies like Node.js, it can now

T be used on the server side as well.


L
WHAT IS A PROGRAMMING LANGUAGE ?
A
AW
A programming language is a formal system designed to

GR
instruct a computer or machine. It consists of a set of rules

A
and syntax that allows programmers to write instructions for

T
the computer to execute specific tasks. These instructions,

AN
known as code, can range from simple operations to complex
algorithms.

SH
TI
AL
Programming languages serve as a bridge between human
understanding and machine execution. They provide a way for

AW
programmers to communicate their intentions to computers in a
structured and understandable manner. Different programming

R
languages have varying levels of abstraction, capabilities, and

G
A
purposes, making them suitable for different types of tasks and

T
applications.

AN
Some common programming languages include Python, Java, C++,
JavaScript, and many others. Each language has its own strengths and

H
weaknesses, and the choice of a programming language often depends on

S
I
the requirements of a particular project.

T
L
WHAT IS A SYNTAX ?
A
AW
In programming, syntax refers to the set of rules that dictate

GR
how programs written in a specific programming language

A
are structured. It defines the combinations of symbols,

T
keywords, and other elements that are considered valid in

AN
that language. Proper syntax is crucial for writing code that
the computer can understand and execute.

SH
TI
INTERNAL AND EXTERNAL A L JS
A W
Certainly! When we talk about R

A G
"external JS," we are referring
"internal JS" and
to the placement of
T
JavaScript code within an HTML document.
N
H A
I S
T
A L
Internal JavaScript: Internal JavaScript refers to including JavaScript
code directly within the HTML document. This is typically done within

W
the <script> tag, either in the <head> section or at the end of the <body>

A
section. Here's an example:

<script>
G R
functionT
// Your JavaScriptA code goes here

A N myFunction() {
alert("Hello, World!");

S H }

TI </script>
A L
External JavaScript: External JavaScript involves
placing the JavaScript code in a separate file with a .js

A W
extension, and then linking to that file from the HTML

R
document. Here's an example:

G
A
<script src="external.js"></script>

T
A Nexternal.js:

H
// Your JavaScript code goes here

S
function myFunction() {

TI alert("Hello, World!");
}
OUR FIRST JS CODE
A L
Create a script.js file and type this example below

A W
and run this code on terminal.

G R
A
Console.log(“hello world”)

N T
HURRAY ! H A
S
YOU RUN YOUR FIRST PROGRAM

T I
AL
AW
LEVELG2
R
T A
AN
ISH
T
VARIABLES IN JAVASCRIPT
A L
In JavaScript, variables are used to store and manage data in

W
a program. Here are some key points about variables in

R A JavaScript:

AG
NT let num = 5;

HA
TIS
RULES OF VARIABLES
AL
AW
Variable names must start with a letter, an underscore ( _ ) or a dollar

GR sign ( $ ).

A
Subsequent characters can also be digits (0-9).

T
Variable names cannot contain spaces.

AN
Variables cannot be the same as reserved keywords such as if or
const .

SH
By convention, JavaScript variable names are written in camelCase.

I
T
VAR, LET & CONST
AL
AW
GR
T A
AN
ISH
T
DATA TYPES IN JS
AL
In JavaScript, there are several data types that can be used to store and
manipulate different kinds of values. Here are the main data types in

AW JavaScript:

GR
T A
AN
ISH
T
ALPrimitive Data Types:

AW
String: Represents textual data, enclosed in single or double quotes.

R
Number: Represents numeric values, including integers and floating-

AG point numbers.
Boolean: Represents either true or false.

T
Undefined: Represents a variable that has been declared but not

N
A
assigned a value.

H
Null: Represents the intentional absence of any object value.

TIS
Object Data Type:

L
Object: Represents a collection of key-value pairs. Objects can be

A
used to store and organize complex data structures.

W
RA Special Data Types:
Symbol: Introduced in ECMAScript 6 (ES6), symbols are unique and

AG
immutable values that can be used as object keys.

NT
BigInt: Also introduced in ES6, BigInt is used to represent integers of

A
arbitrary precision.

ISH Derived Data Types:

T Function: A type of object that can be invoked.


COMMENT IN JS
AL
In JavaScript (JS), a comment is a piece of text in the code that is not

W
executed or interpreted by the JavaScript engine. Comments are used for

A
adding explanatory notes or information within the code to make it more

R
readable and understandable for developers. They are ignored by the

G
browser or JavaScript runtime and are only meant for human readers.

T A
Single-line comments: These comments start with "//" (double

N
slashes) and continue until the end of the line.

A
SH
Multi-line comments: These comments start with "/*" and
I
T
end with "*/" and can span multiple lines.
AL
// This is a single-line comment
var x = 10; // Assigning a value to the variable x

AW
GR /*

T AThis is a multi-line comment.

N
It can span multiple lines without the need for

A
H
"//" on each line.

TIS */
var y = 20; // Another variable assignment
AL
AW
LEVELG3
R
T A
AN
ISH
T
OPERATORS IN JS
AL
In JavaScript, an "operator" refers to a special symbol or keyword that is used to
perform operations on operands. Operands can be variables, values, or expressions.

W
JavaScript operators are categorized into various types based on the kind of

A
operation they perform. Here are some common types of operators in JavaScript:

R
AG
NT
HA
TIS
ARITHMETIC OPERATORS
AL
W
Arithmetic Operators: Perform mathematical operations.

RA Addition: +

G
Subtraction: -

T A Multiplication: *

N
Division: /

HA Modulus: %

TIS
ASSIGNMENT OPERATORS
AL
W
Assignment Operators: Assign values to variables.

RA Assignment: =

G
Addition assignment: +=

T ASubtraction assignment: -=

N
Multiplication assignment: *=

HA Division assignment: /=

TIS
COMPARISON OPERATORS
AL
W
Comparison Operators: Compare values and return a Boolean result.

A
Equal to: == or === (strict equality)

R
G
Not equal to: != or !== (strict inequality)

A
Greater than: >

NT Less than: <


Greater than or equal to: >=

HA Less than or equal to: <=

TIS
LOGICAL OPERATORS
A L
W
Logical Operators: Perform logical operations
A
AND: &&R
and return a Boolean result.

A G
T
OR: ||

A N NOT: !

I S H
T
UNARY OPERATOR
A L
Increment: ++ A
W
Unary Operators: Operate on a single operand.

G R
T A
Decrement: --

A N
I S H
T
AL
AW
LEVELG4
R
T A
AN
ISH
T
CONDITIONAL STATEMENTS
A L
In JavaScript, conditional statements are used to make

AW
decisions in your code based on certain conditions. The most

G R
common conditional statements are if, else if, and else. Here's a
brief overview:

T A
if statement :

A N if (condition) {
// codeH

T IS to be executed if the condition is true


}
if (condition) {
if-else
L
// code to be executed if the condition is true

A
} else {
statement
W
// code to be executed if the condition is false

A
}

GR
T A if (condition1) {

N
// code to be executed if condition1 is true

A
if-else if-else } else if (condition2) {

H
statement: // code to be executed if condition2 is true

TIS } else {
// code to be executed if none of the conditions are true
}
TERNARY OPERATOR
A L
W
Ternary Operator (Conditional Operator): A
A
R
shorthand for an if-else statement.

G
Syntax: condition A
T
? expression_if_true :

A N
expression_if_false

IS H
T
SWITCH STATEMENT
AL
AW
Certainly! In JavaScript, a switch statement is a control flow

R
statement that allows you to compare a variable against multiple
G
A
values and execute code blocks based on the matching value. It

T
provides a more concise way to write multiple if...else statements.

N
HA
TIS
switch (expression) {
case value1:

L
// code to be executed if expression matches value1

A
break;

W
case value2:

A
// code to be executed if expression matches value2

R
break;

G
// additional cases as needed

A
default:

T
// code to be executed if no case matches expression

N
}

A
Here's a brief explanation of how it works:

H
The switch statement evaluates the expression.

S
If the expression matches the value in a case, the code block following that case is

TI executed.
If no case matches, the code block following the default keyword is executed
(optional).
let day = "Monday";

AL switch (day) {
case "Monday":

AW
console.log("It's the start of the week");

R
break;

G
case "Friday":

A
console.log("It's almost the weekend");

T
break;

N
default:

A
console.log("It's a regular day");

H
}

IS
In this example, since the value of day is "Monday," the code block

T
under the case "Monday": will be executed, and the output will be
"It's the start of the week."
ALERT, CONFIRM OR PROMPT

AL
W
Certainly! In JavaScript, an alert is a method that displays a dialog

A
box with a specified message and an OK button.

GR
A
A confirm is another dialog box that displays a message along with

T
OK and Cancel buttons.

AN
A prompt is similar to confirm but also allows the user to input text.

ISH
T
Alert:
A
Syntax: alert("Your message");
L
A W
G R
alert("This isA
an alert box!");
N T
H A
TIS
Confirm:
Syntax: confirm("Your message");
A L
// Code to execute if OK isA
W
if (confirm("Do you want to proceed?")) {

} else {G
R pressed

T A
// Code to execute if Cancel is pressed

A N }

I S H
T
Prompt:

L
Syntax: prompt("Your message", "Default value");
A
W
let userInput = prompt("Enter your name:", "John Doe");

A
R
if (userInput !== null) {

G
// Code to execute with user input

A
} else {

NT // Code to execute if Cancel is pressed


}

HA
TIS
AL
AW
LEVELG5
R
T A
AN
ISH
T
FUNCTIONS IN JS
AL
AW
In JavaScript, functions are blocks of

R
reusable code that perform a specific

G
A
task. They are a fundamental building

T
block of the language and are used to

N
organize and structure code. Functions

A
can be defined using the function

H
keyword.

TIS
FUNCTION WITH PARAMETER

A L
pass values into the function when W
In JavaScript, functions with parameters allow you to

Parameters are variables that actR A it is called.

the values you provide whenG


as placeholders for

T A invoking the function.

N
Here's a simple example:

H A
T IS
// Function with parameters
function greet(name) {

AL
console.log("Hello, " + name + "!");
}

AW
R
// Calling the function with an argument

G
greet("John"); // Output: Hello, John!

T A
// Calling the function with a different argument

N
greet("Alice"); // Output: Hello, Alice!

HA
In this example, the greet function has one parameter, name. When you

IS
call the function and provide an argument (e.g., "John" or "Alice"), that

T
argument is substituted for the name parameter within the function's
code.
You can define multiple parameters in a function, and when calling
the function, you need to provide values in the same order as the

AL
parameters are defined:

W
// Function with multiple parameters

RA function addNumbers(a, b) {
return a + b;

AG }

NT // Calling the function with arguments

HA let result = addNumbers(5, 7);

S
console.log(result); // Output: 12

TI
Here, the addNumbers function takes two parameters (a and b) and returns
their sum. When calling the function with addNumbers(5, 7), it adds 5 and 7,
resulting in 12.
FUNCTION WITH RETURN STATEMENT

A L
used to perform a specific task and thenW
In JavaScript, functions with a return statement are

R A return a value

G
to the calling code. The return statement is used to

T A
send a value back to the code that called the function.

N
This allows you to use the result of the function in your

H A program.

T IS
function addNumbers(a, b) {

L
return a + b;

A
}

AW
// Calling the function and storing the result in a variable

GR let sum = addNumbers(5, 3);

T A // Printing the result

N
console.log(sum); // Output: 8

HA
In this example, the addNumbers function takes two parameters

IS
(a and b), adds them together using the + operator, and then

Treturns the result using the return statement.


GLOBAL AND LOCAL VARIABLE
AL
Certainly! In JavaScript, variables can be categorized into

W
two main types: global variables and local variables.

RA
AG
NT
HA
TIS
Global Variables:

L
A global variable is declared outside of any function or block.

A
It is accessible throughout the entire code, both inside and outside

W
functions.

A
Declaring a variable without the var, let, or const keyword

GR
automatically makes it a global variable.

T A // Global variable

N
var globalVar = "I am global";

HA function exampleFunction() {

TIS console.log(globalVar);
// Accessible here
}
Local Variables:

L
A local variable is declared within a function or a block using the var,

A
let, or const keyword.

W
It is only accessible within the function or block where it is declared.

RA
function exampleFunction() {

AG // Local variable
var localVar = "I am local";

T
console.log(localVar); // Accessible here

N
A
}

ISH
// Trying to access localVar outside the function will result in an error

T// console.log(localVar); // This will throw an error


AL
AW
LEVELG6
R
T A
AN
ISH
T
LOOPS IN JS
AL
In JavaScript, loops are used to repeatedly execute a block of code as
long as a specified condition is true. There are different types of

AW
loops, but two common ones are the for loop and the while loop.

GR
T A
AN
ISH
T
For Loop:
Here's the syntax:
A L
W
for (initialization; condition; increment/decrement) {

A
// code to be executed

R
for (let i = 0; i G
}

T A < 5; i++) {

A N
console.log("Iteration
}
" + i);

IS
This for loopHinitializes i to 0, runs as long as i is less
thanT5, and increments i by 1 in each iteration.
While Loop:
AL Here's the syntax:

W
while (condition) {

RA // code to be executed

G
}

T A let i = 0;

N
while (i < 5) {

A
console.log("Iteration " + i);

H
i++;

TIS }
This while loop runs as long as i is less than 5, and
increments i by 1 in each iteration.
Do-while LOOP
AL
Certainly! The do-while loop is another type of loop in

W
JavaScript. It is similar to the while loop, but with a key

A
R
difference: the do-while loop always executes the code block

A G
at least once, and then it checks the specified condition.
Here's the syntax for the do-while loop:

N T
HA do {

S
// code to be executed

TI } while (condition);
let i = 0;

AL do {

AW
console.log("Iteration " + i);

GR i++;

A
} while (i < 5);

NT
In this example, the loop will execute at least once

HA
because the condition i < 5 is checked after the code block
is executed. As i increments, the loop will continue to

TIS
execute until the condition becomes false.
BREAK AND CONTINUE STATEMENT

AL
In JavaScript, break and continue are control flow statements used in
loops to modify the default flow of execution.

AW break:

R
The break statement is used to exit a loop prematurely, before its

AG
normal termination condition is met.
It can be used in for, while, and do...while loops.

NT for (let i = 0; i < 5; i++) {

A
if (i === 3) {

H
break;

S
}

TI console.log(i);
}
// Output: 0 1 2
continue:
The continue statement is used to skip the rest of the code inside a

AL
loop for the current iteration and move to the next iteration.

W
It allows you to skip certain iterations without terminating the entire

A
loop.

GR for (let i = 0; i < 5; i++) {

T A if (i === 2) {
continue;

AN }

H
console.log(i);

TIS }
// Output: 0 1 3 4
NESTED LOOP
AL
AW
Certainly! In JavaScript, a nested loop is a loop inside

R
another loop. This is often used when you need to iterate
G
A
over a set of data multiple times, typically with an outer loop

T
controlling the number of iterations and an inner loop

N
A
handling the individual elements.

ISH
T
for (let i = 0; i < 3; i++) {
console.log("Outer loop iteration: " + i);

AL
W
for (let j = 0; j < 2; j++) {

A
console.log(" Inner loop iteration: " + j);

R
}

G
}

T A
In this example, the outer loop runs three times, and for each iteration of
the outer loop, the inner loop runs twice. The console.log statements inside

AN both loops demonstrate the iterations.

ISH
Nested loops are commonly used when working with 2D arrays or matrices,

T
among other scenarios where you need to perform operations on each
element in a structured manner.
AL
AW
LEVELG7
R
T A
AN
ISH
T
ARRAY IN JS
AL
In JavaScript, an array is a data structure that allows you

AW
to store multiple values in a single variable. Arrays can

R
hold various types of data, including numbers, strings,
G
A
objects, and even other arrays. Here are some basic

T
operations and information related to arrays in

N
A
JavaScript:

ISH
T
Declaration: You can create an array using the following
syntax:
let myArray = [1, 2, 3, 'four', true];A
L
A W
G R
A
Accessing Elements: Array elements are accessed using

N T
their index, starting from 0. For example:

A
let firstElement = myArray[0]; // Access the first element
H
T I S
Length: You can find the length of an array using the
length property:
A L
W
let arrayLength = myArray.length;
A
Array.isArray: You can check if aR
A G variable is an array

T
using the Array.isArray method:

A N
H
let isArray = Array.isArray(myArray);

T I S
ARRAY METHODS
AL
AW
GR
T A
AN
ISH
T
Certainly! In JavaScript, array methods are functions that can be

L
called on arrays to perform various operations. Here are some

A
commonly used array methods in JavaScript:

A W
push(): Adds one or more elements to the end of an array.

G R
A
let fruits = ['apple', 'banana'];

N T
fruits.push('orange');
// fruits is now ['apple', 'banana', 'orange']

H A
T I S
pop(): Removes the last element from an array.
let fruits = ['apple', 'banana', 'orange'];
A L
W
fruits.pop();

A
// fruits is now ['apple', 'banana']
R
A G
shift(): Removes the first element from an array.

N T
let fruits = ['apple', 'banana', 'orange'];

H A fruits.shift();

T I S
// fruits is now ['banana', 'orange']
unshift(): Adds one or more elements to the beginning of

L
an array.

A
let fruits = ['banana', 'orange'];
W
A
fruits.unshift('apple');

R
// fruits is now ['apple', 'banana', 'orange']
indexOf(): Returns the index ofG
T A the first occurrence of a

let fruitsA N
specified element in an array.

H
= ['apple', 'banana', 'orange'];

T I S
let index = fruits.indexOf('banana');
// index is 1
slice(): Returns a shallow copy of a portion of an array.

A L
let fruits = ['apple', 'banana', 'orange', 'grape'];

A W
let citrus = fruits.slice(2, 4);

R
// citrus is ['orange', 'grape']
G
A
splice(): Changes the contents of an array by removing or
T
N
replacing existing elements and/or adding new elements in place.

H A
let fruits = ['apple', 'banana', 'orange', 'grape'];

T I S
// fruits
fruits.splice(2, 1, 'kiwi');
is now ['apple', 'banana', 'kiwi', 'grape']
FOR EACH LOOP
A L
W
Certainly! In JavaScript, the "for each" loop is not a

R A
standalone construct like in some other

A G
programming languages. Instead, JavaScript

T
provides the forEach method for arrays. It allows

A N
you to iterate over each element in an array and

H
execute a provided function for each element.

T I S
const array = [1, 2, 3, 4, 5];

AL
array.forEach(function(element) {

W
console.log(element);

RA });

AG
In this example, the forEach method is called on the array, and

T
the provided function is executed for each element in the

N
array. The function takes the current element as its argument,

A
H
and you can perform any desired operations within the

TIS function.
MULTIDIMENSIONAL ARRAYS
A L
W
In JavaScript, a multidimensional array is essentially
an array of arrays. You can createA
R
and work with

A G
multidimensional arrays to represent tables or

T
matrices in your code. Here's an example of how you

A N
can create a 2D array:

I S H
T
// Creating a 2D array
let twoDArray = [

AL [1, 2, 3],

W
[4, 5, 6],

A
[7, 8, 9]

R
];

AG
// Accessing elements in a 2D array

T
console.log(twoDArray[0][1]); // Output: 2

N
HA
// Modifying elements in a 2D array

S
twoDArray[1][2] = 10;

TI console.log(twoDArray);
// Output: [[1, 2, 3], [4, 5, 10], [7, 8, 9]]
AL
AW
LEVELG8
R
T A
AN
ISH
T
OBJECTS IN JS
AL
AW
In JavaScript, "objects" refer to a fundamental data type

R
that allows you to store and organize data using key-value

G
A
pairs. Objects in JavaScript can be thought of as

T
collections of properties, where each property has a key

AN
(also known as a name or identifier) and a corresponding
value.

ISH
T
let person = {

L
firstName: "John",

A
lastName: "Doe",

W
age: 30,

A
isStudent: false

GR };

A
In this example, person is an object with four properties: firstName,

T
lastName, age, and isStudent. The keys are on the left side of the colons,

N
and the values are on the right side. You can access the values of these

A
properties using dot notation or square bracket notation, like this:

H
TIS
console.log(person.firstName); // Outputs: John
console.log(person['lastName']); // Outputs: Doe
Creating Objects: You can create an object using object

L
literal notation {} or with the Object constructor.
A
AW
// Using object literal notation
let myObject = R
G
{};

T A
N
// Using Object constructor

H A
let anotherObject = new Object();

TI S
Adding Properties: You can add properties to an object
by assigning values to keys.
myObject.name = "John"; A
L
A W
R
myObject.age = 25;

object properties using dotA


G
Accessing Properties: You can access the values of

N T notation or square bracket


notation.

H A
console.log(myObject.name); // Output: John

T IS
console.log(myObject["age"]); // Output: 25
Nested Objects: Objects can contain other objects as

AL values.
myObject.address = {

AW
city: "New York",

GR zip: "10001"

A
};

NT
Methods: Functions can be added to objects as methods.

HA
S
myObject.sayHello = function() {

TI console.log("Hello!");
};
AL
Object Methods: JavaScript provides built-in methods for
objects, such as Object.keys(), Object.values(), and

AWObject.entries().

GR
A
console.log(Object.keys(myObject));

T
N
// Output: ['name', 'age', 'address', 'sayHello']

HA
TIS
FOR IN LOOP
AL
Certainly! In JavaScript, the for...in loop is used to

W
iterate over the properties of an object. Here's a basic
A
R
syntax:

A G
for (variable in object) {

N T
// code to be executed

A
}

H
variable: A variable that will be assigned the property name

TIS on each iteration.


object: The object whose enumerable properties will be
iterated.
const myObject = { a: 1, b: 2, c: 3 };

A
for (let key in myObject) { L
}
A W
console.log(key, myObject[key]);

G R
T A
This loop will iterate over the properties (a, b, c)

A N
of the myObject and log both the property name

IS H
and its corresponding value.

T
AL
AW
G
LEVEL R
9
T A
AN
ISH
T
STRING METHODS IN JS
AL
In JavaScript, string methods are functions that can be applied to
strings to perform various operations or manipulations. Here are some

AW
commonly used string methods in JavaScript:

GR
T A
AN
ISH
T
charAt(index): Returns the character at the specified
index in a string.
var str = "Hello"; A L
A W
console.log(str.charAt(1)); // Outputs 'e'

G R
T A
concat(str1, str2, ...): Combines two or more strings.

A N
var str1 = "Hello";

H
var str2 = " World";

IS
console.log(str1.concat(str2));
T
// Outputs 'Hello World'
indexOf(searchValue, startIndex): Returns the index of
the first occurrence of the specified value in a string.
var str = "Hello World"; A L
A
console.log(str.indexOf("World")); // W Outputs 6

toUpperCase(): Converts aG
R
T A string to uppercase.

A N
var str = "hello";

S H
console.log(str.toUpperCase()); // Outputs 'HELLO'
I
T
toLowerCase(): Converts a string to lowercase.

var str = "WORLD"; A L


A W
console.log(str.toLowerCase()); // Outputs 'world'

G R
A
slice(startIndex, endIndex): Extracts a portion of a string.

T
A N
var str = "Hello World";

S H
console.log(str.slice(0, 5)); // Outputs 'Hello'
I
T
replace(oldValue, newValue): Replaces a specified value
with another value in a string.
var str = "Hello World";
A L
W
console.log(str.replace("World", "Universe")); // Outputs

A
R
'Hello Universe'

A G
split(separator): Splits a string into an array of substrings

T
based on a specified separator.
N
var strA

IS H = "apple,orange,banana";
console.log(str.split(',')); // Outputs ['apple', 'orange',
T 'banana']
NUMBER METHODS IN JS
AL
AW In JavaScript, there

R
are several methods

G
and properties related

T A to numbers that you


can use for various

AN operations. Here are

H
some commonly used

TIS ones:
toFixed(): Converts a number to a string, rounding to a

L
specified number of decimal places.
let num = 3.14159;
W A
R A
let rounded = num.toFixed(2); // Result: "3.14"

A G
parseInt(): Parses a string and returns an integer.

N T
let num =A
let str = "123";

IS H parseInt(str); // Result: 123

T
parseFloat(): Parses a string and returns a floating-point

L
number.
let str = "3.14";
W A
R A
let num = parseFloat(str); // Result: 3.14

isNaN(): Checks if a value is G


T A NaN (Not-a-Number).

A N
isNaN("Hello"); // Result: true

I S H
isNaN(123); // Result: false

T
isFinite(): Checks if a value is a finite number.

isFinite(42); // Result: true A L


A W
isFinite(Infinity); // Result: false

G R
T A
Number(): Converts a value to a number.

let num A
N
let str = "42";

IS H = Number(str); // Result: 42

T
MATH METHODS IN JS
AL
In JavaScript, you can perform various mathematical operations
using built-in Math methods. Here are some commonly used

AW
Math methods in JavaScript:

GR
T A
AN
ISH
T
Math.abs(x): Returns the absolute value of a number.

A L
let absoluteValue = Math.abs(-5); // Result: 5

Math.ceil(x): Returns the smallestA


W
G R integer greater

A
than or equal to a given number.

N T
let ceilValue = Math.ceil(4.3); // Result: 5

H A
T I S
Math.floor(x): Returns the largest integer less than or
equal to a given number.

A L
A W
let floorValue = Math.floor(4.9); // Result: 4

G R
T A
Math.round(x): Rounds a number to the nearest

A N integer.

IS H
let roundValue = Math.round(4.6); // Result: 5
T
Math.random(): Generates a pseudo-random number
between 0 (inclusive) and 1 (exclusive).
A L
value between 0 andA
W
let randomValue = Math.random(); // Result: Random

G R 1

T A
Math.max(x, y, ...): Returns the largest of the given

A Nnumbers.

IS H
let maxValue = Math.max(10, 5, 8); // Result: 10
T
Math.min(x, y, ...): Returns the smallest of the given numbers.

L
let minValue = Math.min(10, 5, 8); // Result: 5

W A
Math.pow(x, y): Returns the result of raising x to the

A
power of y.

R
A G
let powerResult = Math.pow(2, 3); // Result: 8

Math.sqrt(x): Returns T
A N the square root of a number.

I S H
let squareRoot = Math.sqrt(25); // Result: 5

T
DATE METHODS IN JS
AL
Certainly! In JavaScript, the Date object is used to work with dates
and times. Here are some commonly used methods associated with

AW the Date object:

GR
T A
AN
ISH
T
new Date(): Creates a new Date object representing the

L
current date and time.
let currentDate = new Date(); A

A W
getDate(): Returns the day of theR
G
month (1-31) for the

A
specified date.
T
A
let dayOfMonth N = currentDate.getDate();

I S H
T
getMonth(): Returns the month (0-11) for the specified

L
date.

W
let month = currentDate.getMonth(); A
R A
Note: Months are zero-based, so January is 0 and
December G
A
is 11.

N
getFullYear(): Returns theT year (4 digits for 4-digit years)

H A
for the specified date.

T I
letSyear = currentDate.getFullYear();
getHours(), getMinutes(), getSeconds(): Return the hour,

L
minute, and second of the specified date, respectively.

W
let hours = currentDate.getHours(); A
A
let minutes = currentDate.getMinutes();
R
G
let seconds = currentDate.getSeconds();
A
T
toLocaleDateString(): Returns a string representing the
date portion of the N

H A Date object in a localized format.

T I S
let formattedDate = currentDate.toLocaleDateString();
AL
AW
LEVEL GR
10
T A
A N
ISH
T
DOM (DOCUMENT OBJECT MODEL)
L
In JavaScript, the Document Object Model (DOM) is a programming interface that

A
represents the structure of a document as a tree of objects. It allows scripts to

W
dynamically access and manipulate the content, structure, and style of a

A
document.

GR
T A
AN
ISH
T
Here's a basic overview of how to use the
DOM in JavaScript:
A L
W
Accessing Elements:

A
To access elements in the DOM, you can use various methods.

R
G
The most common one is getElementById to get an element by

T Aits ID:
let element =

A N
document.getElementById("yourElementId");

IS H
T
You can also use getElementsByClassName, getElementsByTagName, or
querySelector to select elements by class, tag name, or CSS selector.
getElementsByClassName:
var elementsByClassExample =
AL
document.getElementsByClassName('yourClassName');

A W
R
getElementsByTagName:
G
A
var elementsByTagExample =

T
document.getElementsByTagName('yourTagName');
N
H A
T I S
querySelector: querySelector returns the first

L
element that matches a specified CSS selector
A
var queryExample =
A W
R
document.querySelector('yourCSSSelector');

A G
T
querySelectorAll: querySelectorAll returns a NodeList

N
containing all elements that match a specified CSS selector.

A
IS H var queryAllExample =
T
document.querySelectorAll('yourCSSSelector');
INNER HTML & INNER TEXT
A L
A W
are properties used to manipulateR
Certainly! In JavaScript, both innerHTML and innerText

A G the content of HTML

N T
elements, but they work in slightly different ways.

H A
T IS
innerHTML:
innerHTML is a property that allows you to get or set the HTML content

AL inside an element.
When used to get the content, it returns a string representing the HTML

W
content of the element, including any HTML tags.

A
R
When used to set the content, it replaces the existing content with the

G
new HTML content provided.

T A // Get HTML content

N
var elementContent =

A
document.getElementById("exampleElement").innerHTML;

ISH // Set HTML content

T
document.getElementById("exampleElement").innerHTML = "<p>New
content</p>";
innerText:
innerText is a property that allows you to get or set the text content inside

AL an element.
When used to get the content, it returns a string representing the text

W
content, excluding any HTML tags.

A
R
When used to set the content, it replaces the existing content with the

G
new text content provided.

T A // Get text content

N
var elementText =

A
document.getElementById("exampleElement").innerText;

ISH // Set text content

T
document.getElementById("exampleElement").innerText = "New text
content";
Manipulating Elements:

L
You can modify elements by changing their properties.

A
For example, to change the text content:

element.textContent = "NewW
R A Text";

To change an G
T A attribute:

A N
element.setAttribute("attributeName", "attributeValue");

IS H
T
Creating and Appending Elements:

A
You can create new elements using
L
W
document.createElement and append them to the
A
R
document using appendChild:

A G
let newElement = document.createElement("div");

N T
document.body.appendChild(newElement);

H A
T IS
L
Event Handling:

A
DOM allows you to handle events like clicks,
W
A
keypress, etc. You can use addEventListener for this:

G R
T A
element.addEventListener("click", function() {

A N
// Your code here
});

IS H
T
Traversing the DOM:

A L
You can navigate through the DOM using properties

W
like parentNode, childNodes, nextSibling, and
A
R
previousSibling:

A G
let parent = element.parentNode;

N T
let siblings = element.parentNode.childNodes;

H A
T I S
Modifying Styles:

style property:
A L
You can change the styles of an element using the

A W
R
element.style.color = "red";
Manipulating G
A
Classes:

N T
Adding, removing, or toggling classes can be done

A
using classList:

IS H
element.classList.add("newClass");
Telement.classList.remove("oldClass");
EVENTS IN JS
AL
W
In JavaScript, events are actions or occurrences that happen in

A
the browser, such as a user clicking a button, resizing a window,

R
G
or submitting a form. Handling events is a crucial aspect of web

A
development for creating interactive and dynamic user

NT
interfaces. Here are some key points about events in
JavaScript:

HA
TIS
Event Types:
Mouse Events: These events occur when a user interacts with the mouse, such as

AL clicking or moving it.


Keyboard Events: Events related to keyboard interactions, such as key presses.

W
Form Events: Events like form submission.

A
Document/Window Events: Events related to the overall document or window, like

GR loading or resizing.

T A Example Code:
Adding an event listener for a button click:

AN
const myButton = document.getElementById('myButton');

ISH
myButton.addEventListener('click', function(event) {

T
// Your code to handle the click event goes here
console.log('Button clicked!');
});
AL
AW
LEVELG R
11
T A
A N
ISH
T
TEMPLATE STRINGS
AL
AW
In JavaScript, a template string is a way to create strings that

R
allows for embedded expressions and multiline strings. Template

G
A
strings are enclosed by backticks (` `) instead of single or double

T
quotes. They can contain placeholders, indicated by the ${}

N
syntax, where expressions or variables can be embedded.

HA
TIS
const name = "John";

L
const age = 30;

W A
// Using template string

R A
const greeting = `Hello, my name is ${name} and I am ${age} years
old.`;

A G
T
console.log(greeting);

In the above example,N

H A the ${name} and ${age} inside the

S
template string are placeholders that get replaced with
the I
T values of the name and age variables.
Template strings also support multiline strings without

L
the need for concatenation:

WA
const multilineString = `

RA This is a

AG multiline
string.

NT `;

HA
S
console.log(multilineString);

TI
ARROW FUNCTIONS
AL
W
Certainly! In JavaScript, an arrow function is a concise way to

A
R
write anonymous functions. Arrow functions were introduced

A G
in ECMAScript 6 (ES6) and provide a more concise syntax
compared to traditional function expressions.

N T
H A
const add = (a, b) => {

TIS return a + b;
};
REST AND SPREAD OPERATORS
A L
A W
Certainly! In JavaScript, the rest and spread

G R
operators are powerful features introduced in

T A
ECMAScript 6 (ES6) to work with arrays and objects.

A N
I S H
T
Rest Operator (...):

L
Used in function parameters to represent an indefinite

A
number of arguments as an array.

W
It collects all the remaining arguments into a single array

RA variable.

AG
T
function sum(...numbers) {

AN
return numbers.reduce((acc, num) => acc + num, 0);
}

ISH
T
console.log(sum(1, 2, 3, 4)); // Output: 10
Spread Operator (...):

L
Used to split array elements or object properties.

A
Useful for spreading the elements of an array or the properties

W
of an object into another array or object

R A
G
Example with arrays:
A
T
const arr1 = [1, 2, 3];

A N const arr2 = [...arr1, 4, 5];

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

T
Spread Operator (...):

L
Used to split array elements or object properties.

A
Useful for spreading the elements of an array or the properties

W
of an object into another array or object

R A
G
Example with Objects:
A
T
const obj1 = { a: 1, b: 2 };

A N const obj2 = { ...obj1, c: 3 };

ISH
console.log(obj2); // Output: { a: 1, b: 2, c: 3 }

T
OBJECT LITERALS
A L
A W
In JavaScript, object literals are a way to create
objects using a concise syntax.R
define and create an object G
They allow you to

T A and its properties in a

N
single declaration. Here's a basic example:

H A
T I S
let person = {

L
firstName: 'John',

A
lastName: 'Doe',

W
age: 30,

RA isStudent: false,
greet: function() {

AG
console.log('Hello, ' + this.firstName + ' ' + this.lastName + '!');

T
}

N
};

HA
In this example, person is an object literal with properties like firstName,

TIS
lastName, age, isStudent, and a method greet. You can access and modify
these properties using dot notation, like person.firstName or person.age,
and invoke the greet method using person.greet().
DESTRUCTURING ARRAY AND OBJECTS

A L
Certainly! In JavaScript, destructuringW
feature that allows you to extract R A is a powerful

G
values from arrays or

T A
properties from objects and assign them to variables in

N
a concise and readable way.

H A
T I S
Destructuring Arrays:

Basic Array Destructuring:


AL
const numbers = [1, A W
G R 2, 3];
const [a, b, c] = numbers;

T A
A N
console.log(a); // 1

ISH console.log(b); // 2
console.log(c); // 3
T
A L
W
Skipping Elements: Rest Parameter:

RA
const numbers = [1, 2, 3, 4, 5]; const numbers = [1, 2, 3, 4, 5];

AG
const [a, , b] = numbers; const [a, ...rest] = numbers;

NT
console.log(a); // 1 console.log(a); // 1

A
console.log(b); // 3 console.log(rest); // [2, 3, 4, 5]

I S H
T
Destructuring Objects:

Basic Object Destructuring:


A L
A W
const { name, age } =R
const person = { name: 'John', age: 30 };

A G person;

N T
console.log(name); // John

H A
console.log(age); // 30

T IS
Renaming Variables:

AL
const person = { name: 'John', age: 30 };
const { name: personName, age: personAge } = person;

AW
console.log(personName); // John

R
console.log(personAge); // 30

G
A
Default Values:
T
AN const person = { name: 'John' };
const { name, age = 25 } = person;

ISH
T
console.log(name); // John
console.log(age); // 25 (default value)
Thank
! you !
MADE BY ❤️BY TISHANT AGRAWAL

You might also like