0% found this document useful (0 votes)
11 views74 pages

Introduction to JavaScript Basics

JavaScript is a high-level, lightweight, and object-based scripting language used for creating interactive web pages, supporting both frontend and backend development. It has evolved since its creation in 1995, with significant updates standardized by ECMA International, and features dynamic typing and interpreted execution. The document also covers JavaScript engines, variable declaration, data types, and type coercion, providing a comprehensive overview of the language's fundamentals and functionalities.

Uploaded by

Harshitha A R
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)
11 views74 pages

Introduction to JavaScript Basics

JavaScript is a high-level, lightweight, and object-based scripting language used for creating interactive web pages, supporting both frontend and backend development. It has evolved since its creation in 1995, with significant updates standardized by ECMA International, and features dynamic typing and interpreted execution. The document also covers JavaScript engines, variable declaration, data types, and type coercion, providing a comprehensive overview of the language's fundamentals and functionalities.

Uploaded by

Harshitha A R
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

JAVA SCRIPT

❖ Introduction to JavaScript:
1. What is JavaScript?
● JavaScript is a high-level scripting as well as programming
language which is used to create interactive web pages.
● JavaScript is an object-based scripting language which is
lightweight and cross-platform
● With the help of JS we can able to add functionality and
behaviour to HTML and CSS webpages.
● It is the only language which is understood by the browser.
● JavaScript is also known as the scripting language
● A lot of framework and libraries are based on javascript. It
can be used for both frontend and backend.
1) Frontend → [Link], [Link], [Link], etc
2) Backend → [Link], [Link], etc

2. History of JS
1) Early Web Limitations :
● In the early days of the web, HTML and CSS were used to create
static web pages.
● HTML provided the structure, and CSS controlled the presentation.
● There was no way to create interactive or dynamic behavior
directly in the browser.
● Users had to reload entire pages to see updates or interact with
content, which was a significant limitation.

2) Creation of JavaScript :
● 1993 ⇒ Mosaic , the first popular web browser with a
graphical user interface, was released. It made the web
accessible to non-technical people and spurred the rapid
growth of the World Wide Web
● 1994 ⇒ The lead developers of Mosaic founded Netscape
Corporation and released Netscape Navigator , a more
polished browser.
● 1994 ⇒ The lead developers of Mosaic founded Netscape
Corporation and released Netscape Navigator , a more
polished browser.
● They collaborated with Brendan Eich to create JavaScript
● Early 1995 ⇒ The scripting language was initially called
"Mocha”
● September 1995 ⇒ Renamed "LiveScript” .
● December 1995 ⇒ Final name, "JavaScript" , was used in
Netscape Navigator 2.0.

3)ECMA
● ECMA (European Computer Manufacturers Association) , now
known as ECMA International, is an organization that develops
and publishes technical standards.
● Its role in the development of JavaScript is critical due to the need
for standardization across different web browsers.
● Since 2015, major versions have been published every June .
● ECMAScript 2024, the 15th and current version, was released in
June 2024.
● ES6 (released in 2015) → Major changes such as the addition of
arrow functions, template literals, and the let and const variable
declarations.
● ECMAScript continues to evolve and new versions are planned to
be released every year in the month of June, with new features
and improvements
● Present version is ECMA15

4)Characteristics of JS
● Light-weight Scripting Language → It’s easy to use and doesn’t
need much memory or processing power.
● Dynamic typing / Dynamically typed language →the type will be
not be specified in js
● Interpreted Language → JavaScript is primarily an interpreted
language, meaning it is executed line-by-line by the browser or
runtime environment without requiring a separate compilation step.
● Run in Browsers and Servers → Works both in web browsers and
on servers using tools like [Link]. Originally developed for client-
side scripting in web browsers, JavaScript can now also run on
servers using environments like [Link].

Working of JS Engine

1. What is JavaScript Engine?


● A JavaScript engine is simply a computer program that executes
JavaScript code.
● It’s responsible for translating human-readable JavaScript code
into machine-readable instructions that the computer’s hardware
can execute.
● When you write JavaScript code and run it in a browser, the code
doesn't directly interact with your computer's hardware.
● Instead, it interacts with the JavaScript engine, which acts as an
intermediary between your code and the underlying machine.
● Every browser has its own JS engine, but the most well known one
is Google's v8 Engine .
● This v8 Engine powers Google Chrome and also [Link] (used to
build server side applications).

[Link] JavaScript engine works?


