0% found this document useful (0 votes)
2 views

Chapter 5

JavaScript is a versatile scripting language used for creating interactive web pages and applications, functioning on both client and server sides. It integrates seamlessly with HTML and CSS, supports asynchronous programming, and has a rich ecosystem of frameworks and libraries. JavaScript's evolution has established it as a key language in modern web development, capable of handling everything from simple scripts to complex applications.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Chapter 5

JavaScript is a versatile scripting language used for creating interactive web pages and applications, functioning on both client and server sides. It integrates seamlessly with HTML and CSS, supports asynchronous programming, and has a rich ecosystem of frameworks and libraries. JavaScript's evolution has established it as a key language in modern web development, capable of handling everything from simple scripts to complex applications.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

Ch-5

Introduction to Java Script


What is Java Script
• JS is a client and server side object based scripting language that is used to make
interactive web pages.
• A scripting language is a programming language designed to automate tasks, control
software applications or manipulate content within a larger environment. Unlike
compiled languages, scripting languages are typically interpreted at runtime, making
them flexible and often easier to use for smaller and specific tasks. Examples include
JavaScript, Python, etc.
• Thus, JavaScript is a versatile programming language primarily used in web development
to create interactive and dynamic user interfaces. Originally designed to add simple
animations and functionality to HTML-based websites, JavaScript has evolved
significantly and is now used in both front-end and back-end development.
What Java Script does?
1.Client-Side Interactivity: JavaScript allows developers to make websites interactive. It
responds to user actions, such as clicks and form submissions, enabling features like pop-
ups, animations, and interactive forms.
2.Server-Side Development: With platforms like Node.js, JavaScript can be used for back-
end programming, allowing developers to build servers and manage databases.
3.Versatility Across Platforms: JavaScript is compatible with all major browsers and
platforms, making it accessible and widely applicable.
4.Integration with HTML and CSS: JavaScript is commonly used alongside HTML and
CSS to build complete and engaging web applications. It can dynamically change the
HTML content and CSS styling of a page based on user interaction.
• JavaScript is often paired with frameworks and libraries, such as React, Angular and
jQuery, for front-end applications and with Node.js for back-end applications, making it
one of the most popular programming languages in web development.
Why Java Script?
• Web Development: JavaScript is the core language for client-side web development,
allowing interactive and dynamic elements on websites. It runs in all modern web browsers
without the need for additional installations.
• Full-Stack Development: With the advent of Node.js, JavaScript can now be used on both
the front end (browser) and back end (server), allowing developers to work with a single
language throughout the stack.
• Rich Ecosystem: JavaScript has a vast ecosystem with numerous libraries and frameworks
(e.g., React, Angular, Vue for front-end; Express for back-end), making development faster
and easier.
• Asynchronous Programming: JavaScript supports asynchronous operations, such as
fetching data from a server, using features like callbacks, promises and async/await. This is
crucial for building responsive web applications.
• Event-Driven: JavaScript is event-driven, making it great for handling user interactions
(clicks, inputs, etc.), animations and real-time updates in web applications.
• Compatibility: JavaScript is compatible with all major browsers and platforms, ensuring a
seamless user experience across different devices and operating systems.
• Popularity: JavaScript is one of the most popular languages in the world, with a large
community, plenty of resources, tutorials and job opportunities for developers.
• Versatility: Besides web development, JavaScript is used in mobile app development
(using frameworks like React Native), desktop apps, games and even IoT projects.
• Easy to Learn: JavaScript has a relatively low entry barrier compared to many other
languages, making it accessible for beginners. Its syntax is simple and intuitive, and it is
often the first language taught for web development.
JavaScript: Scripting Language or Programming
Language?
When learning JavaScript, a frequent question arises: is it a scripting language or a
programming language?
Scripting Languages
• Scripting languages are typically interpreted rather than compiled. This means their code
is executed line by line at runtime by an interpreter, enabling faster development and
easier debugging.
• These languages are commonly employed for tasks such as system administration, web
development, text manipulation, and automation.
• JavaScript is widely recognized for its role in client-side scripting within web browsers.
Over time, it has evolved into a highly versatile tool for web development, supporting
both front-end and server-side scripting, particularly with frameworks like Node.js.
Scripting languages generally operate within a host environment. For example, JavaScript
is embedded within HTML and executed by web browsers.
Programming Languages
• Programming languages are usually compiled, converting source code into machine code
before execution.
• These languages enable communication with computers using structured instructions.
Unlike scripting languages, programming languages rely on compilers rather than
interpreters, resulting in higher performance and independence from host environments.

