KEMBAR78
Web Essentials Unit 4 | PDF | Java Script | World Wide Web
0% found this document useful (0 votes)
5 views29 pages

Web Essentials Unit 4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views29 pages

Web Essentials Unit 4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

CSS103J-Web Essentials

Unit IV- Javascript


JavaScript Introduction – Variables and Data Types-Statements – Operators – Literals-Functions -
Objects-Arrays-Built-in Objects- Regular Expression, Exceptions, Event handling.

JavaScript Introduction

JavaScript is a versatile, dynamically typed programming language that brings life to


web pages by making them interactive. It is used for building interactive web
applications, supports both client-side and server-side development, and integrates
seamlessly with HTML, CSS, and a rich standard library.

 JavaScript is a single-threaded language that executes one task at a time.


 It is an interpreted language which means it executes the code line by line.
 The data type of the variable is decided at run-time in JavaScript, which is why it
is called dynamically typed.
 JavaScript is a single-threaded language that executes one task at a time.
 It is an interpreted language which means it executes the code line by line.
 The data type of the variable is decided at run-time in JavaScript, which is why it
is called dynamically typed.
<html>
<head></head>
<body>
<h1>Check the console for the message!</h1>
<script>
// This is our first JavaScript program
console.log("Hello, World!");
</script>
</body>
</html>
In this example
 The<script> tag is used to include JavaScript code inside an HTML document.
 console.log() prints messages to the browser's developer console. Open the
browser console to see the "Hello, World!" message.
"Hello World" Program in Server Console
We can also print the "Hello World" program directly into the console terminal
without embedded it into HTML. Create an index.js file and add the code to it.
// This is a comment
console.log("Hello, World!");
Run it in your terminal with:
node hello.js
Output:
Hello, World!
Comments in JavaScript
Comments are notes in your code that the JavaScript interpreter ignores. They’re
great for explaining what your code does or for testing purposes.
 Single-line comment: Starts with //
// This is a single-line comment
 Multi-line comment: Enclosed in /* */
/* This is a multi-line comment
spanning multiple lines */
Key Features of JavaScript
Here are some key features of JavaScript that make it a powerful language for web
development:
 Client-Side Scripting:JavaScript runs on the user's browser, so has a faster
response time without needing to communicate with the server.
 Versatile: JavaScript can be used for a wide range of tasks, from simple
calculations to complex server-side applications.
 Event-Driven: JavaScript can respond to user actions (clicks, keystrokes) in
real-time.
 Asynchronous: JavaScript can handle tasks like fetching data
from servers without freezing the user interface.
 Rich Ecosystem: There are numerous libraries and frameworks built on
JavaScript, such as React, Angular, and Vue.js, which make development faster
and more efficient.
Client Side and Server Side nature of JavaScript

Server-Side:
 Involves interacting with databases, manipulating files, and generating responses.
 Node.js and frameworks like Express.js are widely used for server-side
JavaScript, enabling full-stack development.
Programming Paradigms in JavaScript
JavaScript supports both imperative and declarative programming styles:
 Imperative Programming: Focuses on how to perform tasks by controlling the
flow of computation. This includes approaches like procedural and object-
oriented programming, often using constructs like async/await to handle
asynchronous actions.
 Declarative Programming: Focuses on what should be done rather than how it’s
done. It emphasizes describing the desired result, such as with arrow functions,
without detailing the steps to achieve it.
Limitations of JavaScript
Despite its power, JavaScript has some limitations to consider:
 Security Risks : JavaScript can be used for attacks like Cross-Site Scripting
(XSS), where malicious scripts are injected into a website to steal data by
exploiting elements like <img>, <object>, or <script> tags.
 Performance : JavaScript is slower than traditional languages for complex tasks,
but for simple tasks in a browser, performance is usually not a major issue.
 Complexity : To write advanced JavaScript, programmers need to understand
core programming concepts, objects, and both client- and server-side scripting,
which can be challenging.
 Weak Error Handling and Type Checking : JavaScript is weakly typed,
meaning variables don’t require explicit types. This can lead to issues as type
checking is not strictly enforced.
JavaScript Versions

Let’s take a look at the different versions of ECMAScript, their release years, and
the key features they introduced
Version Year Key Features

ES5 2009 strict mode, JSON, getters/setters