● JavaScript is a client-side scripting language commonly used for
building interactive web pages.
● It runs in the browser (client-side) rather than on the server.
● The term "client-side scripting" means that JavaScript code is
executed in the browser (on the user's device) instead of the
server.
● Important Note: The browser (client) must support JavaScript to
execute the code.
● The browser's JS engine takes the code, processes it, and
produces the output.
Here’s how our JS file will be execute in the browser’s JS
engine:

● Programmer : Refers to the developer who writes the JavaScript


code (e.g., [Link] ). This is the source file that serves as the input
to the JavaScript engine.
● Source File ([Link]) : This is the JavaScript file containing the
code written by the programmer. It includes logic, functions, and
variables written in human-readable syntax.
● Parser : The parser is the first step in processing the source file. It
reads the JavaScript code and breaks it into tokens (smaller
pieces of meaningful code like keywords, identifiers, symbols,
etc.). Then, it generates an Abstract Syntax tree
● Abstract Syntax Tree (AST) : A tree-like data structure
representing the logical structure of the code. It breaks the code
into nodes, where each node represents a part of the code (e.g., a
variable declaration, a function call, etc.).
● Interpreter : The interpreter executes the code directly from the
AST by converting it into intermediate bytecode or directly into
machine code for execution. Interpreters are quick to start
execution but can be slower over time as they don’t optimize the
code.
● Convert into Machine Code : The optimizing compiler produces
highly efficient machine code tailored to the platform

[Link] Setup
● Where we can run js code?
➢ VS Code
➢ Node JS
Ways to Add JS
● Javascript Inside the tag
➢ You can also include JavaScript inside the tag of the HTML
file.
➢ Placing JavaScript within the section of an HTML document
ensures that the script is loaded and executed as the page
loads.

Example: <!DOCTYPE html>


<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./[Link]"></script>
</head>
<body>
</body>
html>

● Javascript Inside the tag


➢ You can embed JavaScript code directly inside the <script>
tag within the
➢ HTML document, usually inside the <body> tag.
➢ Typically, scripts placed at the end of the <body> load after
the content,
➢ which can be useful if your script depends on the DOM being
fully loaded

Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>

<body>
<script >
[Link]('====================================');
[Link](hello);
[Link]('====================================');
</script>

</body>
</html>

● External Javascript:
➢ You can write JavaScript code in a separate file (e.g.,
[Link] ) and link it to the HTML file using the <script>
tag with a src attribute.
Example:<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>

</head>

<body>
<script src="./[Link]"></script>

</body>
</html>

Fundamentals of JS
1. Tokens
Tokens are the smallest unit of any programming language that
can be understood by Javascript. When Javascript is interpreted,
the browser parses the script into these tokens.
JavaScript tokens fit in categories:
1. Keywords
2. Identifiers
3. Literals

● Keywords:
Keywords are predefined reserved words in any
programming language.

➢ Each keyword has special meaning internally.


➢ It is always written in lowercase.
➢ NOTE → Programmer cannot modify assigned task of
the keyword.
● Identifiers :
➢ Identifiers are simply names that represent variables,
function or property.
➢ They consist of a combination of characters and digits.
➢ It is usually defined by the user/programmer.
➢ Some names are already built into the JS language and are
therefore reserved these identifiers are called as “Keywords”.

Rules to define identifier:


1. Rule-1 → The first letter of an identifier must be a letter,
underscore ( _ ) or a dollar sign ( $ ).
2. Rule-2 → The whitespace cannot be included in the
identifier.
3. Rule-3 → Identifiers are case sensitive.
4. Rule-4 → Letters include all uppercase characters, “A-Z” ,
and all lowercase characters, “a-z” .
5. Rule-5 → Digits include the characters 0-9 .

● .Literals :
➢ Literals are data used to represent fixed values in
JavaScript.
➢ These are fixed values directly written into the code.
➢ Integer Literals → Integers can be expressed in either
decimal
➢ Floating-Point Literals → Floating-point literals represent
decimal numbers
➢ Boolean Literals → JavaScript implements Boolean data
types
➢ Object Literals → Object literals in JavaScript are a way to
create objects
➢ . Array Literals → Array literals in JavaScript are a way to
create Array

JS Variables
● A javascript variable is simply the name of the storage
location.
● They are container for storing data.
● Variable is nothing but the container, where we can store the
value or data.

Declaring Variables in JavaScript:


● To use a variable in JavaScript, you must first declare it.
● This means creating a variable using specific keywords: var , let
or const .
● There are 3 declaration types in JavaScript:
1. Var
2. Let
3. const
➢ var ⇒
● The var statement is the oldest way to declare
variables in JavaScript.
● Variables declared with var have function scope or
global scope, depending on where they are declared.
1. Variables can be re-declared and updated within the
same scope.
2. Can be declared without initialization.
3. Can be accessed before initialization (default value
is undefined ).
4. Variables declared with var are hoisted.

2. let ⇒
● The let statement is used to declare block-scoped variables,
meaning the variable is accessible only within the block in which it
is defined.
● Features → 1. Variables can be updated but cannot be re-
declared in the same scope.
2. Can be declared without initialization.
3. Cannot be accessed before initialization; attempting to do so
results in a ReferenceError ( Temporal Dead Zone ).
4. Variables declared with let are hoisted, but remain in the
Temporal Dead Zone until initialization.
● Const⇒ The const statement declares block-scoped variables that
` cannot be updated or re-declared.
Features →
1. Variables must be initialized during declaration.
2. Variables cannot be updated or re-declared in the same scope.
3. Cannot be accessed before initialization; attempting to do so
results in a ReferenceError (Temporal Dead Zone).
4. Variables declared with const are hoisted, but remain in the
Temporal Dead Zone until initialization.
Scopes:
- scope is the area where a variable exist and accessable
1. Block Scope: - Whenever we are declaring a variable with let, or
const inside the curly braces is known as block scope.
- Those variables that are declared inside the function have local or
function scope which means that we cannot access outside of the
function.
2. Function Scope: - Whenever we are declaring a variable with var,
const or let then that particular variable is under function scope.
- Those variables that are declared inside the function have local or
function scope which means that we cannot access outside of the
function.
3. Script Scope: - When we are declaring a variable with let or const
outside the function and curly braces then that particular variable is
under script scope.
4. Global Scope: - Whenever we are declaring a variable with var type
declaration outside of the function and this variable is stored inside the
window object then we are calling this variable under the global scope.
- Those variables which are declare outside of the function are inside the
global scope. - In JavaScript global variable can be accessed from
anywhere.

Data Types:
- JavaScript is a dynamically typed language which means you do not
need to specify the type of data that particular variable can hold. The
type is determined at runtime based on the value assigned to the
variable .
1. Primitive Data Types - In JavaScript primitive datatype is the data
that is not an object and has no methods or properties. - The primitive
datatypes are single value

- The types of primitive datatypes are


i) Boolean
ii) String
iii) Number
iv) Undefined
v) Null
vi) Big int (introduced in ES6)

Number:
➢ Number datatype can use decimal as well as non-decimal values.
➢ Ex: var a = 10;
let myage=22;
String: -
The string datatype in the JavaScript represents a sequence of
characters that are surrounded by single or double quotes and template
literals (`Dhanush`)
- Typically, it is used to represent the text.
- Ex: var fname=” Dhanush”
- Var lname = ‘Pagolu’
- Var fullname=`full name is ${fname} ${lname}`

▪ Boolean
1. Java script Boolean represent true or false values
2. It is used for logical operations, conditional testing and variable
assignments based on conditions.
3. values like 0, Nan (not a number), Empty string (“”), undefined are the
falsie values.
4. Non empty strings other than 0, objects and array are truthy values.
Note: A falsie value is a value that is considered as false when
encountered in Boolean context.

▪ Undefined:
1. This means that a variable has been declare but has not been
assigned a value or it has been explicitly set to the value undefined.
2. let a = undefined
3. [Link](a); //undefined

▪ Big Int:
1. In JavaScript big int is the numeric datatype that can represent
integers in the arbitrary precession format. [no limit in range of numbers]
2. Big int value is also known as big int primitive value which is created
by appending ‘n’ to an integer literal.

▪ Null:
1. Null is an empty value.
2. Null is not same as the zero.
3. Null is the absence of any value.
4. Ex: [Link] (null == undefined) //true
5. Ex: [Link] (null === undefined) // false

Type Coercion: - Type coercion is also known as implicit type


conversion. - Implicit conversion:
▪ In the java script values of different datatypes automatically converted
to a common type before an operation is performed.
- This can be sometimes led to unexpected result or expected results if
not understood properly.
- Type coercion scenarios:
i) Arithmetic operations: - Combination of numbers and string:
let a=10;
let b=’11’;
let c=a+b; //string
[Link](c); // ’1011’
-------------------------------------
let x=” true”
[Link](x+5); //’true5’
--------------------------------------]
let u=12
[Link] (“Dhanush” +u) //” Dhanush12”
ii) Comparison Operator:
Ex: [Link] (10 == ‘10’) // true
[Link] (10 === ‘10’) //false
[Link] (false == 0) //true

iii) Strict equality operator (===): Avoiding coercion to avoid the


unexpected behaviour from type coercion use the strict equality
operator. It checks both value and datatype.
[Link] (10 === ‘10’) //false
[Link] (10 === 10) //true

Falsie values in JavaScript: Null, undefined, 0, NaN

Type conversion:
- In JavaScript type conversion is the process of changing the value of
one data type to another datatype.
- It is essential for performing operations and comparisons between
different datatypes
- Explicit Conversion: You can manually convert datatypes using built
in functions like Number (), String (), Boolean ().
- Common Explicit type conversion: Scenarios:
1) Number to String:
Ex: here we are converting the number datatype into string by using
String () built in function:
Let a = 1001
Let d=String(a)
[Link](d) //”1001”
[Link] (typeof d) //string
2) String to Number:
Ex: here we are manually converting the string datatype to number
Let a = “1001”
Let b=Number(a)
[Link](b) //1001

Decision Making Statements:


1.) If statement: It is used for some statement has to be executed
based on the single condition.
Syntax:
if(condition)
{ //statements }
Ex: let cookiesAvaliable=1
if (cookiesAvaliable == 1)
{
[Link] (“I will eat one cookie”);
}
If (cookiesAvaliable == 2) // error
2.) If else statement - It is use when some set of code has to be
executed based on some condition otherwise some other set of code is
executed.
- If statement tells us that if a condition is true, it will execute a block of a
statement and if the condition is false else block get executed. -
Syntax: if(condition)
{
//statements
}
else{//condition}
3.) Else if ladder: - It is used when some set of statements has to be
executed based on hierarchical conditions - If none of the conditions is
true then the final else block gets executed.

SYNTAX:
if(condition)
{
//statement
}
else if(condition)
{
// statement
}
else{
//statement
}

4.) Switch Statement:


- It is used when multiple conditions have to be evaluated based on
single variable expression.
- The switch statement evaluates an expression matching the switch
value against the series of cases values and execute the statement after
the first case matching value until a break statement is encountered.
- The default case of switch statement will be jump to if no case matches
with the switch value
- Syntax :
Switch(expression)
{
case 1: //statements
break;
case 2: //statements
break;
default: //statements
break;
}
Note: 1.) The switch statement accepts n number of cases
2.) Cases are case-sensitive
3.) Default value has the least priority.
4.) The cases must be constant and unique.
5.) The cases cannot be variable or expression.
6.) The execution will flow through each case if break is missing in the
satisfied case.

5.) Looping Statement: -


Whenever we want to perform a task repeatedly that time we can go with
the looping statement.
- There are different types of looping statement in JavaScript.
1.) for loop
2.) while loop
3.) do while loop

1) for loop: -
for loop it is used to execute set of statements repeatedly it is commonly
used when we know how many times the loop needs to be executed.
- Syntax:
for (initialization; condition; updation)
{
//set of statements
}

2) While loop: -
It loops through a block of code as long as specified condition is true.
- It commonly used when you don’t know how many times you want to
execute a block of code and it is based on the condition.
- Syntax:
Initialization
While(condition)
{
//statements
//updation
}

3) Do while loop:
- Do while loop will execute code of block once before checking the
condition.
- If the condition is true then it will repeat the loop as long as the
condition is true, and once condition is false it will stop the execution of
the block
- It is commonly used when you have to execute the loop at least once

- Syntax:
Initialization do {
//statements
//updation
} while(condition);

FUNCTIONS
- Reusable block of code that perform specific task.
- Define with function keyword, name, parameters (optional) and a body
of code in curly braces.
- Called by using the function name and passing the argument (optional)
- Syntax:
- function funcitonName (list of arguments)
{
//statements
}
functionName (list of arguments);

Example:
function sayHello(name)
{
[Link] (`Hello ${name}`)
}
sayHello("Dhanush")

Types of Functions:
1.) Named Function: -
This is the most common way of defining named function.
- Syntax:
function funcitonName (list of arguments) {
//statements
}
functionName (list of arguments);
Example:
function sayHello(name) {
[Link] (`Hello ${name}`)
}
sayHello("JavaScript");

2) Declaration Function: -
Declaration function is hoisted, which means they can be used before
they defined in the code
- Example: function mul (a, b) {
[Link](a*b)
}
mul (10,20)
3)Function Expression - Whenever we are storing any function into a
variable then it is called as function expression.
- Syntax:
var a = function () {
//body
}
a ();
- Example 1:
let a = () => {
[Link] ("This is arrow function")
}
a ();

Example 2:
let even=function(num) {
for (let i=2; i<=num; i+=2)
{ [Link](i) }
}
even(num);

3.) Anonymous Function: -


A function declared without an identifier is known as anonymous
function.
- To execute anonymous function, we have to store them into one
variable. - Syntax: function () {
//body
}
- Example: let a = () => {
[Link] ("This is arrow function")
}
- To execute this function, we need to store the function in the variable
and we need to invoke using that variable

4) Immediate Invoking function Expression (IIFE):


- IIFE function that is defined and executed immediately.
- Syntax: (function () {
//code inside IIFE
}) ();

- Example 1:
(function () {
[Link] ("this is immediate invoking functions")
}) ();
//semi colon is mandatory if not given next IIFE function won’t
execute
(function () {
[Link] ("this is iikf 2")
})();
- Example 2:
(function () {
let secretMessage="Chocolate is in the freezer"
function showSecretMessage(secretMessage)
{
[Link](secretMessage)
}
showSecretMessage(secretMessage)
})();

[Link] Function:
- It is an advanced function.
- It will reduce the code
- To execute this function, we have to store it in a variable.
- Arrow functions are concise way to write functions in JavaScript which
is introduced in ES6.
- They provide a cleaner syntax and can be especially useful for short
syntax, anonymous function.
- Syntax 1: (parameters) => {
//code to be executed
}
- Key points of arrow functions
1.) Concise syntax:
(i) For single line functions with a single expression, you can avoid the
curly braces and return keyword.
(ii) Ex: const square = (x) => x*x;
(iii) For a functions with multiple statements/ expressions or a block of
code we need to use curly braces and return keyword if we have to
return the value from that function.

2.) Implicit return: (i) As mentioned, if you omit the curly braces the
expression is implicitly returned.
(ii) Ex: let add = (a, b) => a+b [Link] (add (10,20))
3.) Parameter handling:
(i) If you have a single parameter you can omit the parenthesis.
(ii) Ex: let greet = name =>{ [Link](`goodafternoon ${name}`) }
greet ();
(iii) If you don’t have any parameter then you can use underscore (_) or
$. (iv) Ex: let greet = _ => [Link] (`good afternoon ${name}`)

4.) This keyword:


(i) Arrow function inherit this value from their enclosing scope unlike
regular functions.
(ii) This can be helpful in some scenarios especially when dealing with
even handlers or asynchronous operations.

[Link] Function:

- It is a function which sends as a parameter to another function. ▪


(or) - callback functions are functions that are passed as a to
arguments to another function
- Syntax:
function callbackFunction ()
{
//Set of statements
}
function mainfunciton (callback)
{
return Callback ();
}
- Example:
function add (a, b) {
return a+b;
}
function Calculate (callback, a, b)
{
return callback (a, b)
}
let res=Calculate(add,10,20)
[Link](res)
- You can send any function as the callback function.

6.) Higher order function: -


It is a function which will accept another function as an argument
(or) it will return another function is called as Higher order function.
Syntax:
function callbackFunction () {
//Set of statements Higher Order function
}
function mainfunciton (callback)
{
return Callback ();
}

- Example:
function add (a, b) {
return a+b;
}
function Calculate (callback, a, b) {
return callback (a, b)
}
let res=Calculate(add,10,20)
[Link](res)

- Example 2:
function areaOfSquare(a)
{
return a*a;
}
function mainFun (callback, a)
{
return callback(a)
}
let a=10;
[Link] ("The area of square is”, mainFun (areaOfSquare, a)) -
There are some inbuilt higher order functions present JavaScript
map, reduce and filter, setTimeOut, setInterval, for each.

7) Immediate Invoking function Expression (IIFE):

- IIFE function that is defined and executed immediately.


- Syntax: (function () { //code inside IIFE }) ();

- Example 1:
(function () {
[Link] ("this is immediate invoking functions")
}
) (); //semi colon is mandatory if not given next IIFE function
won’t execute
(function () { [Link] ("this is iikf 2") })();

- Example 2:
(function () {
let secretMessage="Chocolate is in the freezer" function
showSecretMessage(secretMessage)
{
[Link](secretMessage)
}
showSecretMessage(secretMessage) })();
- It is used to create a private scope encapsulate variables and
functions and avoid polluting the global name space
- How it works:
o The function () part defines an anonymous function.
o Grouping Operator, the outer parenthesis groups the function
expression.
o Immediate invocation the final pair of parentheses immediately
invokes the function

. What is arguments Object?


➢ In traditional functions (not arrow functions), JavaScript provides an arguments
object which is an array-like object representing the passed arguments.
For Example
It will return array-like object but it not an actual array.
NOTE:
There is no arguments object for arrow function for that you have to
use …rest parameter

8) Nested Function:
A function which is present inside another function is called as Nested
Function.
It can access variables from the outer function.
That is something called as Closure function.
For Example →
9) What is Closure Function?
➢ A closure in JavaScript is a feature where a function
"remembers" its
lexical environment (the variables from the scope where it was
created) even after it is executed outside of that scope.
➢ Simply put, closures allow inner functions to access variables
from their outer function, even after the outer function has
finished execution.
NOTE: A closure is a function that has access to its own scope,
the scope
of the outer function, and the global scope.
⚫ When Closure Function will be Created?
A closure itself is not an object; it is a function. Specifically, a
closure
occurs when a function is created inside another function and
retains
access to the variables from the outer function's scope, even
after the
outer function has finished execution.
.

JS Strings
What are Strings in Javascript?
⚫ The string is the collection of characters.
⚫ Strings are immutable, means their content cannot be changed once created.
⚫ However, you can create a new string based on an existing one.
⚫ They are one of the most commonly used data types and can include letters,
numbers, symbols, and even emojis

2. Ways to Create Strings


There are two ways to create a string in Javascript:
1. Using String Literal
a. By Using Single Quotes
b. By Using Double Quotes
c. By Using Template Literals (Backticks)

2. Using String Object


1. Using String Literal
String literals are the most common way to create strings in JavaScript.
They are direct, simple, and concise.
JavaScript allows you to use single quotes ( '' ), double quotes ( "" ), or template
literals ( `` ) to define string literals.

1.1 By Using Single Quotes


You can enclose text in single quotes ( '' ).
For Example →

1.2 By Using Double Quotes


You can enclose text in double quotes ( "" ). It works the same as single
quotes but allows you to include single quotes inside the string without
escaping.
For Example →

1.3 By Using Template Literals ( Backticks )


Template literals, enclosed by backticks ( `` ), allow for more flexible
and advanced string handling. They support:
String interpolation (embedding expressions)
Multi-line strings

For Example → String interpolation


For Example → Multi-line strings

3. Using String Object


A string can also be created using the String() constructor, which creates an object
representing a string.
Syntax → let str = new String('Your text here');

3. String Length Property


The length property is used to determine the number of characters in a
string. This includes spaces, special characters, and punctuation.
The length property is read-only and directly gives the total number of
characters in the string.
Syntax →[Link]
For Example →
Methods of Strings
1. at() ⇒
Returns the character at a specified position (positive or negative index).
Syntax →[Link](index)
For Example →

2. charAt()⇒
Returns the character at a specified index (only positive index allowed)

Syntax →💡
[Link](index)
Return Type:
String
For Example →

3) concat()⇒
Concatenates one or more strings and returns a new string.
Syntax → 💡
[Link](str1, str2, ...)
Return Type:
String
For Example →

4)includes()⇒
Checks if a string contains a specified substring.
Syntax →
[Link](substring, startIndex)
Return Type:
Boolean
For Example →

.
5)indexOf()⇒
Returns the first occurrence index of a substring, or -1 if not found.
Syntax →
[Link](substring, startIndex)
Return Type: Number
For Example →
6)lastIndexOf()⇒
Returns the last occurrence index of a substring, or -1 if not found.
Syntax →

💡[Link](substring, startIndex)
Return Type:
Number
For Example →

7)slice()⇒
Extracts a section of a string and returns it as a new string.
Syntax →

💡
[Link](startIndex, endIndex)
Return Type: String
For Example →

8)split()⇒
Splits a string into an array based on a specified separator.
Syntax →

💡
[Link](separator, limit)
Return Type:
Array
For Example →
9)subString()

Extracts a part of a string between two specified indexes.
Syntax →

💡
[Link](startIndex, endIndex)
Return Type:
String
For Example →

10)toUpperCase()⇒
Converts a string to uppercase.
Syntax →

💡
[Link]()
Return Type:
String
For Example →
11)toLowerCase()⇒
Converts a string to lowercase.
Syntax →

💡
[Link]()
Return Type:
String

12)trim()⇒
Removes whitespace from both ends of a string.
Syntax →

💡
[Link]()
Return Type:
String
For Example →
13)trimStart()⇒
Removes whitespace from the beginning of a string.
Syntax →

💡
[Link]()
Return Type:
String
For Example →

14)trimEnd()⇒
Removes whitespace from the end of a string.
Syntax →

💡
[Link]()
Return Type:
String
For Example →

15)toString()⇒
Converts a string object to a primitive string.
Syntax →

💡
[Link]()
Return Type:
String

Task-1: Reverse a String


Goal: Reverse the characters of a given string.
For Example →

Task-2: Validate Email Address


Goal: Check if a string is a valid email format and belongs to a specific
domain (e.g., @[Link] )
For Example →

Task-3:Check if a Word is a Palindrome or not


Goal: Determine if a given string is a palindrome (reads the same
backward as forward).
For Example →
JS Array
An array in JavaScript is a special type of object used to store multiple
values in a single variable.
In simple words we can say that, array is the collection of data which may be
homogenous or heterogenous.
Arrays allow us to group and organize data efficiently, making it easy to
manipulate and access elements.
Types of Arrays:
1. Homogenous Array: The array which contains the same type of
elements.
For Example → All Numbers, All Strings, etc.

2. Heterogenous Array: The array which contains the different types of


elements.
For Example → Combination of numbers, strings, function, objects,
etc.
2. Ways to Create Arrays
We can create array in main two ways:
1. By Using Array Literal
2. By Using Array Constructor

1. By Using Array Literal ( [] )


The most common and straightforward way to create arrays is by using
array literals.
Syntax →

💡
let arrayRefVar = [value1, value2, value3, ..., valueN];
For Example →

Accessing Elements of an Array: You can access elements using their


index (zero-based).
2. By Using Array Constructor ( new Array() )
The Array constructor allows you to create arrays dynamically.
let myArray = new Array(5); // Creates an array with 5 empty elements
let myArray = new Array(1, 2, 3); // Creates an array with 3 elements

1. push()⇒
Adds one or more elements to the end of an array and returns the new
length of the array.
Syntax →

💡 [Link](element1, element2, ..., elementN)


Return Type: Number (new length of the array).
For Example →

2. pop()⇒
Removes the last element from an array and returns it.
Syntax →

💡
[Link]()
Return Type: The removed element, or undefined
if the array is empty.
For Example →
3. shift()⇒
Removes the first element from an array and returns it.
Syntax →

💡
[Link]()
Return Type: The removed element, or
undefined
if the array is empty.
For Example →

4. unshift()⇒
Adds one or more elements to the beginning of an array and returns the
new length of the array.
Syntax →

💡
[Link](element1, element2, ..., elementN)
Return Type: Number (new length of the array).
For Example →

5. slice()⇒
Returns a shallow copy of a portion of an array into a new array.
Syntax →

💡
[Link](startIndex, endIndex)
Return Type: New array
For Example →

6. splice()⇒
Changes the contents of an array by removing, replacing, or adding
elements.
Syntax →

💡
[Link](startIndex, deleteCount, item1, item2, ...)
Return Type: The Array of removed elements.
For Example →

7. concat()⇒
Merges two or more arrays into a new array.
Syntax →

💡
[Link](array1, array2, ..., arrayN)
Return Type: New array.
For Example →

8. reverse()⇒
Reverses the order of elements in an array.
Syntax →

💡
[Link]()
Return Type: The original array (reversed).
For Example →

9. join()⇒
Joins all elements of an array into a string, separated by a specified
separator.
Syntax →

💡
[Link](separator)
Return Type: String
For Example →

10. indexOf()⇒
Returns the first index of a specified element in the array, or
-1
if not
found.
Syntax →
💡
[Link](searchElement, fromIndex)
Return Type: Number (index)
For Example →

11. lastIndexOf()⇒
Returns the last index of a specified element in the array, or
-1
if not
found.
Syntax →

💡
[Link](searchElement, fromIndex)
Return Type: Number (index)
For Example →

12. includes()⇒
Determines whether an array includes a certain element.
Syntax →

💡
[Link](searchElement, fromIndex)
Return Type: Boolean (
true
if it is present otherwise false )
For Example →

JS Array Iteration Methods


(map,filter, reduce,forEach)

1. What Are Array Iteration Methods?


Array iteration methods in JavaScript are built-in functions that allow us to
loop through arrays and perform specific operations on each element.
These methods simplify array manipulation tasks such as transforming
elements, filtering values, reducing arrays to a single value, or simply
executing a function on every element.
Why Use Array Iteration Methods?
Readable: These methods make the code easier to read and understand.
Efficient: They save us from writing traditional
for
loops.
Flexible: Provide ways to work with data transformation, filtering, or
aggregation without modifying the original array (except forEach ).

2. Types of Array Iteration Methods?


There are 3 main popular types of array iteration methods used for Array:
1. map()
2. filter()
3. reduce()
We will se each and every method in detail. let’s see:

3. map()
The map() method creates a new array by applying a given function to
every element in the array.
It does not modify the original array.
It iterates through each element of the array and invokes a callback
function for each element.
The result of the callback function is then added to the new array.
Syntax →

💡
[Link]((cValue, cIndex, cArray) => {
// return new value for the current element
});
Parameters:
1.
currentValue
: The current element being processed.
2.
currentIndex
(optional): The index of the current element.
3.
currentArray
(optional): The original array.
Return Type: Returns a new array with transformed elements.
For Example →
Key Points:
The original array remains unchanged.
Used for transformation purposes

4. filter()
The filter()method creates a new array containing all the elements that
pass a certain condition (provided in a callback function).
It iterates through each element of the array and invokes the callback
function for each element.
If the callback function returns true for an element, that element is
included in the new array; otherwise, it is excluded.
It filters out unwanted values

Syntax →

💡
[Link]((cValue, cIndex, cArray) => {
// return true to keep the element, false otherwise
});
Parameters:
1.
currentValue
: The current element being processed.
2.
currentIndex
(optional): The index of the current element.
3.
currentArray
(optional): The original array.
Return Type: Returns a new array containing elements that satisfy the
condition.
For Example →

Key Points:
The callback function must return a boolean ( true or false ).
Useful for removing unwanted elements.

5. reduce()
The reduce() method executes a reducer function on each element of the
array, resulting in a single output value.
The callback function takes four arguments: accumulator, currentValue,
currentIndex, and the array itself.
It is ideal used for aggregating array elements into a sum, product, or other
computation.
Syntax →

💡
[Link]((accumulator, cValue, cIndex, cArray) => {
// logic to aggregate values
return updatedAccumulator;
},
initialValue);
Parameters:
1.
accumulator
: The accumulated result from the previous iterations.
2.
currentValue
: The current element being processed.
3.
currentIndex
(optional): The index of the current element.
4.
currentArray
(optional): The original array.
5.
initialValue
(optional): The initial value of the accumulator (default is
the first element of the array).
Return Type: Returns the final accumulated (Single) valu

6. forEach()
The forEach()method executes a provided function once for each array
element. Unlike map() , it does not return a new array. It is primarily used for side
effects (e.g., logging or updating external data).
Syntax →

💡
[Link]((cValue, cIndex, cArray) => {
// perform an operation for each element
});
Parameters:
1.
currentValue
: The current element being processed.
2.
currentIndex
(optional): The index of the current element.
3.
currentArray
(optional): The original array.
Return Type: Undefined. It does not return anything.
For Example →
Key Points:
Does not return a new array.
Best for executing a function on each element without modifying the array

JS Objects
1. What is Object in Javascript?
In Javascript object is a collection of multiple different properties in the form of key-value
pairs.
An object is a programmatical representation of real life entity.
Property → It is the combination of key and value pair

Why we need to use object in JS?


Using objects in JavaScript is essential because they provide a powerful and flexible way to
organize, manage, and manipulate data in your code.
Objects are fundamental to JavaScript as they enable you to represent real-world entities,
model data structures, and implement functionality
Objects let you store data as key-value pairs, making it easier to understand what each value represents.
Ways to Accessing the Object Properties
For Example → Object Creation

Accessing Object Properties:


There are 2 ways we can access the object properties:
1. By Using Dot ( .) Notation →
The dot notation is the most common way to access properties, but it doesn't
work for special keys.
For Example →

2. By Using Square Bracket ( [ ] ) Notation →


The bracket notation is used when:
The key is dynamic.
The key has special characters or spaces.
The key consist of only number.
For Example

Ways of Creating Object


We can create the object various ways so let’s see one by one:
1. By Using Object Literals
2. In-built Object Constructor
3. Functional Constructor
[Link]()

1. By Using Object Literals ⇒


The most common and straightforward way to create an object is using an object literal.
It is defined with curly braces { }
For Example →
2. In-built Object Constructor ⇒
JavaScript provides a built-in Object() constructor that can be used to create objects.

3. Functional Constructor ⇒
A functional constructor is a function that is used to create and initialize objects when
called with the new keyword.
You can define a custom constructor function to create multiple objects with the same
structure.
[Link]() ⇒
Create a new object by copying properties from one or more existing objects

Method in Javascript
1. What is a Method in JavaScript?
In JavaScript, a method is simply a function that is stored as a property of an object.
A method is essentially a function that belongs to an object.
. Different Ways to Define Methods
Important Note: Arrow Functions and this

In the example above, [Link]'t work as expected because thisinside an arrow function does not refer
to the object ( obj ). Instead, it refers to the surrounding scope
4. Correct Way to Use this in Object Methods
To make sure the method works correctly and accesses the object properties using
this you should avoid using arrow functions as methods.
Always use regular function syntax (or ES6 shorthand) to define methods inside objects

Object In-built Methods


1. [Link]() ⇒
The [Link]() method copies properties from one or more source objects to a target
object.
Objects are assigned and copied by reference.
Syntax →

💡
[Link]( target_object, sources );
Return Type → It will return the target object.
For Example →

2. [Link]() ⇒
The [Link]() method prevents additions or deletions of new properties.
But we can modify the property.
Syntax →

💡
[Link]( obj );
Return Type → It will returns the object which has been sealed.
For Example →

3. [Link]() ⇒
The [Link]() method can be used to check if an object is sealed.
The [Link]() returns trueif an object is sealed.
Syntax →
[Link]( obj )

4. [Link]() ⇒
The
[Link]()
method prevents any changes to an object.
Frozen objects are read-only.
The
[Link]()
method freezes an object that we can not add new property, modify the
property and delete the property.
Syntax →

💡
[Link]( obj );
Return Type → It will return the frozen object.
For Example →

5. [Link]() ⇒
The
[Link]()
checks the passed object is frozen or not.
Syntax →

💡
[Link]( obj );
Return Type → It will return the boolean value
true
if the object is frozen and
false
if not.
For Example →
6. [Link]() ⇒
The [Link]() method returns an array with the keys of an object.
The [Link]() method does not change the original object.
Syntax →

💡
[Link]( obj );
Return Type → It will return an array containing the keys of the object.
For Example →

;
8. [Link]() ⇒
The [Link]() method returns the each key and value pair in the form of array.
(nested array) Get an array of [key, value] pairs.
The [Link]() method does not change the original object.
Syntax →

💡
[Link]( obj );
Return Type → It will return an iterable array of the object in the form of key-value pairs.
For Example →
9. [Link]() ⇒
The [Link]() method creates an object from a list of key-value pairs.
Syntax →

💡
[Link]( arr );
Return Type → It will return object created from the key-value pairs.

Changing the Key Name ⇒


It will create a new object, instead of replacing the key name.
For Example →
Rest Parameter and Spread Operator
1. Rest Parameter:
Collects all remaining parameters in an array.
The rest parameter is used when defining a function to gather all
remaining arguments into an array.
This allows you to handle an indefinite number of arguments.
It is used inside a function definition

2. Spread Operator
The spread operator is used to spread or unpack the elements of an
array (or object) into individual elements.
This is typically used when calling a function, or when creating a copy
of an array or object.
It is used inside a function call, or when copying arrays/objects.
Spread Operator spreads the values in a new container and creates a
shallow copy
Example-1: Arrays

Example-2: Objects

Example-3: Strings
It will spread each and every character from the given string.

1. Array Destructuring ⇒
Rest Parameter in Destructuring:

2. Object Destructuring ⇒
Synchronous vs
Asynchronous
Javascript
1. What is Synchronous Javascript?
In synchronous JavaScript, code is executed line by line in the order it
appears.
If a task takes time (e.g., reading a file or fetching data from a server), it
blocks the execution of the following lines until the task is completed.

2. What is Asynchronous Javascript?


Asynchronous JavaScript lets you handle tasks that take time (like fetching
data from a server or reading a file) without stopping the rest of your code
from running.
Instead of waiting for the task to finish, JavaScript moves on to the next
thing and comes back to the task when it's done.
Once the task is finished, a callback or event notifies the program

Ways to Implement Asynchronous


JavaScript
1. Timing Functions:
Functions like setTimeout()and setInterval()are used to delay or
repeatedly execute tasks.
2. Promises (ES6):
A cleaner way to handle asynchronous tasks by representing a future
value or result.
3. async and await:
Syntactic sugar for Promises, making asynchronous code easier to
read and write.
4. Fetch API:
A modern way to make network requests and retrieve resources
asynchronously

1. What is Timing Functions in JS?


Timing functions in JavaScript allow us to execute a block of code after a
certain delay or repeatedly after specific time intervals.
They are essential for creating delays, repeated tasks, or handling time
based actions in web applications

Types of Timing Functions


JavaScript provides four main timing functions:
1. setTimeout()
2. setInterval()
3. clearTimeout()
4. clearInterval()

. setTimeout()
The setTimeout() executes the function once after a specified delay (in
milliseconds).
The setTimeout() is executed only once.
Syntax →

💡
let timerId = setTimeout(callback, timeInMilliseconds);

clearInterval()
The clearInterval() stops a repeating task set by
setInterval()
Syntax →
clearInterval(intervalId);
setInterval()
The setInterval() executes the function repeatedly at specified time
intervals (in milliseconds).
Syntax →

💡
let intervalId = setInterval(callback, timeInMilliseconds);
Use case: Perform tasks repeatedly (e.g., updating a countdown or clock).
For Example →

. clearTimeout()
The clearTimeout() stops a timeout set by setTimeout()
.
Syntax →

💡
clearTimeout(timerId);
Use case: Cancel a delayed task if it's no longer needed.
For Example →

JS Promises
What is a Promise?
A Promise in JavaScript is an object that represents the eventual
completion or failure of an asynchronous operation and its resulting value.
The Promise Object represents the completion or failure of an
asynchronous operation and its results.
States of a Promise:
1. Pending: The promise is in its initial state, neither fulfilled nor rejected.
2. Fulfilled: The promise is successfully completed, and the resulting value is
available.
3. Rejected: The promise failed, and an error or reason is available.

Creating a Promise
ou can create a promise using the Promise constructor.
The syntax is:

💡
let myPromise = new Promise((resolve, reject) => {
// Perform some asynchronous task
// Call resolve() if successful
// Call reject() if there's an error
});

resolve
is a function used to mark the promise as fulfilled.
reject
is a function used to mark the promise as rejected.

. Promise Instance Methods


then() Handles the fulfilled (success) state.
catch(): Handles the rejected (failure) state.
finally(): Executes code no matter what (fulfilled or rejected).

Promise Chaining
Promise chaining allows you to perform a sequence of asynchronous
tasks where the next operation starts only after the previous one finishes
JS Fetch API
What is the fetch API?
The fetchAPI is a modern way provided by browsers to fetch resources
from servers (like APIs, files, etc.).
It allows you to make network requests and retrieve data (e.g., JSON data from an
API or a webpage).
The fetch API is built on promises, making it easier to handle
asynchronous operations.

How to Use the fetch API


There are two common ways to use the fetch API:
1. Using
.then() and .catch() for promise chaining.
2. Using asyncand await for a cleaner, synchronous-looking style
Using .then() and .catch()

Using async and await


JS async and await
. What are asyncand await ?
. async:
The async keyword is used to declare a function that always returns a
Promise.
The returned promise can resolve (fulfilled) or reject, depending on the
outcome of the function.
2. await:
The await keyword makes the function pause execution until the
promise is resolved (fulfilled or rejected).
It can only be used inside an async function.

Async ensures a function always returns a promise.


2. await pauses the execution until a promise is resolved.
3. Using try...catch inside an
async function allows you to handle errors (rejected promises).

JSON (JavaScript Object


Notation)
1. What is JSON ?
JSON stands for JavaScript Object Notation.
It is a format for structuring data.
It is a lightweight data-interchange format used for storing and exchanging data.
JSON is text-based and easy for humans to read and write while being
machine-readable

Key Terms:
Collection: A collection of documents.
Document: A collection of fields (fields are key-value pairs).

How to Create JSON?


Rules for JSON:
Data is represented as key-value pairs.
Keys must be strings enclosed in double quotes.
Values can be strings, numbers, objects, arrays, booleans, or
null

JSON Methods in JavaScript


There are 2 main popular JSON methods used widely:
1. [Link]()
2. [Link]()
1. [Link]()⇒
[Link]()
converts a JSON string to a JavaScript object.
It accepts a JSON string as input.
When receiving data from a web server, the data is always a string.
Parse the data with
[Link]()
, and data becomes a Javascript Object.

Syntax:💡
[Link](string)
2.
[Link]()

converts JavaScript objects into JSON strings,
[Link]()
accepting a single object argument.
When sending data to a web server, the data has to be a string format.
Convert a javascript object into a string with
[Link]()
.
Syntax →
[Link](object)

JS Browser Object Model (BOM)


What is BOM in JavaScript?
The Browser Object Model ( BOM ) refers to the set of objects provided by
the browser to interact and manipulate the browser window.
BOM allows JavaScript to communicate with the browser

BOM Objects
The key objects in the Browser Object Model are:
1. Window: The main global object representing the browser window/tab.
2. Document: Represents the HTML document loaded in the window.
3. Screen: Provides information about the user's screen (like width,
height, etc.).
4. Navigator: Contains information about the browser (user agent,
platform, language, etc.).
5. Location: Represents the current URL and allows navigation to other
pages.

3. What is the WindowObject?


The Window Object is the global object in the BOM.
All other BOM objects (like
document , screen ,
location , etc.) are its
properties. These are the direct children of window object.

1. Document ( [Link] )
The document property refers to the HTML document loaded in the
browser window.
The JavaScript document object is a property of the window object
It can be accessed using [Link]
syntax. It can also be accessed without prefixing window object

You might also like