Thus, Scripting languages are essentially a subset of programming languages. JavaScript, in


particular, exhibits characteristics of both categories. It functions as a scripting language
due to its interpreted nature and as a lightweight programming language because of its
versatility and broader capabilities. Therefore, JavaScript serves as both a scripting
language and a general-purpose programming tool, suitable for tasks ranging from simple
automation to complex application development.
JavaScript: Client-Side or Server-Side
Language?
• Traditionally, JavaScript has been synonymous with client-side scripting, bringing
interactivity and dynamism to web pages.
• Initially designed for the client-side, JavaScript transforms static web pages into
engaging, interactive experiences. It enables functionalities like dynamic content
updates, responsive user interfaces, form handling, and animations—all crucial elements
of modern web design.
• However, JavaScript's capabilities have evolved significantly, bridging the gap between
front-end and back-end development.
• With the advent of Node.js, an open-source JavaScript runtime, JavaScript has cemented
its role as a server-side language as well. Node.js allows developers to execute JavaScript
on the server, enabling the creation of scalable web applications, APIs, and robust
backend systems.
• This evolution highlights JavaScript’s versatility, as it excels in both client-side interactivity
and server-side functionality. Referring to it solely as "client-side" or "server-side"
overlooks its comprehensive nature—it’s a language that seamlessly integrates both
domains, making it indispensable in modern web development.
• JavaScript is an implementation of the ECMAScript standard.
• Have you ever come across terms like ES6 or ES7 in discussions about JavaScript?
• JavaScript’s official name is ECMAScript. The numbers, such as ES6 and ES7, denote
specific versions of the language.
• JavaScript, created over 25 years ago, has continuously evolved with time. In its early
days, updates were infrequent, taking years to implement new features. Today, however,
JavaScript follows an annual update schedule, introducing fresh features and
improvements every year.
Java Script Advantages
• An Interpreted Language
• Embedded Within HTML
• Minimal Syntax – Easy to Learn
• Quick Development
• Designed for Simple, Small Programs
• Performance
• Procedural Capabilities
• Designed for Programming User Events
• Easy Debugging and Testing
• Platform Independence/ Architecture Neutral
Comments in Java Script
Comments in JavaScript are used to explain code, make it more readable, or temporarily
disable code during debugging.

Single-line Comments
• Begin with //.
• Everything after // on that line is ignored by the interpreter.
// This is a single-line comment
let x = 10; // This variable stores the value 10
Multi-line Comments
• Enclosed between /* and */.
• Useful for longer explanations or temporarily disabling blocks of code.
/*
This is a multi-line comment.
It can span multiple lines
and is often used for detailed explanations.
*/
let y = 20;
Ways To write Java Script
• External Java Script : Java Scripts can reside in a separate page.
• Internal JavaScript : JavaScript can be embedded in HTML documents -- in the <head>, in
the <body>, or in both.
• In line JavaScript : JavaScript object attributes can be placed in HTML element tags. e.g.,
<body onLoad="alert('WELCOME')">
Variables in Java Script
• Variables in JavaScript are used to store data values, which can be referenced and
manipulated later in the code. Variables act as containers for storing information.

Declaring Variables
JavaScript allows three keywords for variable declaration:
• var: The older way of declaring variables. It has function scope and is prone to issues due
to hoisting.
• let: Introduced in ES6, it provides block scope and is more modern and safer to use.
• const: Used for constants; values cannot be reassigned after being initialized.
Declaring variables using var
var greeting = “GoodMorning"; // Function-scoped variable

