Chapter 5
Chapter 5
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
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.
• 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.
• 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>
Ease of Use Easy for small tasks Simple for single Slightly more
handlers verbose
• 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.