let/const, classes, arrow


2015
ES6 functions

ES7- 2016- async/await, BigInt, optional


ES13 2022 chaining

ES14 2023 toSorted, findLast, static blocks

Variables and Data Types


Variables and data types are foundational concepts in programming, serving as the
building blocks for storing and manipulating information within a program. In
JavaScript, getting a good grasp of these concepts is important for writing code that
works well and is easy to understand.

Variables
A variable is like a container that holds data that can be reused or updated later in
the program. In JavaScript, variables are declared using the keywords var, let,
or const.
1. var Keyword
The var keyword is used to declare a variable. It has a function-scoped or globally-
scoped behavior
var n = 5;

console.log(n);

var n = 20; // reassigning is allowed

console.log(n);
Output
5
20

2. let Keyword
The let keyword is introduced in ES6, has block scope and cannot be re-declared in
the same scope.

let n= 10;

n = 20; // Value can be updated

// let n = 15; //can not redeclare

console.log(n)
Output
20

3. const Keyword
The const keyword declares variables that cannot be reassigned. It's block-scoped as
well.
Output
100
For more details read the article - JavaScript Variables
Data Types
JavaScript supports various datatypes, which can be broadly categorized into
primitive and non-primitive types.
Primitive Datatypes
Primitive datatypes represent single values and are immutable.
1. Number: Represents numeric values (integers and decimals).
let n = 42;
let pi = 3.14;
2. String: Represents text enclosed in single or double quotes.
let s = "Hello, World!";
3. Boolean: Represents a logical value (true or false).
let bool= true;
4. Undefined: A variable that has been declared but not assigned a value.

let notAssigned;

console.log(notAssigned);
Output
undefined
5. Null: Represents an intentional absence of any value.
let empty = null;
6. Symbol: Represents unique and immutable values, often used as object keys.
let sym = Symbol('unique');
7. BigInt: Represents integers larger than Number.MAX_SAFE_INTEGER.
let bigNumber = 123456789012345678901234567890n;
Non-Primitive Datatypes
Non-primitive types are objects and can store collections of data or more complex
entities.
1. Object: Represents key-value pairs.
let obj = {
name: "Amit",
age: 25
};
2. Array: Represents an ordered list of values.
let a = ["red", "green", "blue"];
3. Function: Represents reusable blocks of code.
function fun() {
console.log("GeeksforGeeks");
}
Exploring JavaScript Datatypes and Variables:
Understanding Common Expressions
console.log(null === undefined)
undefined signifies that a variable has been declared but not assigned a value. Despite
their similar purpose, they are not strictly equal ( ===) to each other.
 null === undefined evaluates to false because JavaScript does not perform type
coercion with ===.
console.log(5 > 3 > 2)
 Expression: 5 > 3 > 2
 Result: false
At first glance, this expression may appear to be checking if 5 is greater than 3 and 3
is greater than 2, but JavaScript evaluates it left-to-right due to its operator
precedence.
 First, 5 > 3 evaluates to true.
 Then, true > 2 is evaluated, which in JavaScript results in 1 > 2 (since true is coerced
to 1), which evaluates to false.
So, 5 > 3 > 2 evaluates to false.
console.log([] === [])

Statements
JavaScript statements are programming instructions that a computer executes. A
computer program is essentially a list of these "instructions" designed to perform
tasks. In a programming language, such instructions are called statements.
Types of Statements
1. Variable Declarations (var, let, const)
In JavaScript, you can declare variables using var, let, or const . let and const are
used in modern JavaScript for block-scoped variables, while var is function-scoped
and generally considered outdated.

let name = "Mohan"; // Declaration with 'let'

const age = 25; // Declaration with 'const' (constant value)

var isActive = true; // Declaration with 'var' (older version)


2. Assignment Statement
An assignment statement is used to assign a value to a variable. You can assign any
type of value, including strings, numbers, and objects, using the assignment operator
=.

let number = 10; // Assigning a number

let message = "Hello, World!"; // Assigning a string


3. Expression Statements
An expression in JavaScript is any valid unit of code that resolves to a value. When
an expression is executed, it can perform an action (e.g., calculation, function call)
and return a result. An expression can also be used as a statement.

x = y + 10; // Expression statement

console.log(x); // Expression statement using a function call


