Web Essentials Unit 4
Web Essentials Unit 4
JavaScript Introduction
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
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);
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;
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.
if (number > 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) {
console.log(greet("Alisha"));
Some commonly used keywords are:
Keyword Description
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.
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
Object Literal
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.
Octal numeric literals include digits (0-7). A leading 0(zero) in a numeric literal indicates
octal format.
Floating-Point Literal in JS
It contains a decimal point, for example, the value 1.234
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 ("").
String literals can have some special characters too which are listed in the table below.
Character Description
\b It represents a backspace.
\t It represents a tab.
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.
Even when you assign an array to a variable, if you create the array directly using the square
brackets, it is an array literal.
In JavaScript, you can create an array using the Array object or using an array literal.
Here is an example,
var myregexp = /ab+c/; // Regular Expression literal
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.
Here is an example,
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
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.
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
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
^^^
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");
}
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
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.
Object initializers are also called object literals. "Object initializer" is consistent with the
terminology used by C++.
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.
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
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.