JavaScript
JavaScript is a programming language used to create dynamic content for websites. It is
a lightweight, cross-platform, and single-threaded programming language. JavaScript is
an interpreted language that executes code line by line providing more flexibility.
• HTML adds Structure to a web page, CSS styles it and JavaScript brings it to life by
allowing users to interact with elements on the page, such as actions on clicking
buttons, filling out forms, and showing animations.
• JavaScript on the client side is directly executed in the user's browser. Almost all
browsers have JavaScript Interpreter and do not need to install any software. There
is also a browser console where you can test your JavaScript code.
• JavaScript is also used on the Server side (on Web Servers) to access databases, file
handling and security features to send responses, to browsers.
1. Versatility: JavaScript can be used to develop (using ElectronJS) websites, games
(Using Phaser and [Link]), mobile apps (using React Native), and more.
2. Client Side: JavaScript is the main language for client-side logic and is supported by
almost all browsers. There is a big list of frameworks and libraries like React
JS, Angular JS, and Vue JS.
3. Server-Side: With runtime environments like [Link] and Frameworks like [Link],
JavaScript is now widely used for building server-side applications.
4. Machine Learning: With Libraries like [Link], JavaScript can be used to
develop and train machine learning models. Please refer to ML in JS for details.
5. Client-Side Scripting:JavaScript runs on the user’s browser, so has a faster response
time without needing to communicate with the server.
6. Versatile: JavaScript can be used for a wide range of tasks, from simple calculations
to complex server-side applications.
7. Event-Driven: JavaScript can respond to user actions (clicks, keystrokes) in real-time.
8. Asynchronous: JavaScript can handle tasks like fetching data from servers without
freezing the user interface.
9. Rich Ecosystem: There are numerous libraries and frameworks built on JavaScript,
such as React, Angular, and [Link], which make development faster and more
efficient.
• Imperative Programming: Focuses on how to perform tasks, controlling the flow of
computation. It includes approaches like procedural and object-oriented
programming, often using constructs like async/await to handle actions.
• Declarative Programming: Focuses on what should be done rather than how it’s
done. It emphasizes describing the desired result, like with arrow functions, without
detailing the steps to achieve it.
JavaScript is an event-driven, functional, and imperative language, commonly used both on
the client-side (in the browser) and server-side (via [Link]). Its capabilities have grown
significantly over time, allowing developers to build complex applications
Why JavaScript is known as a lightweight programming language ?
JavaScript is considered a lightweight language due to its low CPU usage, minimalist syntax,
and ease of implementation. With no explicit data types and a syntax similar
to C++ and Java, it’s easy to learn and runs efficiently in browsers. Unlike heavier languages
like Dart or Java, JavaScript, especially with [Link], performs faster and uses fewer
resources. While it has fewer built-in libraries, this makes it more flexible, though external
libraries are often needed for advanced functionality. JavaScript’s efficiency and simplicity
make it a top choice for web development.
s JavaScript Compiled or Interpreted or both ?
JavaScript is both compiled and interpreted. The V8 engine improves performance by first
interpreting code and then compiling frequently used functions for speed. This makes
JavaScript efficient for modern web apps. It’s mainly used for web development but also
works in other environments. You can learn it through tutorials and examples.
Just-In-Time (JIT) compilation is a technique used by JavaScript engines (like V8) to improve
performance. Here’s how it works
• Interpretation: Initially, the code is interpreted line-by-line by the engine.
• Hot Code Detection: The engine identifies frequently executed code, such as often-
called functions.
• Compilation: The “hot” code is compiled into optimized machine code for faster
execution.
• Execution: The compiled machine code is then executed directly, improving
performance compared to repeated interpretation.
• JIT compilation balances between interpretation (for quick startup) and compilation
(for faster execution).
Translation in the context of programming refers to the process of converting source code
written in a high-level programming language into another form, usually machine-
readable code or an intermediate format. This is done so that the computer can execute the
instructions.
There are two main types of translation processes:
1. Compilation: Translates the entire source code into machine code (binary form) or
intermediate code all at once, which is then executed by the computer. The compiled
code can be run multiple times without needing to re-compile. For example, in C or
C++, the source code is compiled into an executable file.
2. Interpretation: Translates and executes the source code line-by-line, on the fly,
during runtime. This means the code is not saved as a separate machine code file but
is executed directly from the source code. For example, in JavaScript or Python, the
interpreter processes the code as it is being run.
Versions:
Here’s a brief overview of major JavaScript versions:
• ES3 (1999): Introduced regular expressions, try-catch blocks, and basic array
methods.
• ES5 (2009): Added "strict mode", JSON support, and improved array methods.
• ES6 (2015): Major update with arrow functions, classes, modules, let/const, and
promises.
• ES7 (2016): Added [Link] and exponentiation operator (**).
• ES8 (2017): Introduced async/await and shared memory/atomic operations.
• ES9 (2018): Added rest/spread properties and async iteration.
• ES10 (2019): Features like flat, [Link], and trimStart/trimEnd.
• ES11 (2020): Introduced BigInt, ?? (nullish coalescing), and ?. (optional chaining).
• ES12 (2021): Added logical assignment operators and replaceAll.
• ES13 (2022): Added top-level await, [Link], and more.
• ES14 (2023): Ongoing improvements and error handling features.
Console:
The console object in JavaScript is used for logging and debugging purposes. It provides
various methods to output messages to the browser's console, which can help you inspect
your code's behavior during development.
Here are some commonly used console methods:
JavaScript output refers to displaying results or values generated by a JavaScript program.
The output can be shown in various ways, including:
Global Variables
Global variables in JavaScript are those declared outside of any function or block scope. They
are accessible from anywhere within the script, including inside functions and blocks.
Variables declared without the var, let, or const keywords (prior to ES6) inside a function
automatically become global variables.
However, variables declared with var, let, or const inside a function are local to that function
unless explicitly marked as global using window (in browser environments) or global (in
[Link]).
• The scope of a variable or function determines what code has access to it.
Key Characteristics of Global Variables:
1. Scope: Accessible throughout the entire script, including inside functions and blocks.
2. Automatic Global Variables: If a variable is declared inside a function without var,
let, or const, it automatically becomes a global variable (a common source of bugs).
(But it needs function to be called first before accessing the variable)
Local Variables
Local variables are defined within functions in JavaScript. They are confined to the scope of
the function that defines them and cannot be accessed from outside. Attempting to access
local variables outside their defining function results in an error.
Key Characteristics of Local Variables:
• Scope: Limited to the function or block in which they are declared.
• Function-Specific: Each function can have its own local variables, even if they share
the same name.
Hoisting
Hoisting refers to the behaviour where JavaScript moves the declarations
of variables, functions, and classes to the top of their scope during the compilation phase.
This can sometimes lead to surprising results, especially when using var, let, const, or
function expressions.
• Hoisting applies to variable and function declarations.
• Initializations are not hoisted, they are only declarations.
• ‘var’ variables are hoisted with undefined, while ‘let’ and ‘const’ are hoisted but
remain in the Temporal Dead Zone until initialized.
Temporal Dead Zone (TDZ)
The Temporal Dead Zone (TDZ) is a critical concept in JavaScript hoisting. It refers to the
period between the entering of a scope (such as a function or block) and the actual
initialization of a variable declared with let or const. During this time, any reference to the
variable before its initialization will throw a ReferenceError.
How does the TDZ Work?
• Variables declared with let and const are hoisted to the top of their scope, but they
are not initialized until their declaration line is reached.
• Any attempt to access these variables before their declaration will result in an
error.
• The TDZ exists only for variables declared using let and const. Variables declared
with var do not have this issue, as they are hoisted and initialized to undefined.
Hoisting is JavaScript's default behavior of moving variable
and function declarations to the top of their scope before
code execution.
Scopes in JavaScript
Scope determines where variables and functions can be accessed in JavaScript.
1. Global Scope
• Variables declared outside any function/block.
• Accessible from anywhere in the script.
2. Function Scope
• Variables declared with var inside a function are only accessible within that function.
• Not accessible outside the [Link] variables declared inside a function
are function-scoped and cannot be accessed outside the function.
• The variables declared using the var statement are hoisted at the top and are
initialized before the execution of code with a default value of undefined. The
variables declared in the global scope that is outside any function cannot be deleted
3. Block Scope (let and const)
• Variables declared with let or const inside {} are only accessible within that block.
4. Lexical Scope (Closures)
• Inner functions can access variables from their outer functions.
5. Module Scope (ES6 Modules)
• Variables declared inside a module are not accessible globally.
• Use export and import to share variables/functions between modules.
Variables in JS
Var:
The JavaScript var statement declares variables with function scope or globally. Before
ES6, var was the sole keyword for variable declaration, without block scope,
unlike let and const. Var is rarely used these days.
Syntax:
var variableName = valueOfVar;
Function Scope
The variables declared inside a function are function-scoped and cannot be accessed
outside the function.
The variables declared using the var statement are hoisted at the top and are initialized
before the execution of code with a default value of undefined. The variables declared in
the global scope that is outside any function cannot be deleted
1. var (Function-Scoped, Hoisted, Redeclarable)
• Function-scoped: Available throughout the function where it’s declared.
• Can be redeclared and reassigned.
• Gets hoisted but initialized as undefined.
Let:
(Block-Scoped, No Redeclaration)
• Block-scoped: Available only inside {}.
• Cannot be redeclared within the same scope.
• Gets hoisted but not initialized, causing a ReferenceError if accessed before
declaration.
• The let keyword in JavaScript is used to make variables that are scoped to the block
they’re declared in. Once you’ve used let to define a variable, you cannot declare it
again within the same block. It’s important to declare let variables before using them.
The let keyword was introduced in the ES6 or ES2015 version of JavaScript. It’s usually
recommended to use let when you’re working with JavaScript.
Const:
The const keyword in JavaScript is used to create variables that cannot be redeclared or
changed after their first assignment. This keeps the variable’s value fixed.
Additionally, const doesn’t allow redeclaration of the same variable within the same block,
and it provides block scope. It was introduced in ES2015 (ES6) for creating immutable
variables.
Syntax
To declare a variable with const, assign a value immediately upon declaration, as omitting an
initializer will lead to a syntax error:
const const_name;
const x;
Characteristics of JavaScript const
Here are some Characteristics of JavaScript Const :
• Cannot be reassigned: Once a value is assigned to a const variable, it cannot be
changed.
• Block scope: const is limited to the block in which it is defined, meaning it is not
accessible outside of that block.
• Must be assigned during declaration: A const variable must be assigned a value at
the time it is declared.
• Works with primitive values: const is often used with primitive values like numbers,
strings, or booleans, making them immutable.
• Objects and arrays can be modified: While a const object or array cannot be
reassigned to a new reference, the values or properties inside them can be modified.
• Can’t reference new objects or arrays: You can modify the content of const arrays or
objects but cannot reassign them to a completely new array or object.
• Can be redeclared in different block scopes: const variables can be declared again in
a different block scope without any conflict.
• Cannot be hoisted: Unlike var, const variables are not hoisted and must be declared
before use.
• Creates read-only references: const creates a reference to a value that cannot be
changed, although properties of objects and arrays may still be altered.
const (Block-Scoped, Immutable Reference)
• Block-scoped like let.
• Must be initialized at declaration.
• Cannot be reassigned, but objects and arrays declared with const can be mutated.
JavaScript Data Types
In JavaScript, each value has a data type, defining its nature (e.g., Number, String, Boolean)
and operations. Data types are categorized into Primitive (e.g., String, Number) and Non-
Primitive (e.g., Objects, Arrays).
Primitive Data Type
1. Number
The Number data type in JavaScript includes both integers and floating-point numbers.
Special values like Infinity, -Infinity, and NaN represent infinite values and computational
errors, respectively.
String
A String in JavaScript is a series of characters that are surrounded by quotes. There are three
types of quotes in JavaScript, which are.
A string in JavaScript is a sequence of characters used for representing text-based data.
Strings are immutable, meaning once created, they cannot be changed. Strings can be
created using single quotes ('), double quotes ("), or backticks (`) for template literals.
There’s no difference between ‘single’ and “double” quotes in JavaScript. Backticks provide
extra functionality as with their help of them we can embed variables inside them.
Template literals (also known as template strings) in JavaScript are a more powerful
way to work with strings. They were introduced in ES6 (ECMAScript 2015) and provide an
easier and more readable way to create strings with embedded expressions.
Key Features of Template Literals:
1. Multi-line Strings: Template literals allow strings to span multiple lines without the
need for concatenation or escape characters.
2. Expression Interpolation: You can embed expressions directly into the string using
${}.
3. Improved Readability: Template literals make string concatenation and embedding
expressions more intuitive.
Syntax:
Template literals are enclosed by backticks (`), unlike regular strings that are enclosed by
single (') or double (") quotes.
Benefits of Template Literals:
• Cleaner and More Readable Code: Makes string concatenation more readable and
eliminates the need for + operators.
• Flexibility with Expressions: You can embed variables and expressions seamlessly.
• Multi-line Support: Easily work with strings that span multiple lines.
3. Boolean
The boolean type has only two values i.e. true and false.
4. Null
The special null value does not belong to any of the default data types. It forms a separate
type of its own which contains only the null value.
let age = null;
[Link](age)
The ‘null’ data type defines a special value that represents nothing, or empty value.
5. Undefined
A variable that has been declared but not initialized with a value is automatically assigned
the undefined value. It means the variable exists, but it has no value assigned to it.
let a;
[Link](a);
6. Symbol (Introduced in ES6)
Symbols, introduced in ES6, are unique and immutable primitive values used as identifiers
for object properties. They help create unique keys in objects, preventing conflicts with
other properties.
let s1 = Symbol("Geeks");
let s2 = Symbol("Geeks");
[Link](s1 == s2);
Output
false
7. BigInt (Introduced in ES2020)
BigInt is a built-in object that provides a way to represent whole numbers greater than 253.
The largest number that JavaScript can reliably represent with the Number primitive is 253,
which is represented by the MAX_SAFE_INTEGER constant.
let b = BigInt("0b1010101001010101001111111111111111");
[Link](b);
Non-Primitive Data Types
The data types that are derived from primitive data types are known as non-primitive data
types. It is also known as derived data types or reference data types.
Object
JavaScript objects are key-value pairs used to store data, created with {} or the new
keyword. They are fundamental as nearly everything in JavaScript is an object.
Non-primitive (or reference) data types in JavaScript are data types that are not stored
directly in memory but as a reference. These include:
1. Objects
2. Arrays
3. Functions
4. Date
5. RegExp (Regular Expressions)
6. Map
7. Set
let gfg = {
type: "Company",
location: "Noida"
}
[Link]([Link])
2. Arrays
An Array is a special kind of object used to store an ordered collection of values, which can
be of any data type.
3. Function
A function in JavaScript is a block of reusable code designed to perform a specific task
when called.
4. Date Object
The Date object in JavaScript is used to work with dates and times, allowing for date
creation, manipulation, and formatting.
Interesting Facts about Data Types
1. Dynamically Typed : JavaScript Variables are not bound to a specific data type. Mainly
data type is stored with value (not with variable name) and is decided & checked at run
time.
let x = 42;
[Link](x)
x = "hello";
[Link](x)
x = [1, 2, 3]
[Link](x)
Output
42
hello
[ 1, 2, 3 ]
Everything is an Object (Sort of): In JavaScript, Functions are objects, arrays are objects, and
even primitive values can behave like objects temporarily when you try to access properties
on them.
let s = "hello";
[Link]([Link]);
// Example with a number
let x = 42;
[Link]([Link]());
// Example with a boolean
let y = true;
[Link]([Link]());
Output
5
42
true
3. NaN is not equal to itself: NaN Stands for “Not-a-Number”, It is used to represent a
computational error. NaN is technically of type number.
[Link](typeof NaN);
[Link](NaN === NaN);
Output
number
false
4. A Symbol is Never Equal to Another One : Symbol is a unique and immutable data type
often used for creating private properties and methods. Symbols are never equal to any
other Symbol.
let s1 = Symbol("abc");
let s2 = Symbol("abc");
[Link](s1 === s2);
Output
False
5. Undefined and Null: undefined represents a variable that has been declared but not
assigned, while null is an explicit assignment representing “no value”.
6. Integers are Floating are Numbers only. There is only one type number that covers both
integers and floating point numbers.
let x = 42; // Integer
let y = 42.5; // Floating-point
[Link](typeof x);
[Link](typeof y);
Output
number
number
7. A character is also a string. There is no separate type for characters. A single character is
also a string.
let s1 = "gfg"; // String
let s2 = 'g'; // Character
[Link](typeof s1);
[Link](typeof s2);
Output
string
string
typeof operator in JavaScript is used to determine the data type of a value or
variable. It returns a string indicating the type, such as “string”, “number”, “boolean”,
“object”, etc.
[Link](typeof "Hello");
[Link](typeof 42);
[Link](typeof true);
[Link](typeof {});
[Link](typeof undefined);
Output
string
number
boolean
object
undefined
Key Points:
• Always outputs the data type as a string.
• Can be used anywhere without imports or dependencies.
• Determines the type of literals, variables, and expressions.
• Special Cases:
o typeof null returns “object” (a known quirk).
o Functions return “function” instead of “object”.
• Useful for checking types in dynamic or untyped environments.
Type Casting in JavaScript
Type casting (also called type conversion) in JavaScript refers to converting one data type
into another. It can be explicit (manual) or implicit (automatic).
1. Explicit Type Casting (Manual)
JavaScript provides functions to manually convert data types.
A. Converting to String
• Using String()
• Using .toString()
• Using Template Literals
B. Converting to Number
• Using Number()
• Using parseInt()
• Using parseFloat()
• Using + operator
C. Converting to Boolean
• Using Boolean()
2. Implicit Type Casting (Automatic)
JavaScript automatically converts data types in some operations.
A. String Conversion (Concatenation)
Type Coercion refers to the process of automatic or implicit conversion of values
from one data type to another. This includes conversion from Number to String, String to
Number, Boolean to Number, etc. when different types of operators are applied to the
values.
In case the behavior of the implicit conversion is not sure, the constructors of a data type
can be used to convert any value to that datatype, like
the Number(), String() or Boolean() constructor.
These are the basic conversion of one dataType into another dataType:
Table of Content
• Number to String Conversion
• String to Number Conversion
• Boolean to Number
• The Equality Operator
Number to String Conversion
When any string or non-string value is added to a string, it always converts the non-string
value to a string implicitly. When the string ‘Rahul’ is added to the number 10 then
JavaScript does not give an error. It converts the number 10 to string ’10’ using coercion and
then concatenates both strings.
// The Number 10 is converted to
// string '10' and then '+'
// concatenates both strings
let x = 10 + '20';
let y = '20' + 10;
// The Boolean value true is converted
// to string 'true' and then '+'
// concatenates both the strings
let z = true + '10';
[Link](x);
[Link](y);
[Link](z);
Output
1020
2010
true10
String to Number Conversion
When an operation like subtraction (-), multiplication (*), division (/), or modulus (%) is
performed, all the values that are not numbers are converted into the number data type, as
these operations can be performed between numbers only. Some examples of this are
shown below.
Example: In this example, we are converting string to number implicitly.
// The string '5' is converted
// to number 5 in all cases
// implicitly
let w = 10 - '5';
let x = 10 * '5';
let y = 10 / '5';
let z = 10 % '5';
[Link](w);
[Link](x);
[Link](y);
[Link](z);
Output
5
50
2
0
Boolean to Number
When a Boolean is added to a Number, the Boolean value is converted to a number as it is
safer and easier to convert Boolean values to Number values. A Boolean value can be
represented as 0 for ‘false’ or 1 for ‘true’. Some examples of this are shown below.
Example: In this example, we are converting Boolean to number implicitly.
// The Boolean value true is
// converted to number 1 and
// then operation is performed
let x = true + 2;
// The Boolean value false is
// converted to number 0 and
// then operation is performed
let y = false + 2;
[Link](x);
[Link](y);
Output
3
2
The Equality Operator
The equality operator (==) can be used to compare values irrespective of their type. This is
done by coercing a non-number data type to a number. Some examples of this are shown
below:
Example: In this example, we are using == operator for checking the type of the values.
// Should output 'true' as string '10'
// is coerced to number 10
let x = (10 == '10');
// Should output 'true', as boolean true
// is coerced to number 1
let y = (true == 1);
// Should output 'false' as string 'true'
// is coerced to NaN which is not equal to
// 1 of Boolean true
let z = (true == 'true');
[Link](x);
[Link](y);
[Link](z);
Output
true
true
false
Difference Between == and === in JavaScript
[Link]() in JavaScript
[Link]() is a method in JavaScript used to compare two values for strict equality, similar to
the === operator. However, it handles some edge cases differently than ===.
Comparison Behavior
[Link]() compares two values for equality, with special handling for NaN, -0, and +0.
Key Differences from ===
1. NaN:
o === treats NaN as not equal to NaN (i.e., NaN === NaN is false).
o [Link]() treats NaN as equal to NaN (i.e., [Link](NaN, NaN) is true).
2. +0 vs -0:
o === treats +0 and -0 as equal (i.e., +0 === -0 is true).
o [Link]() distinguishes between +0 and -0 (i.e., [Link](+0, -0) is false).
When to Use [Link]()
• Use [Link]() when you need to distinguish between +0 and -0, or correctly
compare NaN.
• In most cases, === is sufficient, but [Link]() is useful for edge cases.
Summary
• [Link]() behaves like ===, but with differences in handling NaN and zero values (+0
vs -0).
Data Structures:
Keyd Collection: keyed collections like Map, Set, WeakMap, and WeakSet.
[Link]
• Stores key-value pairs.
• Keys can be of any data type.
• Maintains insertion order.
• set(key, value): Adds a key-value pair.
• get(key): Retrieves a value.
• delete(key): Removes a key.
• has(key): Checks if a key exists.
• size: Returns the number of entries.
• clear(): Removes all entries.
• Iteration: forEach(), keys(), values(), entries().
[Link] (Unique Values Collection)
• add(value): Adds a value.
• delete(value): Removes a value.
• has(value): Checks if a value exists.
• size: Returns the number of values.
• clear(): Removes all values.
• Iteration: forEach(), values(), keys(), entries().
3. WeakMap (Weakly Held Key-Value Storage)
• Keys must be objects.
• set(key, value): Adds a key-value pair.
• get(key): Retrieves a value.
• delete(key): Removes a key.
• has(key): Checks if a key exists
4. WeakSet (Weakly Held Object Collection)
• Only stores objects.
• add(value): Adds an object.
• delete(value): Removes an object.
• has(value): Checks if an object exists.
JSON (JavaScript Object Notation) in JavaScript
JSON is a lightweight data format used for storing and exchanging data. It is commonly used
in APIs and configurations.
1. JSON Syntax
• Data is stored as key-value pairs.
• Keys must be strings, values can be strings, numbers, objects, arrays, true, false, or
null.
• Uses double quotes around keys and strings.
5. JSON Use Cases
✔ Web APIs (REST, GraphQL)
✔ Configuration Files ([Link], .json settings)
✔ Data Exchange (LocalStorage, IndexedDB)
JavaScript Object
A JavaScript Object is a collection of key-value pairs where keys are strings (or symbols) and
values can be any data type, including functions.
9. When to Use Objects?
✔ Storing structured data in key-value pairs
✔ Creating reusable data structures
✔ Managing configurations/settings in apps
JavaScript Indexed Collections
Indexed collections in JavaScript are arrays and typed arrays that store elements in a
sequential manner, accessed via numerical indices.
Loops And Iterations:
Loops and Iterations in JavaScript
Loops allow executing a block of code multiple times. JavaScript provides several types of
loops for different use cases.
For object
For(let <var_name> in obj){
[Link](<var_name>,obj[<var_name>]);
}
Var_name will always be a key.. it will not give the value
For array <var_name> will always be index values like 0, 1 ,2;
To access the value we will need to access it by array[index] method
for...of Loop in JavaScript
The for...of loop is designed to iterate over iterable objects like arrays, strings, maps, sets,
etc. It is particularly useful when you need to access the values of these collections, rather
than the keys or indices.
Key Features of for...of:
• Iterates over values in iterable objects.
• Does not iterate over object properties like for...in does.
• Works with arrays, strings, maps, sets, NodeLists, and any object that implements
the iterable protocol.
For of Loop will give access to values directly
forEach Method in JavaScript
The forEach() method is a built-in array method in JavaScript that allows you to iterate over
the elements of an array or an array-like object (like NodeList), executing a provided function
once for each element. Unlike loops like for...of, forEach is a higher-order function and
provides a more functional approach to iteration.
• Iterates over array elements: It only works with arrays and array-like objects (like
NodeList or arguments).
• Does not return a value: It returns undefined, so it can't be chained with other
methods.
• Does not support break, continue, or return: It runs the provided callback for every
element, and you can't exit the loop prematurely using break or continue.
• Provides the element, index, and array as arguments to the callback.
• currentValue: The current element being processed in the array.
• index (optional): The index of the current element being processed in the array.
• array (optional): The array that forEach is being called on.
Control Flow
The break statement is used in a switch statement to exit the current case block and prevent
the execution from falling through to subsequent cases. Without break, JavaScript will
continue executing the code in the following case blocks, even if the condition does not
match. This behavior is known as "fall-through".
Loops;
For, while, dowhile ,for in,for of
Error Objects:
error objects:
are used to represent runtime errors in the program. These objects contain information
about the error, such as its message, type, and where it occurred. JavaScript provides built-in
Error objects that can be used to handle and throw exceptions.
Types of Error Objects:
JavaScript has several built-in error types that are extensions of the Error object. Some
common ones include:
1. Error: The base class for all error types. It's the generic error type.
2. SyntaxError: Represents errors related to invalid JavaScript syntax.
3. ReferenceError: Thrown when referencing a variable that doesn't exist.
4. TypeError: Raised when a value is not of the expected type.
5. RangeError: Thrown when a number is outside the allowable range.
6. EvalError: Represents errors related to the eval() function.
7. URIError: Thrown when there are issues with the encodeURI() or decodeURI()
functions.
Creating and Throwing an Error:
You can create a new error using the Error constructor or the specific error types.
Conditional Operators:
1. Ternary (Conditional) Operator (? :)
The ternary operator is a shorthand for an if-else statement. It evaluates a condition and
returns one of two values depending on whether the condition is true or false.
If the condition is true, expression1 is executed and returned.
If the condition is false, expression2 is executed and returned.
BigInt Operators in JavaScript
BigInt is a special data type in JavaScript used to represent arbitrary-precision integers. It
allows you to work with integers that are larger than 2^53 - 1, the maximum value that a
standard Number can safely represent.
Spread Operator (...) in JavaScript
The spread operator (...) allows you to unpack elements from an iterable (such as an array,
string, or object) and spread them into a new array or object. It is often used to make a
shallow copy of arrays or objects, merge them, or pass elements as individual arguments in
function calls.
The Spread operator (represented as three dots or …) is used on iterables like array and
string, or properties of Objects. to expand wherever zero or more elements are required top
be copied or assigned. Its primary use case is with arrays, especially when expecting multiple
values. The syntax of the Spread operator is the same as the Rest parameter but it works
opposite of it.
JavaScript Rest parameter:
The JavaScript Rest parameter allows a function to accept an indefinite number of
arguments as an array. It is represented by three dots (…) followed by the parameter name
and must be the last parameter in the function, enabling flexible and dynamic argument
handling.
The rest operator (...) is used to collect multiple elements into a single entity, such as an
array or object. It is essentially the inverse of the spread operator, which spreads elements
out. The rest operator allows you to gather values into a single array or object.
The rest operator is used in function parameters, array destructuring, and object
destructuring.
Only One Rest Parameter: You can only have one rest parameter in a function, and it must
be the last parameter. If you try to add multiple rest parameters, it will throw a syntax error.
Works in Destructuring: You can use the rest operator in both array and object destructuring
to collect the remaining elements or properties into a new array or object.
Destructuring in JavaScript
Destructuring is a shorthand syntax in JavaScript that allows you to unpack values from
arrays or properties from objects and assign them to variables in a more readable and
concise way.
It simplifies the process of extracting multiple values from arrays or objects and assigning
them to variables.
Functions in JavaScript:
Functions in JavaScript are reusable blocks of code designed to perform specific tasks. They
allow you to organize, reuse, and modularize code. It can take inputs, perform actions, and
return outputs.
Function Parameters
Parameters are input passed to a function. In the above example, sum() takes two
parameters, x and y.
Why Functions?
• Functions can be used multiple times, reducing redundancy.
• Break down complex problems into manageable pieces.
• Manage complexity by hiding implementation details.
• Can call themselves to solve problems recursively.
Function Invocation
The function code you have written will be executed whenever it is called.
• Triggered by an event (e.g., a button click by a user).
• When explicitly called from JavaScript code.
• Automatically executed, such as in self-invoking functions.
Function Expression
It is similar to a function declaration without the function name. Function expressions can be
stored in a variable assignment.
Arrow Functions
Arrow functions are a concise syntax for writing functions, introduced in ES6, and they do
not bind their own this context.
Immediately Invoked Function Expression (IIFE)
IIFE functions are executed immediately after their definition. They are often used to create
isolated scopes.
It is used to create a private scope and avoid polluting the global namespace.
Why Use an IIFE?
1. Avoids Global Scope Pollution
o Variables inside an IIFE are not accessible globally.
2. Encapsulation & Data Privacy
o Keeps variables private and prevents them from being modified externally.
3. Executes Immediately
o Runs as soon as it is defined, making it useful for initialization tasks.
Callback Functions
A callback function is passed as an argument to another function and is executed after the
completion of that function
Pure Functions
Pure functions return the same output for the same inputs and do not produce side effects.
They do not modify state outside their scope, such as modifying global variables, changing
the state of objects passed as arguments, or performing I/O operations.
function pureAdd(a, b) return a + b;}
[Link](pureAdd(2, 3));
Advantages of Functions in JavaScript
• Reusability: Write code once and use it multiple times.
• Modularity: Break complex problems into smaller, manageable pieces.
• Improved Readability: Functions make code easier to understand.
• Maintainability: Changes can be made in one place without affecting the entire
codebase.
Argument Object
The arguments object in JavaScript is an array-like object available inside regular functions
(not arrow functions). It contains all the arguments passed to the function.
2. Function Stack (Call Stack)
The call stack is a data structure that manages function execution.
How it Works:
• Functions are pushed onto the stack when called.
• Functions are popped off when they return.
all Stack Execution:
1. first() is called → Pushed to the stack.
2. first() calls second() → Pushed to the stack.
3. second() calls third() → Pushed to the stack.
4. third() executes and completes → Removed.
5. second() completes → Removed.
6. first() completes → Removed.
Here’s a summary of common built-in functions in JavaScript:
• String functions: .toUpperCase(), .toLowerCase(), .includes(), .trim(), .split()
• Number functions: parseInt(), parseFloat(), [Link](), [Link](), [Link](),
[Link](), [Link](), [Link]()
• Array functions: .length, .push(), .pop(), .indexOf(), .includes(), .reverse(), .join(),
.map(), .filter(), .reduce()
• Date functions: new Date(), .getFullYear(), .getMonth(), .getDate()
• JSON functions: [Link](), [Link]()
• Utility functions: typeof(), isNaN(), Boolean(), encodeURIComponent(),
decodeURIComponent()
DOM
The DOM (Document Object Model) API is a collection of interfaces that allow JavaScript to
interact with and manipulate HTML or XML documents. Through the DOM, JavaScript can
access, modify, delete, or create elements and content on a webpage.
Key DOM Methods and Properties
1. Selecting Elements
o [Link](id) – Selects an element by its ID.
o [Link](class) – Selects elements by class name.
o [Link](tag) – Selects elements by tag name.
o [Link](selector) – Selects the first element that matches
the CSS selector.
o [Link](selector) – Selects all elements that match the
CSS selector.
2. Manipulating Elements
o .innerHTML – Gets or sets the HTML content of an element.
o .textContent – Gets or sets the text content of an element.
o .setAttribute(name, value) – Sets the value of an attribute.
o .getAttribute(name) – Gets the value of an attribute.
o .style – Modifies the inline styles of an element.
3. Creating and Removing Elements
o [Link](tag) – Creates a new element.
o [Link](child) – Appends a child element to a parent element.
o [Link](child) – Removes a child element from a parent.
o [Link](newChild, oldChild) – Replaces an old child with a new
one.
4. Event Handling
o .addEventListener(event, function) – Attaches an event listener to an
element.
o .removeEventListener(event, function) – Removes an event listener.
o .onclick, .onmouseover, .onkeydown – Shortcut event handlers (e.g.,
[Link] for click events).
5. Traversing the DOM
o .parentNode – Gets the parent element of the current element.
o .childNodes – Gets all the child nodes of an element.
o .firstChild, .lastChild – Gets the first or last child element.
o .nextSibling, .previousSibling – Gets the next or previous sibling element.
Window Object:
The window object in JavaScript represents the global environment in which JavaScript code
is executed in the browser. It is a built-in object that provides access to various properties
and methods for interacting with the browser window, the document, and the environment.
Here are some key points about the window object:
1. Global Object
• In the browser, the window object is the global object, meaning all global variables,
functions, and objects are properties of the window object.
2. Properties of the Window Object
• The window object has several properties that provide information about the
browser environment:
o [Link]: Represents the DOM (Document Object Model), allowing
manipulation of HTML elements.
o [Link]: Provides information about the current URL and allows
navigation.
o [Link]: Provides information about the browser (like the version,
platform, etc.).
o [Link]: Allows navigation through the browser's session history.
o [Link] and [Link]: Return the width and height of
the browser’s viewport (the visible area).
o [Link] and [Link]: Allow storing data in the
browser.
3. Methods of the Window Object
• The window object provides various methods for interacting with the browser:
o [Link](): Displays a simple alert box.
o [Link](): Displays a dialog with OK and Cancel buttons, returning a
boolean.
o [Link](): Displays a prompt dialog asking for user input.
o [Link](): Executes a function after a specified time delay.
o [Link](): Repeatedly executes a function at specified intervals.
o [Link](): Opens a new browser window or tab.
Window Variables:
In JavaScript, window variables refer to variables that are defined in the global scope, which
are automatically properties of the window object when running in a browser. This means
that any global variable or function is a property of the window object and can be accessed
through [Link].
1. Declaring Variables in the Global Scope
When you declare a variable outside any function, it becomes a global variable. If you're
running the code in a browser environment, this variable will also be accessible as a
property of the window object.
Here, globalVar is a global variable, and it's accessible as a property of the window object.
2. Using var to Declare Variables
Variables declared using var in the global scope are automatically added as properties to the
window object.
In this example, the name variable is stored as a property of the window object.
3. Using let and const for Global Variables
Variables declared with let or const at the global scope do not become properties of the
window object. This is one of the key differences between var and let/const.
• let and const are block-scoped, meaning they don’t become properties of the
window object even when declared in the global scope.
4. Global Functions as Window Properties
When you declare a function in the global scope, it also becomes a method of the window
object.
Here, the greet function is accessible via the window object.
5. window Variables in the Browser Console
In the browser's developer console, you can access and interact with global variables and
functions as properties of the window object.
6. Important Note on Global Variables
• Global variables declared with var: These are automatically added as properties of
the window object.
• Global variables declared with let or const: These are not added as properties of the
window object.
• Window-specific variables: Certain properties and methods (like [Link],
[Link]) are predefined by the browser and exist on the window object.
Use Strict:
The "use strict" directive in JavaScript enables strict mode, a more restrictive version of
JavaScript that catches common coding errors and improves performance by enforcing
stricter parsing and error handling in your JavaScript code.
Benefits of "use strict":
• Error Prevention: It helps prevent common coding errors like accidental global
variable declarations, which could cause bugs.
• Cleaner Code: Enforces a cleaner, more predictable way of writing JavaScript.
• Performance Optimization: JavaScript engines can optimize strict mode code more
efficiently, leading to better performance in some cases.
This keyword:
The this keyword in JavaScript refers to the execution context of the current function or
method. Its value depends on how the function or method is invoked. Understanding how
this works in different situations is crucial to mastering JavaScript's object-oriented and
functional programming features.
1. In a Method
When you use this inside a method of an object, it refers to the object that the method is a
part of (i.e., the owner of the method).
Here, this inside the greet method refers to the person object because it is calling the
method from within that object.
2. In a Function (Global Context or Inside a Function)
In non-method functions, the value of this depends on how the function is called:
• In a regular function (not in strict mode), this refers to the global object (window in
browsers).
• In strict mode ('use strict'), this is undefined if the function is called directly (not as
part of an object).
Example in non-strict mode:
3. Alone (Global Context)
If you reference this alone (not in a function or method), its behavior depends on the
context:
• In non-strict mode, this refers to the global object (window in browsers).
• In strict mode, this is undefined.
Example:
4. In Event Handlers
In an event handler, this refers to the element that fired the event (the target element). This
can be useful when you want to access properties or methods of the element inside the
event handler.
Example:
In this case, when the button is clicked, this inside the event handler refers to the button
element that fired the click event.
5. In Arrow Functions
Arrow functions do not have their own this; instead, they inherit this from the surrounding
context where they are defined (lexical scoping). This means this in an arrow function
behaves differently from regular functions and methods.
In this example, the arrow function inside setTimeout does not have its own this. It inherits
this from the greet method, which refers to the person object. Therefore, [Link] inside
the arrow function correctly refers to "Alice".
Example of what happens with a regular function:
In the example with a regular function inside setTimeout, this refers to the global object (or
is undefined in strict mode), so [Link] will be undefined.
Function Borrowing:
It refers to a concept in JavaScript where one object can borrow a function or method from
another object and use it. This typically involves using methods like .call(), .apply(), or
.bind() to allow one object to temporarily use the methods of another object, even though
the method is not defined within the object's prototype chain.
This is useful when you want to reuse a method from another object without needing to
copy or redefine it.
How Function Borrowing Works:
• The method fullName is part of the person object.
• By using .call(employee), we borrow the fullName method from the person object
and apply it to the employee object. The this inside the fullName method now refers
to the employee object, allowing us to access [Link] and
[Link].
Note: in this call method is use to pass the second object which don’t have to method that
it want to use To the first object which has the method that is needed by second object.
So in this example.. employee method don’t have the method named fullname , but the
same method is present in the person object. So we can pass the employee object as an
argument to function present in person object using call function. So that the this keyword
in the fullname function present in person object will refer to the employee object instead
of person object. So that “this” keyword can access the properties of employee object.
Change from call method is that , the apply function takes the argument as an array on
values.
.bind() Method
• The .bind() method also allows you to set the value of this, but it does not
immediately invoke the function. Instead, it returns a new function that, when called,
will have this bound to the specified object and will use the passed arguments.
Bind method is just use to create the copy of function related to passed/borrowing object.
So that it can be used later.
Higher Order Functions:
In JavaScript, higher-order functions are functions that can:
1. Accept one or more functions as arguments, and/or
2. Return a function as a result.
A higher-order function treats functions as first-class citizens, which means they can be
passed around just like other values (e.g., numbers, strings, objects, etc.).
Characteristics of Higher-Order Functions:
• Accepting functions as arguments: A higher-order function can take a function as a
parameter.
• Returning a function: A higher-order function can return a function.
1. map()
• Purpose: The map() method creates a new array populated with the results of calling
a provided function on every element in the array.
• callback: A function that is executed on each element. It takes:
o currentValue: The current element being processed.
o index (optional): The index of the current element.
o array (optional): The original array.
• thisArg (optional): The value to use as this when executing the callback.
Returns: A new array with the same number of elements, but transformed based on the
function applied.
Asynchronous Javascript:
Event Loop
The event loop in JavaScript is a mechanism that allows asynchronous code to run without
blocking the main thread. It continuously checks if there are tasks in the call stack or the
message queue to be executed.
How it works:
1. Call Stack: The call stack is where your code is executed. When a function is invoked,
it’s pushed onto the stack. If that function calls another function, it’s also pushed to
the stack. When a function finishes execution, it’s popped off the stack.
2. Message Queue: The message queue holds tasks (like callback functions, promises,
or events) that are waiting to be executed. These tasks are processed after the call
stack is empty.
3. Event Loop: The event loop constantly checks if the call stack is empty. If it is, it
moves tasks from the message queue to the call stack so they can be executed. This
allows asynchronous functions to be executed after synchronous code has finished
running.
Even though setTimeout is set to 0 milliseconds, it doesn’t run immediately. The event loop
first processes the synchronous code ([Link]('Start') and [Link]('End')), and only
after the call stack is empty does it pull the setTimeout callback from the message queue to
the stack.
Key Points:
• Synchronous code runs in the call stack.
• Asynchronous code like setTimeout, Promises, or event handlers are pushed to the
message queue.
• The event loop continuously checks the call stack and moves tasks from the queue to
the stack when the stack is empty.
The event loop allows JavaScript to handle asynchronous operations like I/O without
blocking the main execution thread, keeping the application responsive.
SetTimeOut & SetInterval:
JavaScript SetTimeout and SetInterval are the only native function in JavaScript that is used
to run code asynchronously, it means allowing the function to be executed immediately,
there is no need to wait for the current execution completion, it will be for further
execution.
The setTimeout() Method executes a function, after waiting a specified number of
milliseconds.
Both setTimeout and setInterval are used for handling asynchronous timing operations in
JavaScript.
1. setTimeout
Executes a function once after a specified delay (in milliseconds).
callback: Function to execute.
delay: Time in milliseconds before executing the function.
param1, param2, ...: Optional parameters to pass to the callback.
• The timeout function runs after the rest of the script finishes execution.
Clearing Timeout:
Use clearTimeout(timerId) to cancel a timeout.
2. setInterval
Executes a function repeatedly at a specified interval.
Same parameters as setTimeout.
Clearing Interval:
Use clearInterval(intervalId) to stop it.
Interesting Facts
• Asynchronous Execution: Both methods are asynchronous, meaning the browser
doesn’t block other code execution while waiting for the timer.
• Return Value: Both methods return a unique identifier (ID), which can be used with
clearTimeout() or clearInterval() to stop the scheduled task.
• Timer Accuracy: Timers are not perfectly precise; delays can vary due to browser
limitations and other queued tasks.
• Infinite Intervals: Using setInterval() without a clearInterval() call can lead to infinite
loops, potentially causing performance issues.
• Nested Timers: A setTimeout() can mimic a setInterval() by recursively calling itself
after each execution.
• Minimum Delay: The minimum delay for setTimeout() or setInterval() is 4
milliseconds, though it may increase in inactive browser tabs for performance
reasons.
• Timer in [Link]: Both methods are also available in [Link] with similar behavior
but are part of the global object.
Callback Function:
A callback is a function passed as an argument to another function, allowing the latter to
execute the callback function at a specific time, often after completing an operation.
Callbacks are a foundational concept in JavaScript, enabling asynchronous programming
and modular code design.
A callback is a function passed as an argument to another function to be executed later.
Why Use Callbacks?
JavaScript is single-threaded, meaning it executes one task at a time. If a task (like fetching
data) takes time, a callback ensures that other code keeps running instead of waiting.
Here sayGoodBye is passed as an argument which will not execute instantaly,it will get
executed when it gets called inside greet function.
If we do greet(“Alice”,sayGoodBye()) then it will get called immediately.
Why use Callbacks?
Callbacks are used for managing the outcomes of asynchronous tasks without blocking the
program’s execution. Asynchronous tasks, like network requests or database queries, take
time to finish. If these tasks were synchronous, the program would halt until they were
done, resulting in a sluggish user experience.
With callbacks, though, you can keep the program running while these tasks happen in the
background. When the task finishes, the callback function handles the result. This ensures
the program stays responsive, enhancing the user experience.
Important Points to Know About Callbacks
1. Asynchronous programming:
Callbacks are used to handle the results of asynchronous operations, which means that the
operation does not block the execution of the rest of the program. Instead, the program
continues to run and the callback function is executed when the operation is complete.
2. Non-blocking:
Callbacks allow for non-blocking programming, which means that the program does not stop
and wait for an operation to complete before continuing to execute. This is important for
improving the performance and responsiveness of applications.
3. Higher-order functions:
A higher-order function is a function that takes one or more functions as arguments, or
returns a function as a result. The main Function in the examples above is a higher-order
function because it takes a callback function as an argument.
4. Anonymous functions:
Anonymous functions are functions that are not named and are often used as callbacks.
The function passed to setTimeout in the first code example is an anonymous function.
5. Closure:
A closure is a function that has access to variables in its outer scope, even after the outer
function has returned. This allows the callback function to access variables and information
from the main function, even after the main function has completed its execution.
Real-Life Examples
1. Loading images on a website
When you load a website, images can take a while to load, especially if they’re large. If
images were loaded synchronously, the website would freeze and wait for each image to
load before continuing. With callbacks, you can load the images asynchronously, which
means that the website continues to load while the images are being loaded in the
background.
2. Handling form submissions
When a user submits a form, it takes time to process the data and send it to the server. If the
form submission was executed synchronously, the user would have to wait for the data to be
processed and sent before the form can be submitted. With callbacks, you can handle the
form submission asynchronously, which means that the user can continue to interact with
the form while the data is being processed and sent in the background.
What is Callback Hell?
Callback Hell happens when multiple nested callbacks make code hard to read, understand,
and maintain. This usually occurs in asynchronous operations, like fetching data or handling
multiple async tasks in sequence.
Problems with Callback Hell:
• Hard to read and debug.
• Error handling becomes complex.
• Code becomes deeply nested (the "Pyramid of Doom").
How to Fix Callback Hell?
Solution 1: Use Named Functions
Instead of nesting callbacks, break them into separate functions.
Solution 2: Use Promises
Instead of callbacks, use Promises to handle async operations sequentially.
Solution 3: Use async/await
The best way to write clean and readable async code.
Promises:
JavaScript Promises make handling asynchronous operations like API calls, file loading, or
time delays easier. Think of a Promise as a placeholder for a value that will be available in
the future. It can be in one of three states
A Promise in JavaScript is an object that represents the eventual completion (or failure) of
an asynchronous operation and its resulting value.
• Pending: The task is in the initial state.
• Fulfilled: The task was completed successfully, and the result is available.
• Rejected: The task failed, and an error is provided.
• resolve(value): Marks the promise as fulfilled and provides a result.
• reject(error): Marks the promise as rejected with an error.
operations (e.g., fetching data from an API, reading files), the program would freeze while
waiting.
Previously, we used callbacks, but they led to callback hell (deeply nested code that's hard
to read).
Promises solve this problem by:
Handling async operations in a clean and structured way.
Avoiding callback hell with better chaining (.then()).
Improving error handling using .catch().
Key Takeaways
• A Promise is an object that represents a future value.
• States: Pending → Fulfilled/Rejected.
• Methods:
o .then() → Runs on success
o .catch() → Runs on failure
o .finally() → Runs always
• Advanced:
o [Link]() → Waits for all
o [Link]() → Returns fastest
• Use async/await for cleaner, more readable async code.
Real-World Example of JavaScript Promises (Simple Explanation)
Imagine you order a pizza online.
1. Order Placed (Promise Created)
o You call the restaurant and place an order.
o They tell you the pizza will be ready soon (but not immediately).
2. Processing (Promise is Pending)
o The restaurant is preparing your pizza.
o You don’t know yet if it will be delivered successfully or if something will go
wrong.
3. Three Possible Outcomes:
o Pizza Delivered (Promise Fulfilled) → You get your pizza and enjoy it!
o Delivery Failed (Promise Rejected) → The delivery person gets lost, and
your pizza never arrives.
o Regardless of the outcome, you move on (Finally runs).
Key Takeaways:
• A promise is like waiting for your pizza.
• You don’t block other tasks while waiting (just like you can watch TV while waiting).
• It either succeeds (then) or fails (catch).
• Finally() runs no matter what.
Async and Await in JavaScript
Async and Await in JavaScript is used to simplify handling asynchronous operations using
promises. By enabling asynchronous code to appear synchronous, they enhance code
readability and make it easier to manage complex asynchronous flows.
async/await is a modern way to handle asynchronous code in JavaScript. It makes
asynchronous code look like synchronous code, making it easier to read and maintain.
Async Function
The async function allows us to write promise-based code as if it were synchronous. This
ensures that the execution thread is not blocked. Async functions always return a promise.
If a value is returned that is not a promise, JavaScript automatically wraps it in a resolved
promise.
The async keyword makes a function return a promise.
Await Keyword
The await keyword is used to wait for a promise to resolve. It can only be used within an
async block. Await makes the code wait until the promise returns a result, allowing for
cleaner and more manageable asynchronous code.
The await keyword pauses execution until the promise is resolved (or rejected).
Why?
Since async functions always return a promise, we can use .then() to handle the result.
async makes a function return a promise.
await pauses execution until the promise resolves.
try...catch is used for error handling.
[Link]() can be used with await for parallel execution.
Working with Apis:
XMLHttpRequest is an older JavaScript API used to make HTTP requests in web
browsers. It’s still supported in all browsers but has been largely replaced by the more
modern fetch() API. However, understanding XMLHttpRequest can still be useful for legacy
projects or when working with older browser environments.
Here’s a detailed guide on how to use XMLHttpRequest.
Basic Structure
The XMLHttpRequest object is used to interact with servers. It can be used to retrieve data
from a URL without having to reload the web page.
Steps to Use XMLHttpRequest
1. Create an XMLHttpRequest object
2. Open a request (specify the method and URL)
3. Set any necessary headers
4. Send the request
5. Handle the response
Explanation:
• [Link](method, url, async): Initializes a new request. The async parameter
specifies whether the request should be asynchronous (true means asynchronous,
which is the usual case).
• [Link]: This is triggered when the response is received. Inside this handler, you
check for a successful status code (200-299), parse the JSON response, and handle
the data.
• [Link]: This handles any network errors (like no internet connection).
• [Link](): Sends the request to the server.
Explanation:
• [Link]('Content-Type', 'application/json'): This sets the Content-
Type to tell the server that you're sending JSON data in the body of the request.
• [Link](data): The send method sends the data (in this case, the JSON data) to the
server.
Event Listeners
• onload: Called when the request completes successfully. It handles the server
response.
• onerror: Called when a network error occurs.
• onreadystatechange: This is another way to handle the request's state change. It's
not as commonly used today, but can be handy for tracking the request’s progress.
Understanding readyState and status
• readyState: The state of the request. Possible values:
o 0: UNSENT – The request has not been opened yet.
o 1: OPENED – The request has been opened.
o 2: HEADERS_RECEIVED – The request has received the response headers.
o 3: LOADING – The response body is being received.
o 4: DONE – The request has completed.
• status: The HTTP response status code (e.g., 200 for success, 404 for not found, 500
for server error).
1. Understanding HTTP Methods
In API communication, you’ll frequently use the following HTTP methods:
• GET: Retrieves data from the server.
• POST: Sends data to the server (typically used for creating resources).
• PUT: Updates an existing resource on the server.
• DELETE: Removes a resource from the server.
These methods are part of the RESTful API architecture, but the same principles apply for
other API types (like GraphQL or WebSocket APIs).
2. Fetch API (Built-in)
The fetch() API is a built-in JavaScript method for making HTTP requests. It’s promise-based
and works asynchronously.
7. Using Axios (Third-Party Library)
Axios is a promise-based HTTP client for both browser and [Link]. It is widely used because
of its ease of use, support for request/response interceptors, and automatic JSON parsing.
Axios Features
• Automatic JSON Parsing: Axios automatically converts the response to JSON.
• Request/Response Interceptors: You can intercept and modify requests/responses
globally.
• Error Handling: Axios provides better error handling through .catch() for all errors
(network, 4xx, 5xx, etc.).
HTTP headers
In HTTP requests, headers are key-value pairs that provide additional information about the
request or the response. Headers can define things like the type of content being sent,
authentication information, the desired format for the response, etc.
In the context of JavaScript and XMLHttpRequest, you can set request headers using the
setRequestHeader method. Similarly, you can read response headers from the server once
the request has been completed.
Common Headers
Here are some of the most commonly used headers:
1. Content-Type: Specifies the media type of the resource or the data being sent. It tells
the server what type of data you're sending (e.g., JSON, form data, text).
o application/json: For sending JSON data.
o application/x-www-form-urlencoded: For sending form data.
o multipart/form-data: For file uploads.
2. Accept: Indicates the media types that the client is willing to receive in the response.
o application/json: To request JSON data.
o text/html: To request HTML content.
3. Authorization: Used to pass credentials (such as tokens) for API authentication.
o Bearer <token>: For passing a token for Bearer authentication (e.g., OAuth).
o Basic <base64_encoded_credentials>: For passing username and password in
a basic authentication scheme.
4. User-Agent: Contains information about the client (browser or application) making
the request.
5. X-Requested-With: Often used in AJAX requests to indicate that the request was
made by JavaScript.
6. Cache-Control: Directs caching behavior of the response.
7. Cookie: Sends cookies to the server associated with the current domain.
Cookie:
A cookie is a small piece of data stored on a user's device by a website. It is sent to the
server with each subsequent request to that domain. Cookies are used for various
purposes, such as maintaining user sessions, storing preferences, and tracking users.
Key Points:
• Set-Cookie Header: Servers use the Set-Cookie header to send cookies to the client.
• [Link]: JavaScript uses [Link] to access and set cookies.
• Expiration: Cookies can have an expiration date or be session cookies (deleted when
the browser is closed).
• Attributes:
o Secure: Sends cookies only over HTTPS.
o HttpOnly: Restricts JavaScript access for security.
o SameSite: Controls cross-site cookie behavior (to prevent CSRF attacks).
Cookies are commonly used for session management, user preferences, and tracking.
Class in JS
1. 2.
3.
Class: Animal, Dog, and Cat are examples of classes, each with a constructor and methods.
Object: dog, cat, and person are objects created from their respective classes.
Inheritance: Dog and Cat inherit from the Animal class using extends.
Encapsulation: Private fields (like #age in the Person class) and public getters/setters (getName, getBreed,
etc.) encapsulate the internal state.
Abstraction: Animal class provides an abstract speak() method that is overridden in subclasses (Dog and
Cat).
Polymorphism: The speak() method is overridden in both Dog and Cat, allowing the same method name to
produce different behavior.
Constructor: Each class has a constructor that initializes properties like name, breed, color, etc.
Super: The super() method is used to call the parent class's constructor from the child class (Dog and Cat).
Iterator:
1. Iterator
An Iterator is an object that allows you to traverse through a collection (like an array, object,
or string) one item at a time. It implements the next() method, which returns an object with
two properties:
• value: The current value in the iteration.
• done: A boolean indicating whether the iteration is complete.
You can create an iterator by defining an object with a next() method.
Arrow function will not work.
2. Generator
A Generator is a special type of function in JavaScript that can be paused and resumed,
allowing for lazy evaluation. It uses the function* syntax, and the yield keyword is used to
pause the function execution and return a value. When the generator is resumed, it
continues execution from where it left off.
Key Points:
• A generator function returns a generator object.
• The generator object has a next() method, which can be called to execute the
function until it hits a yield or completion.
• Each time next() is called, it resumes execution from the last yield.
The yield keyword in JavaScript is used inside a generator function (function*) to pause the
function's execution and return a value. When the generator is called again, it resumes
execution from where it last yielded.
Key Uses of yield:
1. Pause and Resume Execution:
o The generator function can "pause" at a yield and later "resume" from that
point when next() is called again.
o This allows for lazy evaluation, where values are produced only when needed,
rather than all at once.
2. Returning Values from Generator:
o Each time yield is called, it returns a value to the caller, and the generator
function continues its execution from where it left off.
3. Use with next() Method:
o The generator's next() method triggers the function, advancing it to the next
yield and returning an object with value and done properties.
A real-time example of using generators could be for managing an asynchronous task queue
or lazy loading data, especially when you want to pause execution while waiting for a task to
complete, like fetching data from an API.
Here's a real-time example where a generator is used to simulate fetching data from a server
and processing it step-by-step. This could be useful when you're working with multiple async
tasks (e.g., loading user data, posts, comments) and you want to process them sequentially
without blocking the execution of other tasks.
Example: Real-Time Task Processing with a Generator
Imagine you have a task where:
1. You fetch user data from an API.
2. You fetch posts for the user.
3. Then, you fetch comments for each post.
You want to process them one by one, with each step waiting for the previous one to finish
before continuing.
Modules in JavaScript
A module in JavaScript is a file containing code that can be imported and used in other files.
It helps in organizing and separating concerns within a program, making the code more
maintainable and reusable.
Modules allow you to encapsulate code, export specific parts of it (like functions, objects,
variables), and import only what you need in other parts of the application.
ypes of Modules in JavaScript
1. CommonJS (CJS):
o Used primarily in [Link].
o Synchronous loading.
o Syntax:
▪ [Link]: To export functionality from a file.
▪ require(): To import functionality in other files.
ESM (ECMAScript Modules):
• Official module system in JavaScript, supported in modern browsers and [Link].
• Asynchronous loading.
• Syntax:
o export: To export functionality from a file.
o import: To import functionality in other files.
Memory Management in JavaScript
Memory management in JavaScript refers to the process of allocating, using, and freeing
memory during the execution of a program. JavaScript handles memory management
automatically via garbage collection but provides some tools and mechanisms for
developers to optimize memory usage.
Memory Allocation:
• JavaScript automatically allocates memory when variables, objects, arrays, or
functions are created. The memory is allocated on the heap (for objects) or stack (for
primitive types like numbers and strings).
Heap vs Stack:
• Stack: Used for simple variables like numbers, booleans, or references to objects.
• Heap: Used for more complex types like objects, arrays, and functions. The heap is
dynamic, meaning its size can grow and shrink.
Garbage Collection in JavaScript
Garbage collection (GC) is the automatic process of identifying and reclaiming memory that
is no longer in use by a program. This process ensures that JavaScript applications don’t run
out of memory by cleaning up objects that are no longer reachable or referenced.
In JavaScript, the garbage collector runs in the background, freeing up memory used by
objects and variables that are no longer needed.
Key Concepts in Garbage Collection
1. Reachability:
o An object is considered reachable if it can be accessed by the program
through any chain of references starting from the global environment or from
local variables (such as in a function scope).
o Unreachable objects are those that no longer have references pointing to
them.
2. Mark-and-Sweep Algorithm:
o Mark Phase: The garbage collector traverses all the reachable objects starting
from the global objects, function scopes, and any other reference points. It
marks all objects that are reachable.
o Sweep Phase: The garbage collector sweeps through memory and removes
any objects that were not marked as reachable. These objects are considered
garbage and are removed from memory.
Garbage Collection in Action
JavaScript uses the V8 engine (in Chrome and [Link]) for garbage collection, which uses a
Mark-and-Sweep strategy, enhanced with generational garbage collection. Here’s how it
works:
1. Object Creation:
o When an object is created, the engine allocates memory for it in the heap.
2. Object Reachability:
o If an object is still referenced (for example, via a variable, function, or
property), it remains reachable and is not garbage collected.
3. Garbage Collection:
o If an object is no longer referenced by any active code, the garbage collector
marks it as unreachable.
o The sweep phase cleans up the memory, freeing it for future use.
memory lifecycle in JavaScript refers to the process of managing memory from the
moment it is allocated, used, and eventually deallocated. Here's a short breakdown of the
key stages:
1. Memory Allocation:
o When variables, objects, or functions are created, memory is allocated either on the stack
(for simple data types) or heap (for complex data types like objects and arrays).
2. Memory Usage:
o The program uses the allocated memory during execution. Variables hold values or
references to objects, and functions are executed with the allocated memory.
3. Memory Deallocation (Garbage Collection):
o When memory is no longer needed (e.g., when an object or variable is unreachable), the
garbage collector automatically reclaims that memory by identifying and removing unused
objects.
o This ensures efficient memory usage and prevents memory leaks.
Memory Leaks in JavaScript
A memory leak occurs when a program retains memory that is no longer needed or
accessible, resulting in inefficient memory usage. This happens when objects, variables, or
resources are unintentionally kept alive in memory, preventing the garbage collector from
freeing up that memory.
Debugging Issues in JavaScript (Short Summary)
1. Syntax Errors: Mistakes in the code structure (e.g., missing parentheses).
2. Type Errors: Invalid operations on incompatible data types.
3. Reference Errors: Accessing undeclared or out-of-scope variables.
4. Logic Errors: The program runs but produces incorrect results due to flawed logic.
5. Asynchronous Issues: Incorrect handling of asynchronous operations (e.g., promises or callbacks).
6. Scope & Closure Issues: Problems caused by improper variable scoping or closures.
7. Memory Leaks: Unused memory not being freed, causing performance degradation.
8. Performance Issues: Slow code execution due to inefficient algorithms or large data handling.
Debugging Performance Issues in JavaScript (Short)
Common Issues:
1. Inefficient Algorithms: Slow algorithms or redundant operations.
2. Memory Leaks: Unused memory not being released.
3. Excessive DOM Manipulation: Frequent, unnecessary changes to the DOM.
4. Blocking Code: Long synchronous tasks blocking the event loop.
5. Too Many HTTP Requests: Excessive network requests slowing down performance.
Tools:
• Chrome DevTools (Performance and Memory tabs) to analyze code execution and
memory usage.
• Lighthouse for auditing performance.
• Console Profiling using [Link]() to measure execution time.
Optimization Tips:
• Optimize loops and use efficient algorithms.
• Minimize DOM manipulation, use virtual DOM if applicable.
• Debounce/Throttle event handlers.
• Use Web Workers for heavy tasks.
• Implement lazy loading and caching for better performance.