Declaring variables using let


let age = 28; // Block-scoped variable

Declaring constants using const


const country = “India"; // Value cannot be changed
Java Script Identifiers
• All JavaScript variables must be identified with unique names.
• These unique names are called identifiers.
Identifiers can be short names (like x and y), or more descriptive names (age, sum,
totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
• Names can contain letters, digits, underscores and dollar signs.
• Names must begin with a letter.
• Names can also begin with $ and _
• Names are case sensitive (y and Y are different variables).
• Reserved words (like JavaScript keywords) cannot be used as names.
Data Types in Java Script
Primitive data types
– Number: integer & floating-point numbers.
– Boolean: true or false.
– String: a sequence of alphanumeric characters.
Composite data types (or Complex data types)
– Object: a named collection of data
– Array: a sequence of values (an array is actually a predefined object)
Special data types
– Null: the only value is "null" – to represent nothing.
– Undefined: the only value is "undefined" – to represent the value of an uninitialized
variable
Scopes in JS
1. Global Scope
• Variables declared outside of any function or block are in the global scope.
• They are accessible from anywhere in the program, including inside functions or
blocks.
• In browsers, variables in the global scope are added to the window object.
• Avoid polluting the global scope by declaring too many global variables.
2. Function Scope
• Variables declared with var, let or const inside a function are only accessible within
that function. This is function scope.
• Variables declared with var are function-scoped, meaning they are accessible
throughout the entire function, even before their declaration (due to hoisting).
• Variables declared with let and const are block-scoped within the function.
3. Block Scope
• Block scope applies to variables declared with let and const inside a block ({}), such
as inside loops, conditionals, or other code blocks.
• Variables declared with var do not have block scope; they are function-scoped.

Thus,
• Global Scope: Variables are accessible anywhere in the program.
• Function Scope: Variables are accessible only within the function they are declared in.
• Block Scope: Variables are accessible only within the block (e.g., if, for) they are declared
in. let and const are block-scoped, while var is function-scoped.
JavaScript Reserved Key-Words
Reserved keywords are special words that have predefined meanings in the language syntax. These words are
reserved by the JavaScript engine and cannot be used as variable names, function names, or identifiers in the
program.
Using them incorrectly will lead to syntax errors.
Operators in JS
Different types of JavaScript operators are:
• Arithmetic Operators
• Assignment Operators
• Comparison Operators
• Logical Operators
• Bitwise Operators
• Ternary Operators
• Type Operators
Arithmetic Operators
Assignment Operators
Comparison Operator
Logical Operators
Bitwise Operators
JavaScript Operator’s Precedence
Conditional Statements
if Statement
Executes a block of code if the condition evaluates to true.
if (condition) {
// Code to execute if condition is true
}
if...else Statement
Executes one block of code if the condition is true and another if the condition is false.
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
if...else if...else Statement
Tests multiple conditions and executes a block of code for the first true condition.

if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else {
// Code to execute if no condition is true
}
Switch Statement
Tests a variable against multiple values and executes the code block corresponding to the
matching case.
switch (expression) {
case value1:
// Code to execute if expression === value1
break;
case value2:
// Code to execute if expression === value2
break;
default:
// Code to execute if no case matches
}
break Statement
Terminates the current loop or switch statement and transfers control to the statement
after it. Commonly used in loops or switch cases.
continue Statement
Skips the rest of the current iteration in a loop and jumps to the next iteration. Used inside
loops when you want to skip certain iterations based on a condition.
return Statement
Exits from a function and optionally returns a value. Used inside functions when you want
to send a value back to the caller or stop function execution.
Thus,
break exits a loop or switch early. Works in loops and switch.
Continue skips the rest of the current loop iteration. Works only in loops.
return exits a function and optionally returns a value. Works only inside functions.
JavaScript Loops
for Loop
Used when you know in advance how many times the loop should run.
It has three components:
Initialization: Sets a starting point (e.g., let i = 0).
Condition: Defines when the loop should stop (e.g., i < 5).
Increment/Decrement: Updates the loop variable (e.g., i++).
while Loop
Repeats as long as the condition evaluates to true.
Ideal for cases where the number of iterations is unknown.
do...while Loop
Similar to while, but guarantees the loop runs at least once before checking the
condition.
for...of Loop
Iterates through values of an iterable object (e.g., arrays, strings).
Suitable for processing lists or collections.
The for...of loop is used to iterate over iterable objects, such as arrays, strings, maps, sets,
and more. It provides a simple way to access the values of the iterable.
for (const element of iterable) {
// Code to execute for each element}
for...in Loop
Iterates through keys/properties of an object.
Useful for accessing object properties or array indices.
The for...in loop is used to iterate over the enumerable properties of an object. It is
primarily designed for objects, not for arrays.
for (const key in object) {
// Code to execute for each property }
Dialog Boxes
• Alert, confirm, and prompt are built-in functions that create dialog boxes for user
interaction. They are part of the Window interface and are commonly used for simple
user notifications or input.
• Alert
 The alert() function displays a simple dialog box with a specified message and an
"OK" button. It is primarily used to inform the user about something.
 alert(message);
• Confirm
 The confirm() function displays a dialog box with a specified message, along with
"OK" and "Cancel" buttons. It returns a boolean value: true if the user clicks "OK"
and false if the user clicks "Cancel". This is useful for asking for user confirmation.
 let result = confirm(message);

• Prompt
 The prompt() function displays a dialog box that prompts the user for input. It
includes an input field for the user to type in their response. The function returns the
input value as a string, or null if the user clicks "Cancel".
 let userInput = prompt(message, default);
Taking Inputs from User
• For asking input from user we need to use window prompt or HTML text box.
• The window.prompt() method displays a dialog box that prompts the user for input. It
takes two optional parameters: a message to display and a default value.
• You can also create a more user-friendly interface using HTML input elements. This
allows for more control over the layout and styling of your input forms.
• Thus, both window.prompt() and HTML text boxes can be used to gather input from
users, but they serve different purposes and offer different user experiences. For simple
applications or quick prototypes, window.prompt() can be sufficient. However, for
production applications, using HTML input elements is generally preferred due to their
flexibility, styling options, and better user experience.
JavaScript Functions
• Function are blocks of Java Script code that perform a specific task and often return
value.

Function are two types:


• Built – in Function
• User Define Function
Built-in Functions In JavaScript
• Java script provides several built-in functions that can be used to perform explicit type
conversions.
• Eval() - used to convert a string expression to a numeric value.
• parseInt() - used to convert a string value to an integer.
• Parsefloat() - return the first floating point number contained in a string.
User Defined Functions In JavaScript
• Functions offer the ability to group together Java Script program code that performs a
specific task into a single unit that can be used repeatedly whenever required in a Java
Script program.
• User defined function
 Need to be declared
 Coded
 Invoked
 Can be return value
• Functions are declared and created using the “function” keyword
• A function can comprise of following:
 A name of the function
 A list of parameters that will accept values passed to the function when called.
 A block of Java script code that defines what the function does.
• Syntax:
function function_name (parameter1, parameter2, ….)
{
…...... // block of java script code
}
• function_name is case sensitive, can include (_) and has to start with a letter.
JavaScript Arrays
• An array in JavaScript is a data structure that allows you to store multiple values in a
single variable. Arrays are a type of object and can hold elements of different data types,
including numbers, strings, booleans, objects, or even other arrays. This flexibility is a
direct result of JavaScript’s dynamic typing and object-oriented nature.
• Array elements are indexed starting from 0. The index is used to access individual
elements.
• The .length property returns the number of elements in the array.
• Accessing Elements: Use the index to access or modify elements in the array.
• If arr is [15,20,25,30]
• arr[1] = 25; // Changes 20 to 25
Characteristics of JavaScript Arrays
• Dynamic Typing (Heterogeneous):
Unlike languages like C or Java, JavaScript arrays do not require a fixed data type for
their elements. This means an array can contain a mix of different types:
let arr = [42, "hello", true, { key: "value" }, [1, 2, 3]];

• Index-Based Access:
Elements in an array are accessed using zero-based indexing, where the first element
has an index of 0:
let arr = [10, 20, 30];
console.log(arr[0]); // Outputs: 10
• JavaScript array-copy operations create shallow copies.
• Length Property:
JavaScript arrays have a dynamic length property that automatically updates when
elements are added or removed:
let arr = [1, 2, 3];
console.log(arr.length); // Outputs: 3
Creating Arrays in JS
1. Using Array Literals
This is the simplest and most common way to create an array. You simply define the array
using square brackets [].
let fruits = ["apple", "banana", "cherry"];
console.log(fruits); // ["apple", "banana", "cherry"]
2. Using the Array Constructor
You can also create arrays using the Array constructor, although this method is less
common.
Creating an array with elements
let numbers = new Array(1, 2, 3, 4);
console.log(numbers); // [1, 2, 3, 4]
Creating an array with a specific length (empty slots)
let emptyArray = new Array(5); // Array with 5 empty slots
console.log(emptyArray); // [ <5 empty items> ]
Iterating over Arrays
• for loop: Traditional, flexible.
• forEach(): Ideal for simply performing actions on elements.
• for...of: Cleaner syntax, ideal for arrays.
• map(): For transforming array elements.
• filter(): For selecting elements based on a condition.
• reduce(): For reducing the array to a single value.
Memory and Implementation
• Internally Represented as Objects:
Arrays in JavaScript are specialized objects where indices are property names.
• Dynamic Resizing:
JavaScript arrays can grow or shrink dynamically, unlike static arrays in languages like C.
• Storage:
JavaScript arrays may be stored in contiguous memory blocks for optimization, but
they are not strictly required to be contiguous.
Applications of Arrays in JavaScript
• Storing lists of related data (e.g., names, scores).
• Implementing stacks or queues using array methods.
• Managing dynamic datasets for web applications.
Objects in JS
What are Objects?
• In JavaScript, objects are fundamental data structures that allow you to store collections
of related data and functionality. They consist of key-value pairs, where keys are strings
(or Symbols) and values can be of any data type, including other objects. Objects can also
contain methods, which are functions associated with the object.
• JavaScript objects are versatile and allow for the creation of complex data structures.
They can hold various types of data and methods, making them essential for organizing
and managing data in applications. Understanding how to create, access, modify, and
iterate over objects is crucial for effective JavaScript programming.

• Objects are containers for Properties and Methods.


• Properties are named Values.
• Methods are Functions stored as Properties.
• Properties can be primitive values, functions, or even other objects.
Creating Objects
• Object Literals: The most common way to create an object is using an object literal,
which is a comma-separated list of key-value pairs enclosed in curly braces {}.
const car = {
make: "Toyota",
model: “Innova",
year: 2022,
start: function() {
console.log("Car started");
}
};
• Object Constructor: You can also create objects using the Object constructor.
const car = new Object();
car.make = "Toyota";
car.model = “Innova";
car.year = 2024;
Accessing Object Properties

• Dot Notation: You can access properties using dot notation.


console.log(car.make);

• Bracket Notation: Alternatively, you can use bracket notation, which is useful for dynamic
property names.
console.log(car["model"]);
Hoisting in JavaScript
• Hoisting is a behavior where variable and function declarations are moved to the top of
their containing scope during the compile phase, before the code is executed. This
means that you can use variables and functions in your code before they are actually
declared.
• Variable hoisting refers to the behavior where variable declarations are moved to the top
of their containing scope during the compilation phase. This means that you can use
variables before they are declared in the code.
• var is initialized to undefined, allowing it to be accessed before its declaration.
• let and const are not initialized, which leads to a ReferenceError if accessed before their
declaration, due to the temporal dead zone.
• Variables declared with let and const exist in the TDZ from the start of their scope until
their declaration is encountered. Accessing them in this zone results in a ReferenceError.
• The "Temporal Dead Zone" (TDZ) refers to the period of time during which a variable is in
a state of existence but is not yet accessible. This applies specifically to variables declared
with let and const.
• Thus, declarations (variables and functions) are hoisted, not initializations.
• Use let and const to avoid unintended bugs caused by hoisting, as they make the
behavior of your code more predictable.
JavaScript Events
What are Events?
• Events in JavaScript, refer to actions that are detected by a JavaScript program when you
perform a particular task.
• For example, onclick event is detected by the program when you click the mouse button.
• JavaScript events are actions or occurrences that happen in the browser that JavaScript
can respond to. These events are typically triggered by the user (e.g., clicking a button,
typing in a text field, or moving the mouse) or by the browser itself (e.g., page load,
errors, or resizing the window). JavaScript can listen for these events and execute specific
code in response, enabling interactive and dynamic functionality on web pages.
• Thus, the change in the state of an object is an event.
How to write Events?
• The syntax for working with events in JavaScript depends on how you attach the event
handler to an element. There are three main ways to do this inline event handlers, DOM
property event handlers and event listeners.
• Inline Event Handler
 You can directly include the event in the HTML element using attributes like onclick,
onmouseover, etc.
 <element event="JavaScript code"></element>

• DOM Property Event Handler


 You assign a JavaScript function to an event property of a DOM element.
 element.event = functionName;
• Event Listener
 The addEventListener method is a more modern and flexible way to attach events.
 element.addEventListener(event, function, useCapture);
Feature Inline Event DOM Property Event Listeners
Handlers Handlers

Ease of Use Easy for small tasks Simple for single Slightly more
handlers verbose

Readability Reduces readability Improves with Best readability in


external JS modern
applications

Multiple Handlers Not supported Not supported Fully supported


Separation of Poor Better Best
Concerns

Debugging Difficult Easier Easier


• Thus,
 Use inline event handlers sparingly, primarily for quick demos or prototypes.
 Use DOM property handlers for simple scripts or when only one handler per event is
needed.
 Prefer event listeners in modern applications for better flexibility and maintainability.
addEventListners
• addEventListener() is a method in JavaScript used to attach an event handler to an HTML
element. This method allows you to define a function that will run when a specified
event occurs on the element (e.g., a click, mouse movement, or a key press).
• element.addEventListener(event, function, useCapture);
Form Events
Keyboard Events
Mouse Events
Window Events
Event Object
• A special object which has details about particular event.
• The event object in JavaScript is a built-in object that contains detailed information about
an event that occurs in the browser. It is automatically passed to the event handler
function when an event is triggered.
Key Features of the Event Object
• Type of Event: Indicates the type of event, such as click, keydown, mouseover, etc., using
the type property.
• Target Element: Refers to the element where the event occurred via the target property.
• Default Actions: Allows you to prevent default browser actions using the preventDefault()
method.
• Mouse and Keyboard Data: Provides details specific to the event, such as:
• Mouse events: clientX, clientY, button
• Keyboard events: key, code
Event Propagation
• Event bubbling and event capturing (or trickling) are two phases of event propagation in
the DOM. Understanding these concepts helps developers manage how events are
handled when they are triggered on nested elements.
• Event Bubbling:
 Event bubbling is the default mode of event propagation in which an event starts
from the innermost element that triggered the event and bubbles up to its parent
elements until it reaches the document or window object.
 The event is first captured and handled by the innermost element, and then it
bubbles up to its parent, then the next parent, and so on, until it reaches the root of
the DOM.
• Event Capturing:
• Event capturing is an alternative mode of event propagation where the event starts
from the outermost element and trickles down to the innermost element that
triggered the event.
• The event is first captured by the parent elements and propagates down to the
target element.
• Need to use true as 3rd parameter.
Event Propagation Stages

• Capturing Phase: The event starts from the outermost element and propagates down the
DOM tree to the target element.
• Target Phase: The event has reached the target element, which is the element that
triggered the event. Event handlers added to the target element itself run during this
phase.
• Bubbling Phase: The event bubbles up from the target element to the outer elements,
propagating back up the DOM tree.
Escape Sequence
• An escape sequence is a sequence of characters that does not represent itself when used
inside a character or string, but is translated into another character or a sequence of
characters that may be difficult or impossible to represent directly.
JavaScript Classes and Modules
• Templates for creating objects.
• Encapsulate data and behavior.
• Provide a blueprint for defining reusable structures.
• Support inheritance for sharing behavior among different objects.
• Enable encapsulation, improving modularity and maintainability.
How to define a class
class ClassName {
constructor(parameter1, parameter2) {
this.property1 = parameter1;
this.property2 = parameter2;
}
method1() {
// Code for method
}
}
What are constructors
• Constructors are special functions used to create and initialize objects. They serve as
templates for creating objects with predefined properties and methods. A constructor
function is invoked with the new keyword.
• How is it different to normal functions?
 The main difference lies in between the purpose of the usage of the both.
 Constructor is used to create and initialize objects while regular function performs
specific tasks.
 Invocation of constructor is done by using new keyword while function is directly
called by its name.
Getter and Setter Methods
• Encapsulate data access.
• Provide controlled ways to get or set properties.
• Ensure data integrity by validating inputs.
• Enable derived or computed properties based on other class fields.
• It enhances modularity and abstraction and reduces direct manipulation of object
properties.
Modules
• Modules are reusable pieces of code that can be exported from one file and
imported into another. They help organize code into smaller, maintainable units and
avoid global namespace pollution. JavaScript modules enable a more structured and
scalable approach to building applications.
• Thus, modules are a way to organize and encapsulate code in a modular fashion,
allowing developers to break down their applications into smaller, reusable pieces.
This modular approach helps in managing dependencies, improving code
maintainability and avoiding global namespace pollution.
• A module is a file that contains code (functions, objects, variables) that can be
exported and imported by other modules. In JavaScript, modules can be defined
using the export and import statements.
• Exporting: You can export variables, functions, or classes from a module using the export
keyword. There are two types of exports:
// myModule.js
export const myVariable = 42;
export function myFunction() { /* ... */ }

• Importing: You can import exported items from a module using the import statement.
import { myVariable, myFunction } from './myModule.js’;

• Each module is typically defined in its own file, and the file extension is usually .js. When
using modules in a browser, you need to include the type="module" attribute in the
<script> tag.
<script type="module" src="main.js"></script>
Exception Handling in JavaScript
• Exception handling in JavaScript is a process that allows developers to handle errors
gracefully, preventing abrupt program terminations.
• Used to detect and respond to errors.
• It improves code robustness and maintainability.

Where to use?
• Handling user input errors.
• Managing failed network requests.
• Protecting against unexpected code behavior.
Why Exception Handling?
• Prevents Crashes: Catches runtime errors and prevents the program from stopping
unexpectedly.
• Enhanced User Experience: Provides meaningful feedback and keeps the program
running smoothly.
• Debugging: Helps pinpoint issues by capturing error details.
Exception Handling Blocks
• try block:
 Contains code that may throw an error.
 Executes normally if no error occurs.

• catch block:
 Executes only if an error is thrown in the try block.
 Captures and handles the error, making the program resilient.

• finally block:
 Always executes after the try block, regardless of whether an error occurred or not.
 Useful for cleanup operations (e.g., closing files, freeing resources).

• throw statement:
 Used to create custom errors and force an error to be thrown.
Syntax
try {
// Code that may throw an error
} catch (error) {
// Code to handle the error
} finally {
// Code that runs no matter what
}
• The try block attempts to run code that might fail.
• The catch block handles any error that occurs, accessing the error object.
• The finally block runs code that must execute regardless of an error occurring
(e.g., closing a connection).
Throw
• The throw statement is used to create and throw an error. When you use throw, it
interrupts the execution of the program and passes control to the nearest catch block, or
terminates the program if no catch block is available.
throw expression;
• The expression can be any valid JavaScript expression, such as:
• A string
• A number
• An object (usually an instance of Error or its subclasses)
• You need to throw an error using the Error object.

You might also like