4. Control Flow Statements
Control flow statements are used to control the order in which statements are
executed in a program. Examples include if, else, switch, while, and for loops

let number = 10;

if (number > 5) {

console.log("Number is greater than 5");

}
5. Function Declarations
A function declaration is a statement that defines a function in JavaScript. Functions
are reusable blocks of code designed to perform specific tasks.

function greet(name) {

return "Hello, " + name;

console.log(greet("Alisha"));
Some commonly used keywords are:
Keyword Description

var Used to declare a variable

let Used to declare a block variable

const Used to declare a block constant

Used to decide if certain block will get


if executed or not

Executes a block of codes depending on


switch different cases
Keyword Description

Executes a block of statements till the


for condition is true

function Used to declare a function

return Used to exit a function

Used to handle errors in a block of


try statements

break Used to terminate a loop

continue Used to continue a loop

Operators
JavaScript operators are symbols or keywords used to perform operations on values
and variables. They are the building blocks of JavaScript expressions and can
manipulate data in various ways.
There are various operators supported by JavaScript:
1. JavaScript Arithmetic Operators
Arithmetic Operators perform mathematical calculations like addition, subtraction,
multiplication, etc.

const sum = 5 + 3; // Addition


const diff = 10 - 2; // Subtraction
const p = 4 * 2; // Multiplication
const q = 8 / 2; // Division
console.log(sum, diff, p, q);
Output
8884
 + adds two numbers.
 - subtracts the second number from the first.
 * multiplies two numbers.
 / divides the first number by the second.
2. JavaScript Assignment Operators
Assignment operators are used to assign values to variables. They can also perform
operations like addition or multiplication while assigning the value.
let n = 10;
n += 5;
n *= 2;
console.log(n);
Output
30
 = assigns a value to a variable.
 += adds and assigns the result to the variable.
 *= multiplies and assigns the result to the variable.
3. JavaScript Comparison Operators
Comparison operators compare two values and return a boolean (true or false). They
are useful for making decisions in conditional statements.
console.log(10 > 5);
console.log(10 === "10");

Output
true
false
 > checks if the left value is greater than the right.
 === checks for strict equality (both type and value).
 Other operators include <, <=, >=, and !==.
4. JavaScript Logical Operators
Logical operators are mainly used to perform the logical operations that determine the
equality or difference between the values.
const a = true, b = false;
console.log(a && b); // Logical AND
console.log(a || b); // Logical OR Output
false
true
 && returns true if both operands are true.
 || returns true if at least one operand is true.
 ! negates the boolean value.
5. JavaScript Bitwise Operators
Bitwise operators perform operations on binary representations of numbers.
const res = 5 & 1; // Bitwise AND
console.log(res);

Output
1
 & performs a bitwise AND.
 | performs a bitwise OR.
 ^ performs a bitwise XOR.
 ~ performs a bitwise NOT.
6. JavaScript Ternary Operator
The ternary operator is a shorthand for conditional statements. It takes three
operands.
const age = 18;
const status = age >= 18 ? "Adult" : "Minor";
console.log(status);

Literals
In JavaScript, literals are fixed values that are represented directly in the source
code. They are not variables and their values cannot be changed during program
execution. Literals are used to represent various data types.
Here are the main types of literals in JavaScript:
 Numeric Literals:
Represent numerical values.
 Integer Literals: Whole numbers, e.g., 10, -5, 0.
 Floating-point Literals: Numbers with decimal points or exponents, e.g., 3.14, 1.2e-5.
 String Literals:
Represent sequences of characters enclosed in single quotes ( ') or double quotes ( "), e.g., 'hello
world', "JavaScript".

 Boolean Literals:
Represent truth values, which are either true or false.
 Array Literals:
Represent collections of values, enclosed in square brackets ( []), e.g., [1, 2, 3], ['apple', 'banana'].
 Object Literals:
Represent collections of key-value pairs, enclosed in curly braces ( {}), e.g., { name: 'John', age:
30 }.

 RegExp Literals:
Represent regular expressions, used for pattern matching, enclosed in forward slashes ( /),
e.g., /abc/i.
 Template Literals (Template Strings):
Introduced in ES6, these are string literals enclosed in backticks (`` ` ``). They allow for
embedded expressions using ${} and support multiline strings without explicit newline
characters, e.g., `` Hello, ${name}! ``.
JavaScript supports various types of literals which are listed below:

 Numeric Literal

 Floating-point Literal

 Boolean Literal

 String Literal

 Array Literal

 Regular Expression Literal

 Object Literal

Let's see some code examples to see each one of these.

Numeric Literal in JS
 It can be a decimal value(base 10), a hexadecimal value(base 16), or an octal value(base
8).

 Decimal numeric literals consist of a sequence of digits (0-9) without a leading 0(zero).
These are integer values that you will be using mostly in your JS code.

 Hexadecimal numeric literals include digits(0-9), letters (a-f) or (A-F).

 Octal numeric literals include digits (0-7). A leading 0(zero) in a numeric literal indicates
octal format.

Numeric Literals Example:

Here is an example of the different types of numeric literals.

120 // decimal literal

021434 // octal literal

0x4567 // hexadecimal literal

Floating-Point Literal in JS
 It contains a decimal point, for example, the value 1.234

 A fractional value is a floating-point literal.

 It may contain an Exponent.

Floating-Point Literal Example:

Here is an example of floating point literals.

6.99689 // floating-point literal

-167.39894 // negative floating-point literal


Boolean Literal in JS
Boolean literal can have two values, either true or false.

true // Boolean literal

false // Boolean literal

String Literal in JS
A string literal is a combination of characters (alphabets or numbers or special characters)
enclosed within single('') or double quotation marks ("").

"Study" // String literal

'tonight' // String literal

String literals can have some special characters too which are listed in the table below.

Character Description

\b It represents a backspace.

\f It represents a Form Feed.

\n It represents a new line.

\r It represents a carriage return.

\t It represents a tab.

\v It represents a vertical tab.

\' It represents an apostrophe or a single quote.


Character Description

\" It represents a double quote.

\\ It represents a backslash character.

\uXXXX It represents a Unicode character specified by a four-digit hexadecimal number.

Array Literal in JS
 An array literal is an array in JavaScript created using the square bracket ([]) with or
without values.

 Whenever you create an array using an array literal, it is initialized with the elements
specified in the square bracket.

JavaScript Array Literal Example:

Here is a quick example,

["Abhishek","Supriya","Joey"]; // Array literal

Even when you assign an array to a variable, if you create the array directly using the square
brackets, it is an array literal.

let students = ["Abhishek","Supriya","Joey"]; // Array literal

In JavaScript, you can create an array using the Array object or using an array literal.

Regular Expression Literal in JS


Regular Expression is a bunch of characters defining a pattern, that is used to match a character
or string in some text. It is created by enclosing the regular expression string between forward
slashes.

JavaScript Regular Expression Example:

Here is an example,
var myregexp = /ab+c/; // Regular Expression literal

var myregexp = new RegExp("abc"); // Regular Expression object

Object Literal in JS
It is a collection of key-value pairs enclosed in curly braces ({}). The key-value pairs are
separated using a comma.

JavaScript Object Literal Example:

Here is an example,

var games = {cricket :11, chess :2, carom: 4} // Object literal

In the code example above, on the right side of the equals to or assignment operator, we have the
object literal.

JavaScript Keywords
Every programming language has its keywords or reserved words. Every keyword is created to
perform a specific task or to be used for a specific purpose, which is known to the compiler or
the interpreter. JavaScript supports a rich set of keywords, listed in the below table.

Keyword Description

for The for keyword is used to create a for loop.

do/while They do and while both keywords are used to create loops in JavaScript.
Keyword Description

if/else The if and else keywords are used to create conditional statements.

continue The continue keyword is used to resume the loop.

break It is used to break the loop.

function The function keyword is used to declare a function.

debugger It is used to call the debugger function

class The class keyword is used to declare the class.

return Return keyword is used to return function from the function.

export Used to export some functions, variables, etc. from a module

var, let, const The var, let and const keywords are used to declare a variable.
Keyword Description

switch The switch creates various statement blocks and executes only on block depending on the conditio

try/catch It is used to create a block for error handling of the statements.

In the table above we have mentioned some keywords. There are many other keywords as well in
JavaScript.

NOTE: While defining the name of any function or a variable or class, you should not use any
keyword or reserved words.

For example,

let for = 10

console.log(for)

let for = 10

^^^

SyntaxError: Unexpected token 'for'

You get an error because for cannot be used as a variable name.

Functions
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 sum(x, y) {
return x + y;
}
console.log(sum(6, 9)); // output: 15
Function Syntax and Working
A function definition is sometimes also termed a function declaration or function
statement. Below are the rules for creating a function in JavaScript:
 Begin with the keyword function Keyword
 A user-defined function name (In the above example, the name is sum)
 A list of parameters enclosed within parentheses and separated by commas (In
the above example, parameters are x and y)
 A list of statements composing the body of the function enclosed within curly
braces {} (In the above example, the statement is "return x + y").
Return Statement
A function can return a result using the return keyword. This is optional but useful
when you want to send data back from the function.
Function Parameters
Parameters are input passed to a function. In the above example, sum(x , y) takes
two parameters, x and y.
Calling Functions
After defining a function, the next step is to call them to make use of the function.
We can call a function by using the function name separated by the value of
parameters enclosed between the parenthesis.
// Function Definition
function welcomeMsg(name) {
return ("Hello " + name + " welcome to GeeksforGeeks");
}

let nameVal = "User";

// calling the function


console.log(welcomeMsg(nameVal));
// Function Definition
function welcomeMsg(name) {
return ("Hello " + name + " welcome to GeeksforGeeks");
}

let nameVal = "User";


// calling the function
console.log(welcomeMsg(nameVal));
Output
Hello User welcome to GeeksforGeeks

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.
Syntax:
let geeksfor
Output
Hello User welcome to GeeksforGeeks

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.
Syntax:
let geeksfor
Objects

JavaScript is designed on an object-based paradigm. An object is a collection of properties, and a


property is an association between a name (or key) and a value. A property's value can be a
function, in which case the property is known as a method.

Objects in JavaScript, just as in many other programming languages, can be compared to objects
in real life. In JavaScript, an object is a standalone entity, with properties and type. Compare it
with a cup, for example. A cup is an object, with properties. A cup has a color, a design, weight,
a material it is made of, etc. The same way, JavaScript objects can have properties, which define
their characteristics.

In addition to objects that are predefined in the browser, you can define your own objects. This
chapter describes how to use objects, properties, and methods, and how to create your own
objects.

Creating new objects


You can create an object using an object initializer. Alternatively, you can first create a
constructor function and then instantiate an object by invoking that function with
the new operator.

Using object initializers

Object initializers are also called object literals. "Object initializer" is consistent with the
terminology used by C++.

The syntax for an object using an object initializer is:

const obj = {
property1: value1, // property name may be an identifier
2: value2, // or a number
"property n": value3, // or a string
};

Each property name before colons is an identifier (either a name, a number, or a string literal),
and each valueN is an expression whose value is assigned to the property name. The property
name can also be an expression; computed keys need to be wrapped in square brackets.
The object initializer reference contains a more detailed explanation of the syntax.

In this example, the newly created object is assigned to a variable obj — this is optional. If you
do not need to refer to this object elsewhere, you do not need to assign it to a variable. (Note that
you may need to wrap the object literal in parentheses if the object appears where a statement is
expected, so as not to have the literal be confused with a block statement.)
Object initializers are expressions, and each object initializer results in a new object being
created whenever the statement in which it appears is executed. Identical object initializers create
distinct objects that do not compare to each other as equal.

The following statement creates an object and assigns it to the variable x if and only if the
expression cond is true:

let x;
if (cond) {
x = { greeting: "hi there" };
}

Objects created with initializers are called plain objects, because they are instances of Object, but
not any other object type. Some object types have special initializer syntaxes — for
example, array initializers and regex literals.

Using a constructor function


Alternatively, you can create an object with these two steps:

1. Define the object type by writing a constructor function. There is a strong convention, with good
reason, to use a capital initial letter.
2. Create an instance of the object with new.

To define an object type, create a function for the object type that specifies its name, properties,
and methods. For example, suppose you want to create an object type for cars. You want this
type of object to be called Car, and you want it to have properties for make, model, and year. To
do this, you would write the following function:

JS
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
Arrays
Arrays in JavaScript are ordered, zero-indexed collections of values. They are a
fundamental data structure used to store multiple items in a single variable.
Key Characteristics:
 Ordered Collection:
Elements in an array are stored in a specific sequence, and their position is determined by a
numerical index.
 Zero-Indexed:
The first element of an array is at index 0, the second at 1, and so on.
 Resizable:
Arrays in JavaScript are dynamic and can grow or shrink in size as elements are added or
removed.
 Heterogeneous:
Unlike some other languages, JavaScript arrays can store elements of different data types (e.g.,
numbers, strings, booleans, objects, or even other arrays) within the same array.
 Object-based:
Arrays are a special type of object in JavaScript, inheriting properties and methods from
the Array prototype.
Creating Arrays:
Arrays are typically created using array literals, which involve enclosing a comma-
separated list of values within square brackets:
const numbers = [1, 2, 3, 4, 5];
const fruits = ["Apple", "Banana", "Orange"];
const mixedData = [10, "Hello", true, { name: "John" }]; Accessing and
Modifying Elements:
Elements are accessed using their index within square brackets

const fruits = ["Apple", "Banana", "Orange"];


console.log(fruits[0]); // Output: "Apple"
fruits[1] = "Grape"; // Modifies the element at index 1
console.log(fruits); // Output: ["Apple", "Grape", "Orange"]
 push(): Adds one or more elements to the end of an array.
 pop(): Removes the last element from an array.
 shift(): Removes the first element from an array.
 unshift(): Adds one or more elements to the beginning of an array.
 forEach(): Executes a provided function once for each array element.
 map():
Creates a new array populated with the results of calling a provided function on every
element in the calling array.
 filter():
Creates a new array with all elements that pass the test implemented by the provided
function.
 sort(): Sorts the elements of an array in place.

Built-in Objects
JavaScript includes a variety of built-in objects, also known as global objects or
standard built-in objects, which are readily available for use without needing to be
explicitly created. These objects provide core functionalities and data structures
within the language.
Some prominent examples of JavaScript built-in objects include:
 Fundamental Objects:
 Object: The base object from which all other JavaScript objects inherit.
 Function: Represents a function.
 Boolean: A wrapper object for primitive boolean values.
 Symbol:Represents a unique identifier.
 Error Objects:
 Error: The base type for all error objects.
 Specific error types like TypeError, ReferenceError, SyntaxError, etc.
 Numbers and Dates:
 Number: A wrapper object for primitive number values.
 BigInt: Represents arbitrary-precision integers.
 Math: Provides mathematical constants and functions.
 Date:For working with dates and times.
 Text Processing:
 String: A wrapper object for primitive string values.
 RegExp:For working with regular expressions.
 Indexed Collections:
 Array: For creating and manipulating ordered lists of data.
 TypedArray:
For handling binary data.
 Keyed Collections:
 Map: A collection of key-value pairs where keys can be any data type.
 Set: A collection of unique values.
 WeakMap and WeakSet: Similar to Map and Set but with weak references.
 Structured Data:
 JSON: Provides methods for parsing and stringifying JSON data.
Beyond these core language objects, environments like web browsers or Node.js also
provide their own specific built-in objects, such as window, document, and console in web
browsers, or global and process in Node.jS

Regular Expression
In JavaScript, a Regular Expression (often shortened to RegEx or RegExp) is an
object used to define a search pattern for text. It provides a powerful and flexible way
to find, match, and manipulate strings based on specific character combinations.
Key aspects of JavaScript RegEx:
 Pattern Matching:
RegEx allows you to create patterns using a special syntax, including literal characters,
metacharacters (characters with special meaning like . for any character or \d for a digit), and
quantifiers (like + for one or more occurrences).
 Creation Methods:
 RegExp Literal: Defined using forward slashes: /pattern/flags.
 RegExp Constructor: Created using new RegExp("pattern", "flags") . This is useful when the
pattern or flags are dynamic.
 Applications:
RegEx is widely used for:
 Validation: Checking if an input (e.g., email, phone number) conforms to a specific format.
 Searching: Finding specific patterns within a string.
 Replacement: Replacing parts of a string that match a pattern.
 Extraction: Extracting specific data from a larger text.
 Associated Methods:
JavaScript's String and RegExp objects offer methods for working with regular expressions, such
as search(), match(), replace(), split(), and test().
In essence, RegEx in JavaScript provides a concise and efficient mechanism for
advanced text processing and pattern recognition within your applications.

Exceptions
Exceptions in JavaScript are events that disrupt the normal flow of a program's
execution due to an error or an unexpected situation. They are a mechanism for
handling errors gracefully, preventing a program from crashing and allowing for
recovery or informative error messages.
Core Concepts of Exception Handling:
 try...catch Statement:
This is the primary construct for handling exceptions.
 The try block contains code that might potentially throw an exception.
 The catch block executes if an exception is thrown within the try block. It receives the thrown
exception object as an argument, allowing you to inspect and handle the error.
 throw Statement:

This statement is used to explicitly create and throw an exception. You can throw any
JavaScript value (string, number, object), but it is common practice to throw Error objects or
their subclasses for better error information.
 Block:
finally
This optional block within a try...catch statement executes regardless of whether an exception
was thrown or caught. It is commonly used for cleanup operations, such as closing files or
releasing resources.
Common Types of Built-in Errors (and thus potential exceptions):
 Error: The base constructor for all error objects.
 TypeError:
Indicates that an operation could not be performed because the operand is of an
unexpected type.
 ReferenceError: Occurs when a non-existent variable is referenced.
 SyntaxError:
Indicates that the code has a grammatical error that prevents the JavaScript engine
from parsing it.
 RangeError: Occurs when a numeric variable or parameter is outside of its valid range.
 URIError: Occurs when a malformed URI is used in functions like decodeURI() or encodeURI().
Example:
function divideNumbers(a, b) {
try {
if (b === 0) {
throw new Error("Cannot divide by zero.");
}
return a / b;
} catch (error) {
console.error("An error occurred:", error.message);
return null; // Or handle the error appropriately
} finally {
console.log("Division attempt finished.");
}
}
console.log(divideNumbers(10, 2)); // Output: 5, then "Division attempt
finished."
console.log(divideNumbers(10, 0)); // Output: "An error occurred: Cannot
divide by zero.", then "Division attempt finished.", then null

Event handling.

Event handling in JavaScript refers to the process of responding to user interactions or


browser actions, known as events. These events can include clicks, key presses, form
submissions, page loads, and more. JavaScript provides mechanisms to detect these
events and execute specific code in response.
There are several ways to handle events in JavaScript: Inline Event Handlers (HTML
Event Attributes).
Event handlers can be directly embedded within HTML tags using attributes
like onclick, onmouseover, onsubmit, etc.
<button onclick="alert('Button clicked!')">Click Me</button> While simple
for basic interactions, this method mixes HTML and JavaScript, making code less
maintainable for complex applications. Traditional DOM Event Handlers.
Events can be assigned to DOM elements using properties like element.onclick = function()
{ ... };.
const button = document.getElementById('myButton');
button.onclick = function() {
console.log('Button clicked!');
};
This approach separates JavaScript from HTML but only allows one event handler per
event type on an element. addEventListener() Method.
This is the preferred and most flexible method for event handling. It allows multiple
event listeners of the same type to be attached to a single element and offers more
control over event propagation (bubbling and capturing).
const button = document.getElementById('myButton');
button.addEventListener('click', function() {
console.log('Button clicked!');
});

// You can add another listener for the same event


button.addEventListener('click', function() {
console.log('Another click action!');
});
The addEventListener() method takes three arguments: the event type (e.g., 'click',
'mouseover'), the function to execute (event handler), and an optional boolean
for useCapture (determining whether the event is handled during the capturing or
bubbling phase).
Key Concepts in Event Handling:
 Events:
Actions or occurrences that happen in the browser, such as user interactions (clicks, key
presses) or browser-generated events (page load, image load).
 Event Handlers:
Functions that are executed when a specific event occurs.
 Event Listeners:
Mechanisms (like addEventListener()) that "listen" for events on specific elements and trigger
their corresponding event handlers.
 Event Object:
An object automatically passed to event handler functions, containing information about the
event that occurred (e.g., target element, mouse coordinates, key pressed).
 Event Propagation (Bubbling and Capturing):
The order in which events are handled on nested elements within the DOM. Bubbling is the
default, where the event propagates from the target element upwards to its ancestors. Capturing
is the opposite, propagating downwards from the root to the target.
 Event Delegation:
A technique where a single event listener is attached to a parent element to handle events for
multiple child elements, improving performance and simplifying code, especially for
dynamically added elements.

You might also like