Table of Contents

JS Introduction

JS Output

JS Statements

JS Syntax

JS Comments

JS Variables

JS Let

JS Const

JS Operators

JS Arithmetic

JS Assignment

JS Data Types

JS Objects

JS Strings

JS String Methods

JS String Search

JS String Templates

JS Numbers

JS BigInt

JS Number Methods

JS Number Properties

JS Arrays

JS Array Methods

JS Array Sort

JS Array Iteration

JS Array Const

JS Dates

JS Date Formats

JS Date Get Methods

JS Date Set Methods

JS Math

JS Random

JS Booleans

JS Comparisons

JS If Else

JS Switch

JS Loop For

JS Loop For In

JS Loop For Of

JS Loop While

JS Break

JS Iterables

JS Sets

JS Maps

JS Typeof

JS Type Conversion

JS Bitwise

JS Introduction

JavaScript, often abbreviated as JS, is a versatile programming language primarily used for creating dynamic content on websites. It is an essential component of web development alongside HTML and CSS. JavaScript enables developers to add interactivity, manipulate the Document Object Model (DOM), and respond to user actions, making web pages more engaging and responsive.

Here are some key points about JavaScript:

1.                Client-Side Scripting: JavaScript is primarily a client-side scripting language, meaning it runs in the user's browser rather than on the server. This allows for real-time interaction without the need to reload the entire web page.

2.                Object-Oriented: JavaScript is an object-oriented language, which means it uses objects to represent and manipulate data. Objects in JavaScript can be predefined (like the built-in objects) or created by the programmer.

3.                Event-Driven Programming: One of JavaScript's strengths is its ability to respond to events such as user actions (clicks, mouse movements, keyboard inputs). Developers can define functions to be executed when certain events occur, providing a dynamic and interactive user experience.

1.Cross-Browser Compatibility: JavaScript is supported by all major web browsers, including Chrome, Firefox, Safari, and Edge. This cross-browser compatibility makes it a reliable choice for web development.

2.Asynchronous Programming: JavaScript supports asynchronous programming through mechanisms like callbacks, promises, and async/await. This allows developers to perform tasks without blocking the main execution thread, improving the responsiveness of web applications.

3.Libraries and Frameworks: JavaScript has a rich ecosystem of libraries and frameworks such as jQuery, React, Angular, and Vue.js. These tools simplify and streamline the development process, enabling developers to build complex applications more efficiently.

4.Server-Side Development: With the introduction of Node.js, JavaScript can also be used for server-side development. This extends the language beyond the browser and allows developers to use JavaScript for both client and server-side scripting.

In summary, JavaScript is a versatile and powerful programming language that plays a crucial role in web development, enhancing the interactivity and functionality of websites. Its widespread adoption and continuous development make it an essential skill for web developers.

JS Output

The term "JS Output To" isn't a standard phrase in the context of JavaScript. However, I'll provide an explanation of how JavaScript typically produces output.

In JavaScript, the primary way to generate output is through methods like console.log() and by manipulating the content of HTML elements. Let's break this down:

1.console.log(): This is a method used for debugging and logging information to the console. It's commonly used during development to display values, messages, or any other information. For example:

console.log("Hello, World!");

1.In this case, the text "Hello, World!" would be output to the browser's console.

2.Manipulating HTML Elements: JavaScript can also be used to dynamically update the content of HTML elements on a web page. This is often done using the DOM (Document Object Model). For example:

3.HTML:

<div id="output"></div>

JavaScript:

// Select the HTML element with the id "output"

var outputElement =

document.getElementById("output");

// Change the content of the selected element outputElement.innerHTML = "Hello, World!";

1.In this case, the text "Hello, World!" would be inserted into the HTML element with the id "output," dynamically changing the content of the web page.

These are two common ways JavaScript can produce output, either by logging information to the console or by dynamically updating the content of HTML elements in a web page. The specific method used depends on the context and purpose of the

JS Statements

JavaScript (JS) statements are individual instructions or commands that make up a JavaScript program. Each statement performs a specific action, and the browser or JavaScript engine executes them sequentially, one after another.

1.Building Blocks:

JavaScript programs are composed of statements, and each statement is a building block of the overall logic and functionality of the program. Statements can include variable declarations, control flow statements, function calls, and more.

2.Execution Order:

JavaScript statements are executed in the order in which they appear in the code, from top to bottom. This sequential execution is fundamental to the flow of the program, and it determines how tasks are carried out in a specific sequence.

3.Semicolons:

Statements in JavaScript are typically terminated by a semicolon (;). The semicolon acts as a statement terminator, signaling the end of one statement and the beginning of the next. While in many cases, JavaScript allows statements to be separated by line breaks without semicolons, it's a good practice to include them for clarity and consistency.

4.Statement Types:

JavaScript supports various types of statements, including but not limited to:

Variable Declarations: let x = 5;

Conditional Statements: if (condition) { /* code block */ } else { /* code block */ }

Looping Statements: for (let i = 0; i < 5; i++) { /* code block

*/ }

Function Calls: functionName();

Return Statements: return result;

Error Handling Statements: try { /* code block */ } catch (error) { /* handle error */ }

1.Control Flow:

Control flow in a JavaScript program is determined by conditional statements (e.g., if, else if, else) and looping statements (e.g., for, while, do-while). These statements allow developers to control the order in which statements are executed based on conditions or repeat statements multiple times.

2.Function Calls:

Functions in JavaScript are executed by calling them as statements. Function calls may have side effects, return values, or both, depending on the function's implementation.

3.Asynchronous Statements:

JavaScript also supports asynchronous statements, especially in environments like web browsers. Asynchronous statements, such as callbacks, promises, and async/await, allow developers to handle asynchronous tasks like fetching data or handling user input.

4.Error Handling:

JavaScript provides error-handling mechanisms, such as the try...catch statement, which allows developers to catch and handle errors gracefully, preventing the program from crashing in the event of unexpected issues. 5.Code Blocks:

Many statements in JavaScript are compound statements that consist of code blocks enclosed in curly braces ({}). Code blocks group multiple statements together and define the scope of variables.

JavaScript statements are the fundamental units of code that enable developers to express algorithms, logic, and functionality in a way that a computer can understand and execute. Understanding how statements work and their various types is crucial for writing effective and structured JavaScript programs.

// JavaScript Statements Example

// Declaration and Initialization

let x = 5; let y = 10;

// Addition Statement let sum = x + y;

// Conditional Statement if (sum > 15) {   console.log("Sum is greater than 15");

} else {

console.log("Sum is not greater than 15"); }

// Loop Statement

for (let i = 0; i < 5; i++) {   console.log("Iteration " + (i + 1)); }

// Function Statement function multiply(a, b) {   return a * b; }

// Function Call Statement let product = multiply(x, y);

// Display Results console.log("Sum: " + sum); console.log("Product: " + product);

In this example, various JavaScript statements are used:

1.Declaration and Initialization Statements:

let x = 5; and let y = 10;

2.Addition Statement: let sum = x + y;

3.Conditional Statement:

if (sum > 15) { ... } else { ... }

4.Loop Statement:

for (let i = 0; i < 5; i++) { ... }

5.Function Statement:

function multiply(a, b) { ... }

6.Function Call Statement: let product = multiply(x, y);

7.Display Results Statements:

console.log("Sum: " + sum); and console.log("Product: " + product);

These statements showcase common constructs in JavaScript, including variable declaration, arithmetic operations, conditional logic, loops, function declaration, and function invocation. Statements are the building blocks of JavaScript programs, and they perform specific actions or control the flow of the program.

JS Syntax

JavaScript (JS) syntax refers to the set of rules that dictate how JavaScript code should be structured and written. Following proper syntax is essential for writing functional and error-free JavaScript programs.

1.Case Sensitivity:

JavaScript is case-sensitive, meaning that variables, function names, and other identifiers must be written with consistent capitalization. For example, variableName and VariableName would be treated as two different entities.

2.Statements and Semicolons:

JavaScript programs consist of individual statements, and each statement is typically terminated by a semicolon (;). While JavaScript allows statements to be separated by line breaks in many cases, using semicolons is a recommended practice to avoid potential issues.

3.Whitespace:

Whitespace, including spaces and line breaks, is generally ignored by JavaScript. However, proper indentation and spacing are crucial for code readability. Developers often follow a consistent indentation style to enhance the visual structure of their code.

4.Comments:

JavaScript supports both single-line comments (prefixed with //) and multi-line comments (enclosed between /* and */). Comments are ignored during code execution and are used to provide explanations or disable code temporarily.

5.Variables:

Variables in JavaScript are declared using the var, let, or const keywords, followed by the variable name. Variable names must adhere to certain rules, such as starting with a letter, underscore (_), or dollar sign ($), and they cannot be reserved words.

6.Data Types:

JavaScript supports various data types, including numbers, strings, booleans, objects, arrays, and more. Understanding how to declare and use these data types is fundamental to writing effective JavaScript code.

1.Operators:

JavaScript uses operators for performing operations on variables and values. Common operators include arithmetic operators (+, -, *, /), assignment operators (=, +=, -=), comparison operators (==, ===, !=, !==), and logical operators (&&, ||, !).

2.Control Flow Statements:

Control flow statements, such as if, else, for, while, and switch, control the flow of execution in a JavaScript program. Proper usage of these statements ensures that the program behaves as intended.

3.Functions:

Functions in JavaScript are defined using the function keyword, followed by the function name and parameters. Understanding function syntax, including how to define, call, and return values from functions, is essential for creating modular and reusable code.

4.Objects and Arrays:

JavaScript uses objects and arrays to organize and store data. Understanding the syntax for creating and accessing object properties and array elements is crucial for working with complex data structures.

5.String Concatenation and Template Literals:

JavaScript allows developers to concatenate strings using the + operator or use template literals (enclosed in backticks) for more advanced string interpolation.

6.Error Handling:

Error handling in JavaScript involves using try...catch statements to catch and handle runtime errors. Proper syntax for error handling ensures that the program gracefully handles unexpected issues.

Understanding and adhering to JavaScript syntax is fundamental for writing clean, readable, and functional code. It allows developers to express their ideas and logic in a way that the JavaScript engine can interpret and execute correctly.

// JavaScript Syntax Example

let firstName = "John"; let lastName = "Doe";

function greet(name) {   console.log("Hello, " + name + "!");

}

let fullName = firstName + " " + lastName; greet(fullName);

for (let i = 0; i < 5; i++) {   console.log("Iteration " + (i + 1));

}

if (fullName.length > 10) {   console.log("Long name!");

} else {   console.log("Short name!");

}

In this example, the JavaScript syntax is demonstrated through various elements:

1.Variable Declaration and Initialization: ​let firstName = "John"; and let lastName = "Doe";

2.Function Declaration and Invocation:

​              function greet(name) { ... } and greet(fullName);

3.String Concatenation:

​              let fullName = firstName + " " + lastName;

4.For Loop:

​              for (let i = 0; i < 5; i++) { ... }

5.Conditional Statement:

​              if (fullName.length > 10) { ... } else { ... }

This example uses common JavaScript syntax constructs such as variables, functions, string concatenation, loops, and conditional statements. The syntax defines the structure and rules of the JavaScript programming language

JS Comments

JavaScript comments are annotations within the code that are ignored by the JavaScript interpreter. They are used to add explanatory notes or disable specific code temporarily.

1.Single-Line Comments:

Single-line comments in JavaScript are denoted by the double forward slash //. Anything following // on the same line is treated as a comment and is ignored by the JavaScript interpreter. Single-line comments are often used for brief explanations or notes on a single line of code.

2.Multi-Line Comments:

Multi-line comments in JavaScript are enclosed between /* and */. Everything between these delimiters is treated as a comment and is ignored by the interpreter. Multi-line comments are useful for adding longer explanations, comments that span multiple lines, or temporarily excluding a block of code.

3.Purpose of Comments:

Comments serve several purposes in JavaScript code: Documentation: Comments provide information about the purpose and functionality of code, making it easier for developers (including the code's author or collaborators) to understand the codebase.

Debugging: Comments can be used to temporarily disable code during debugging without removing it. This allows developers to isolate and test specific sections of code.

TODOs and FIXMEs: Developers often use comments to indicate areas of code that need attention, such as implementing a feature (// TODO: implement feature) or fixing a bug (// FIXME: fix this issue).

1.Commenting Best Practices:

While comments are valuable for code documentation, it's important to follow best practices:

Clarity: Write clear and concise comments that explain the purpose or logic behind the code. Avoid unnecessary or redundant comments.

Consistency: Maintain a consistent commenting style throughout the codebase. If there are conventions in place, follow them.

Up-to-Date Comments: Keep comments up-to-date with changes to the code. Outdated comments can mislead developers.

Avoid Overcommenting: Code should be selfexplanatory to the extent possible. Avoid overcommenting by focusing on essential information.

2.Conditional Comments:

Comments can also be used conditionally. For example, developers might use a comment to disable or enable a specific block of code based on certain conditions or development stages.

3.HTML and CSS Comments:

In addition to JavaScript, HTML and CSS also support comments. HTML comments are denoted by <!-- and ->, while CSS comments use /* and */.

Comments play a crucial role in maintaining code quality and facilitating collaboration among developers. They serve as a form of communication within the codebase, helping developers understand, collaborate on, and maintain the software more effectively.

// JavaScript Comments Example

// Variable Declaration and Initialization let x = 5; let y = 10;

// Addition Operation let sum = x + y;

/*

Multi-line Comment:

This section displays the results.

*/ console.log("Sum: " + sum);

// Function Declaration function multiply(a, b) {   return a * b; }

// Function Call let product = multiply(x, y);

// Display Product console.log("Product: " + product);

// End of JavaScript Comments Example

In this example, JavaScript comments are demonstrated through various types:

1.Single-line Comments:

// Variable Declaration and Initialization

// Addition Operation

2.Multi-line Comment:

/* Multi-line Comment: This section displays the results. */

3.Comments for Function Declaration and Function Call:

// Function Declaration

// Function Call

4.End of JavaScript Comments Example:

​​// End of JavaScript Comments Example

Comments in JavaScript provide a way to add explanatory notes to the code, making it more readable and understandable. Single-line comments start with //, and multi-line comments are enclosed within /* ... */. They are ignored by the JavaScript interpreter and serve for documentation purposes.

JS Variables

JavaScript variables are containers for storing and managing data in a program. They play a fundamental role in programming by allowing developers to store and manipulate values.

1.Variable Declaration:

In JavaScript, a variable is declared using the var, let, or const keyword, followed by the variable name. For example, var x; declares a variable named x. The choice between var, let, or const depends on the desired scope and mutability of the variable.

2.Variable Naming:

​Variable names in JavaScript must adhere to certain rules:

They can include letters, digits, underscores (_), or dollar signs ($).

They must begin with a letter, underscore, or dollar sign.

They are case-sensitive, so variableName and VariableName are considered different.

3.Assignment:

After declaring a variable, a value can be assigned to it using the assignment operator (=). For example, x = 10; assigns the value 10 to the variable x. The assigned value can be of any data type, such as a number, string, boolean, or object.

4.Data Types:

​JavaScript ​variables ​can ​hold ​various ​data ​types, including:

Numbers: Representing numeric values.

Strings: Representing sequences of characters.

Booleans: Representing true or false values.

Objects: Representing complex data structures.

Arrays: Representing ordered collections of values.

Undefined: Representing the absence of a value.

1.Scope:

The scope of a variable in JavaScript determines where the variable can be accessed. Variables declared with var have function scope, while those declared with let or const have block scope. Global scope refers to variables accessible throughout the entire program.

2.Hoisting:

JavaScript has a behavior called hoisting, where variable declarations are moved to the top of their containing scope during the compilation phase. This means that variables declared with var are hoisted and can be used before their actual declaration in the code.

3.Mutability:

Variables declared with var and let can be reassigned to new values, making them mutable. On the other hand, variables declared with const are constants and cannot be reassigned after initialization.

4.Dynamic Typing:

JavaScript is a dynamically typed language, which means that variable types are determined at runtime. This allows for flexibility in assigning different types of values to a variable during the execution of the program.

5.Null and Undefined:

A variable can be explicitly set to null or be uninitialized, resulting in the value undefined. null is a deliberate absence of a value, while undefined typically indicates that a variable has been declared but not yet assigned a value.

JavaScript variables are essential for storing and managing data in a program. They provide flexibility and dynamic typing, allowing developers to work with a wide range of data types and values. Understanding how to declare, assign, and use variables is fundamental to writing JavaScript code.

// JavaScript Variables Example

let firstName = "John"; let lastName = "Doe"; let age = 30; let fullName = firstName + " " + lastName; let isStudent = false; let skills = ["JavaScript", "HTML", "CSS"];

let address = {   street: "123 Main St",   city: "Anytown",   zipCode: "12345"

};

let temperature; // Declaration without initialization

// Displaying Variables console.log("Full Name: " + fullName); console.log("Age: " + age); console.log("Is Student? " + isStudent); console.log("Skills: " + skills.join(", ")); console.log("Address: " + address.street + ", " + address.city + " "

+ address.zipCode); console.log("Temperature: " + temperature); // Displays 'undefined'

// End of JavaScript Variables Example

In this example, JavaScript variables are demonstrated with various data types:

1.String Variables: let firstName = "John"; and let lastName = "Doe";

2.Numeric Variable: let age = 30;

3.String Concatenation: let fullName = firstName + " " + lastName;

4.Boolean Variable: let isStudent = false;

5.Array Variable: let skills = ["JavaScript", "HTML", "CSS"];

6.Object Variable:

let address = { ... };

7.Undefined Variable: let temperature; // Declaration without initialization

8.Displaying Variables:

console.log("Full Name: " + fullName); console.log("Age: " + age); console.log("Is Student? " + isStudent); console.log("Skills: " + skills.join(", ")); console.log("Address: " + address.street + ", " + address.city + " " + address.zipCode);

console.log("Temperature: " + temperature); // Displays 'undefined'

Variables in JavaScript are used to store and manipulate data. They can hold different types of data, including strings, numbers, booleans, arrays, objects, and more. The example demonstrates variable declaration, initialization, and usage.

JS Let

In JavaScript, the let keyword is used to declare variables. It was introduced in ECMAScript 6 (ES6) to provide a more flexible alternative to the older var keyword.

1.Variable Declaration:

The let keyword is used to declare variables in JavaScript. When a variable is declared with let, it can be reassigned to a new value.

2.Block Scope:

Variables declared with let have block scope. This means that the variable is only accessible within the block of code where it is defined. A block is typically defined by a pair of curly braces {}.

3.Redeclaration:

Unlike variables declared with var, a variable declared with let cannot be redeclared within the same block. Attempting to redeclare a variable using let in the same block would result in an error.

4.Hoisting:

Variables declared with let are hoisted to the top of their block, but they are not initialized until the declaration statement is encountered. This means that, unlike var, a variable declared with let is not accessible before its declaration in the code.

1.Temporal Dead Zone (TDZ):

The concept of the Temporal Dead Zone (TDZ) is related to hoisting with let. During the TDZ, trying to access a let variable before its declaration results in a runtime error. This enforces a cleaner scoping behavior compared to var.

2.Global Object Property:

Unlike variables declared with var, variables declared with let do not become properties of the global object (window in browsers). This avoids potential conflicts and unintended global variable declarations.

3.For Loops and Closure:

let is commonly used in for loops to create a new variable for each iteration, preventing unintended closure-related issues that might occur when using var. This behavior is often referred to as "block-scoped loop variables."

4.Conditional Statements:

Variables declared with let in an if statement or any other block-scoped structure are confined to that specific block. This ensures that the variable is isolated and does not leak into the outer scope.

5.Function Scope:

Unlike var, which has function scope, variables declared with let have block scope even within functions. This allows for more fine-grained control over variable visibility and reduces the likelihood of unintended variable leaks.

6.TDZ and Closures:

The Temporal Dead Zone behavior in combination with closures can be used to create more predictable and intentional scoping in certain scenarios.

The use of let in JavaScript is preferred over var in many modern coding practices due to its block-scoping behavior and improved handling of variable declarations. It provides more predictable scoping and helps prevent common issues associated with the hoisting behavior of var.

// JavaScript 'let' Example

// Variable Declaration and Initialization with 'let' let x = 5; let y = 10;

// Addition Operation let sum = x + y;

// Display Result console.log("Sum: " + sum);

// Reassignment with 'let' let message = "Hello"; console.log("Message: " + message);

message = "Hi";

console.log("Updated Message: " + message);

// Block Scope with 'let' if (sum > 15) {

let result = "Sum is greater than 15";   console.log(result);

} else {

let result = "Sum is not greater than 15";   console.log(result); }

// 'let' in a Loop for (let i = 0; i < 3; i++) {   console.log("Iteration " + (i + 1)); }

// End of 'let' Example

In this example, the JavaScript let keyword is used for variable declaration and reassignment:

1.Variable Declaration and Initialization with 'let':

let x = 5; and let y = 10;

2.Addition Operation: let sum = x + y;

3.Reassignment with 'let':

let message = "Hello"; message = "Hi";

4.Block Scope with 'let':

Variables declared with let have block scope. In the if block, result is scoped to that block.

5.'let' in a Loop:

for (let i = 0; i < 3; i++) { ... } demonstrates using let in a loop, creating a new variable i for each iteration.

The let keyword is used for variable declaration in modern JavaScript. It allows block-scoping, preventing variable hoisting issues associated with var.

JS Const

In JavaScript, the const keyword is used to declare constants. Constants are variables whose values cannot be reassigned after their initial assignment.

1.Constant Declaration:

The const keyword is used to declare constants in JavaScript. When a variable is declared with const, its value must be assigned at the time of declaration, and once assigned, the value cannot be changed.

2.Immutable Values:

Constants are designed to represent values that should not be modified during the execution of a program. Once a value is assigned to a const variable, any attempt to reassign a new value to that variable results in an error.

3.Block Scope:

Similar to variables declared with let, variables declared with const have block scope. This means that the constant is only accessible within the block of code where it is defined.

4.Hoisting:

Like variables declared with let, variables declared with const are hoisted to the top of their block. However, unlike var, they are not initialized until the declaration statement is encountered. Attempting to access a const variable before its declaration results in a runtime error.

5.Redeclaration:

Unlike variables declared with var, which can be redeclared within the same scope, attempting to redeclare a variable using const in the same block results in an error. Each constant must have a unique name within its scope.

1.Global Object Property:

Similar to variables declared with let, variables declared with const do not become properties of the global object (window in browsers). This avoids potential conflicts and unintended global variable declarations.

2.Initializing Values:

When declaring a constant with const, it is mandatory to initialize it with a value. This is in contrast to variables declared with var or let, which can be declared without an initial value.

3.Immutable References:

When a constant holds a reference to an object (such as an array or an object), the reference itself is immutable. This means that the constant cannot be reassigned to a new object, but the properties or elements of the referenced object can still be modified.

4.Use Cases:

Constants are often used for values that should remain fixed throughout the execution of a program, such as mathematical constants, configuration values, or other constants that should not be accidentally changed.

5.Choosing Between const and let:

When declaring a variable, it's advisable to use const by default. If the value needs to be reassigned later in the program, then let can be used. This helps prevent unintentional reassignments and promotes code that is easier to reason about.

Using const to declare constants helps improve code quality by making the intent of immutability clear and preventing accidental modifications to important values throughout the program.

// JavaScript 'const' Example

// Constant Declaration and Initialization with 'const' const PI = 3.14159;

// Display Constant console.log("Value of PI: " + PI);

// Attempted Reassignment (Results in Error)

// PI = 3.14; // Uncommenting this line would result in a

TypeError

// Constant Object const person = {   firstName: "John",   lastName: "Doe",   age: 30

};

// Display Constant Object console.log("Person: " + person.firstName + " " + person.lastName + ", Age: " + person.age);

// Attempted Reassignment of Property (Allowed) person.age = 31;

// Display Updated Constant Object console.log("Updated Person: " + person.firstName + " " + person.lastName + ", Age: " + person.age);

// End of 'const' Example

In this example, the JavaScript const keyword is used for constant declaration:

1.Constant Declaration and Initialization with 'const':

const PI = 3.14159;

2.Display Constant:

console.log("Value of PI: " + PI);

3.Attempted Reassignment (Results in Error):

Uncommenting the line PI = 3.14; would result in a TypeError because constants cannot be reassigned.

4.Constant Object:

const person = { ... }; declares a constant object.

5.Display Constant Object: console.log("Person: " + person.firstName + " " + person.lastName + ", Age: " + person.age);

6.Attempted Reassignment of Property (Allowed):

Modifying the properties of a constant object is allowed, so person.age = 31; is valid.

7.Display Updated Constant Object:

​console.log("Updated Person: " + person.firstName + " " + person.lastName + ", Age: " + person.age);

The const keyword is used for declaring constants in JavaScript. Once a value is assigned to a constant, it cannot be reassigned. However, for objects declared with const, their properties can still be modified.

JS Operators

JavaScript operators are symbols that perform operations on variables and values. They allow you to manipulate data, perform calculations, compare values, and more.

1.Arithmetic Operators:

​Arithmetic ​operators ​perform ​basic ​mathematical operations.

Addition (+): Adds two values.

Subtraction (-): Subtracts the right operand from the left operand.

Multiplication (*): Multiplies two values.

Division (/): Divides the left operand by the right operand. Modulus (%): Returns the remainder of the division of the left operand by the right operand.

2.Assignment Operators:

Assignment operators assign values to variables.

Assignment (=): Assigns the value on the right to the variable on the left.

Addition Assignment (+=): Adds the right operand to the variable and assigns the result.

Subtraction Assignment (-=): Subtracts the right operand from the variable and assigns the result.

Multiplication Assignment (*=): Multiplies the variable by the right operand and assigns the result.

Division Assignment (/=): Divides the variable by the right operand and assigns the result.

Logical Operators:

Logical operators perform logical operations and return a Boolean result.

AND (&&): Returns true if both operands are true.

OR (||): Returns true if at least one operand is true.

NOT (!): Returns the opposite Boolean value of the operand.

1.Comparison Operators:

​Comparison operators compare values and return a Boolean result.

Equal (== or ===): Checks if two values are equal. === also checks for the same data type.

Not Equal (!= or !==): Checks if two values are not equal. !== also checks for different data types.

Greater Than (>): Checks if the left operand is greater than the right operand.

Less Than (<): Checks if the left operand is less than the right operand.

Greater Than or Equal To (>=): Checks if the left operand is greater than or equal to the right operand.

Less Than or Equal To (<=): Checks if the left operand is less than or equal to the right operand.

2.Unary Operators:

Unary operators operate on a single operand.

Unary Plus (+): Converts its operand to a number.

Unary Negation (-): Negates its operand.

Increment (++): Increases the value of its operand by 1.

Decrement (--): Decreases the value of its operand by 1. Logical NOT (!): Converts the operand to a Boolean value and negates it.

3.Conditional (Ternary) Operator:

The conditional operator (? :) is a shorthand way to write an if...else statement. It evaluates a condition and returns one of two values based on whether the condition is true or false.

4.Bitwise Operators:

Bitwise operators perform operations on the binary representation of integers.

AND (&): Performs a bitwise AND operation.

OR (|): Performs a bitwise OR operation.

XOR (^): Performs a bitwise XOR (exclusive OR) operation.

NOT (~): Inverts the bits of its operand.

Left Shift (<<): Shifts the bits of the operand to the left.

Right Shift (>>): Shifts the bits of the operand to the right. JavaScript operators are essential for manipulating data and making decisions within your programs. Understanding how to use operators effectively is crucial for writing expressive and functional JavaScript code.

// JavaScript Operators Example

// Arithmetic Operators let x = 5; let y = 10;

let addition = x + y; let subtraction = x - y; let multiplication = x * y; let division = x / y; let remainder = x % y;

// Display Results of Arithmetic Operations console.log("Addition: " + addition); console.log("Subtraction: " + subtraction); console.log("Multiplication: " + multiplication); console.log("Division: " + division); console.log("Remainder: " + remainder);

// String Concatenation Operator let firstName = "John"; let lastName = "Doe"; let fullName = firstName + " " + lastName;

// Display Concatenated String console.log("Full Name: " + fullName);

// Assignment Operator let z = 15;

// Comparison Operators let isEqual = x === y; let isNotEqual = x !== y; let isGreater = x > y; let isLess = x < y; let isGreaterOrEqual = x >= y; let isLessOrEqual = x <= y;

// Display Results of Comparison Operations console.log("Is Equal: " + isEqual); console.log("Is Not Equal: " + isNotEqual); console.log("Is Greater: " + isGreater); console.log("Is Less: " + isLess);

console.log("Is Greater or Equal: " + isGreaterOrEqual); console.log("Is Less or Equal: " + isLessOrEqual);

// Logical Operators let isTrue = true; let isFalse = false;

let andResult = isTrue && isFalse; let orResult = isTrue || isFalse; let notResult = !isTrue;

// Display Results of Logical Operations console.log("AND Result: " + andResult); console.log("OR Result: " + orResult); console.log("NOT Result: " + notResult);

// Increment and Decrement Operators

let count = 5; count++;

let incrementedCount = count; count--;

let decrementedCount = count;

// Display Incremented and Decremented Values console.log("Incremented Count: " + incrementedCount); console.log("Decremented Count: " + decrementedCount);

// Conditional (Ternary) Operator let isEven = x % 2 === 0;

let parityMessage = isEven ? "Even" : "Odd";

// Display Parity Message console.log("Parity: " + parityMessage);

// Typeof Operator let variableType = typeof x;

// Display Type of Variable console.log("Type of x: " + variableType);

// End of JavaScript Operators Example

In this example, various JavaScript operators are demonstrated:

1.Arithmetic Operators:

+ (Addition)

- (Subtraction)

* (Multiplication)

/ (Division)

% (Remainder)

2.String Concatenation Operator:

+ (String Concatenation)

3.Assignment Operator:

= (Assignment)

4.Comparison Operators:

=== (Equal)

!== (Not Equal)

> (Greater Than)

< (Less Than)

>= (Greater Than or Equal)

<= (Less Than or Equal)

5.Logical Operators:

&& (Logical AND)

|| (Logical OR)

! (Logical NOT)

6.Increment and Decrement Operators:

++ (Increment)

-- (Decrement)

7.Conditional (Ternary) Operator:

? : (Conditional)

8.Typeof Operator:

typeof (Type Check)

These operators are fundamental for performing operations, comparisons, and logical evaluations in JavaScript.

JS Arithmetic

Arithmetic in JavaScript involves performing mathematical operations on numeric values using arithmetic operators. These operators allow you to add, subtract, multiply, divide, and perform other basic mathematical calculations.

1.Addition (+):

The addition operator (+) adds two numeric values together. For example, 3 + 5 would result in 8.

2.Subtraction (-):

The subtraction operator (-) subtracts the right operand from the left operand. For example, 7 - 4 would result in

3.

3.Multiplication (*):

The multiplication operator (*) multiplies two numeric values. For example, 2 * 6 would result in 12.

4.Division (/):

The division operator (/) divides the left operand by the right operand. For example, 10 / 2 would result in 5.

5.Modulus (%):

The modulus operator (%) returns the remainder of the division of the left operand by the right operand. For example, 10 % 3 would result in 1 because 10 divided by 3 leaves a remainder of 1.

1.Exponentiation (**):

The exponentiation operator (**) raises the left operand to the power of the right operand. For example, 2 ** 3 would result in 8 because 2 raised to the power of 3 is 8.

2.Increment (++):

The increment operator (++) increases the value of a variable by 1. For example, if x is initially 5, then x++ would result in 6.

3.Decrement (--):

The decrement operator (--) decreases the value of a variable by 1. For example, if y is initially 8, then y-would result in 7.

4.Unary Plus (+):

The unary plus operator (+) converts its operand to a number. If the operand is not already a number, JavaScript attempts to convert it. For example, +"42" would result in the numeric value 42.

5.Unary Negation (-):

The unary negation operator (-) negates its operand. If the operand is not a number, JavaScript attempts to convert it to a number and then negates it. For example, -3 would result in -3.

JavaScript arithmetic operators follow the standard rules of arithmetic. They can be used in combination to create complex expressions, and the order of operations (parentheses, exponentiation, multiplication and division from left to right, and addition and subtraction from left to right) is observed. Understanding these operators is fundamental to performing mathematical calculations in JavaScript.

// JavaScript Arithmetic Example

// Addition let sum = 5 + 10;

// Subtraction let difference = 20 - 8;

// Multiplication let product = 4 * 6;

// Division let quotient = 36 / 9;

// Remainder (Modulus) let remainder = 15 % 4;

// Display Results console.log("Sum: " + sum); console.log("Difference: " + difference); console.log("Product: " + product); console.log("Quotient: " + quotient); console.log("Remainder: " + remainder);

// Combined Operations

let result = (sum * product) - difference / (remainder + 1);

// Display Combined Result console.log("Combined Result: " + result);

// Increment and Decrement

let counter = 5; counter++; // Increment by 1 let incrementedCounter = counter;

counter--; // Decrement by 1 let decrementedCounter = counter;

// Display Incremented and Decremented Values console.log("Incremented Counter: " + incrementedCounter); console.log("Decremented Counter: " + decrementedCounter);

// End of JavaScript Arithmetic Example

In this example, various arithmetic operations are demonstrated using JavaScript:

1.Addition: let sum = 5 + 10;

2.Subtraction: let difference = 20 - 8;

3.Multiplication:

let product = 4 * 6;

4.Division:

let quotient = 36 / 9;

5.Remainder (Modulus): let remainder = 15 % 4;

6.Combined Operations:

A combination of addition, subtraction, multiplication, and division.

7.Increment and Decrement:

Increment (counter++) and decrement (counter--) operations.

8.Displaying Results:

console.log("Sum: " + sum); console.log("Difference: " + difference); console.log("Product: " + product); console.log("Quotient: " + quotient); console.log("Remainder: " + remainder); console.log("Combined Result: " + result); console.log("Incremented Counter: " + incrementedCounter); console.log("Decremented Counter: " + decrementedCounter);

These ​arithmetic ​operations ​are ​fundamental ​for ​performing ​mathematical calculations in JavaScript.

JS Assignment

In JavaScript, assignment involves storing a value in a variable or modifying the value of an existing variable. The assignment operator (=) is used for this purpose:

1.Assignment Operator (=):

The assignment operator (=) is used to assign a value to a variable. For example, x = 5; assigns the value 5 to the variable x.

2.Variable Declaration and Assignment:

Variables are typically declared using the var, let, or const keyword, followed by the variable name. The assignment operator is then used to assign an initial value to the variable.

3.Reassignment:

Once a variable has been declared and assigned a value, its value can be changed or reassigned using the assignment operator. For example, if y is initially 10, the statement y = y + 5; would change the value of y to 15.

4.Updating Variables:

The assignment operator is often used in combination with arithmetic operators to update the value of a variable based on its current value. For example, count = count + 1; increments the value of the variable count by 1.

1.Chaining Assignment:

JavaScript allows for chaining assignment statements. For example, a = b = c = 10; assigns the value 10 to variables a, b, and c in a single line.

2.Shorthand Assignment:

Shorthand assignment operators, such as +=, -=, *=, and /=, combine the assignment operator with arithmetic operators. They provide a concise way to update variables based on their current values. For example, x += 3; is equivalent to x = x + 3;.

3.Assigning Values to Constants (const):

Variables declared with the const keyword are constants, meaning their values cannot be reassigned after the initial assignment. Attempting to reassign a value to a constant variable results in an error.

4.Assigning Values to Undefined Variables:

If you attempt to assign a value to a variable that has not been declared or initialized, JavaScript will create a global variable (in non-strict mode) or throw a reference error (in strict mode).

5.Assignment by Reference:

When dealing with objects or arrays, assignment works by reference. If one variable is assigned the value of another object or array, changes to one variable will affect the other.

Understanding how to use the assignment operator is fundamental to working with variables in JavaScript. It allows developers to store and manipulate data within their programs, making it a core concept in programming.

// JavaScript Assignment Example

// Basic Assignment

let x = 5;

// Display Assigned Value console.log("Initial Value of x: " + x);

// Reassignment

x  = 10;

// Display Updated Value console.log("Updated Value of x: " + x);

// Combined Assignment (Addition)

let y = 3;

y  += 7; // Equivalent to: y = y + 7;

// Display Combined Assignment Result

console.log("Combined Assignment Result (Addition): " + y);

// Combined Assignment (String Concatenation)

let greeting = "Hello"; let name = "John";

greeting += " " + name; // Equivalent to: greeting = greeting + " " + name;

// Display Combined Assignment Result (String Concatenation) console.log("Combined Assignment Result (String Concatenation): " + greeting);

// Combined Assignment (Multiplication) let z = 4;

z *= 2; // Equivalent to: z = z * 2;

// Display Combined Assignment Result (Multiplication) console.log("Combined Assignment Result (Multiplication): " + z);

// End of JavaScript Assignment Example

In this example, JavaScript assignment operations are demonstrated:

1.Basic Assignment:

let x = 5; 2.Reassignment:

x  = 10;

3.Combined Assignment (Addition):

y  += 7; (Equivalent to y = y + 7;)

4.Combined Assignment (String Concatenation):

greeting += " " + name; (Equivalent to greeting = greeting + " " + name;)

5.Combined Assignment (Multiplication):

z  *= 2; (Equivalent to z = z * 2;)

6.Displaying Results:

console.log("Initial Value of x: " + x); console.log("Updated Value of x: " + x);

console.log("Combined Assignment Result (Addition): " + y);

​console.log("Combined ​Assignment ​Result ​(String

Concatenation): " + greeting);

console.log("Combined Assignment Result (Multiplication): " + z); These assignment operations allow variables to be assigned values and updated based on calculations or concatenation.

JS Data Types

In JavaScript, data types define the nature of the values that variables can hold. JavaScript is a dynamically typed language, meaning that variable types are determined at runtime.

1.Primitive Data Types:

Number: Represents numeric values. It includes integers and floating-point numbers.

​String: Represents sequences of characters, such as text.

Boolean: Represents true or false values.

Undefined: Represents a variable that has been declared but not assigned a value.

Null: Represents the absence of a value or a reference to no object.

Symbol: Introduced in ECMAScript 6 (ES6), symbols are unique and immutable data types often used as identifiers for object properties.

2.Object Data Type:

The Object data type is a complex data type that allows you to group related data and functions together. Objects are instances of user-defined or built-in classes and consist of key-value pairs.

3.Function Data Type:

In JavaScript, functions are considered a distinct data type. Functions can be assigned to variables, passed as arguments to other functions, and returned from functions.

4.Array Data Type:

Arrays are a type of object used to store ordered collections of values. Each value in an array is identified by an index.

1.Special Values:

Infinity: Represents positive infinity.

-Infinity: Represents negative infinity.

NaN (Not a Number): Represents a value that is not a valid number.

BigInt: Introduced in ECMAScript 2020 (ES11), BigInt is a primitive data type that represents arbitrary-precision integers.

2.Primitive Wrapper Objects:

JavaScript provides object wrappers for primitive data types, such as Number, String, and Boolean. These objects allow you to access additional methods and properties associated with each data type.

3.Typeof Operator:

The typeof operator is used to determine the data type of a variable or an expression. It returns a string indicating the type of the operand.

4.Dynamic Typing:

JavaScript is dynamically typed, meaning that variables can change types during runtime. The same variable can hold different types of values at different points in the program.

5.Type Coercion:

JavaScript performs type coercion, which is the automatic conversion of values from one data type to another. This can happen implicitly or explicitly.

6.Understanding Data Types:

Knowing the data types in JavaScript is important for writing robust and error-free code. It helps in understanding how values behave, what operations can be performed on them, and how they interact with each other.

Understanding JavaScript data types is fundamental to writing effective code. It allows developers to work with different kinds of values, perform appropriate operations, and ensure that programs handle data in a predictable manner.

// JavaScript Data Types Example

// Primitive Data Types let number = 5; // Number let text = "Hello, World!"; // String let isTrue = true; // Boolean let isNull = null; // Null let undefinedVar; // Undefined

// Display Primitive Data Types console.log("Number: " + number); console.log("Text: " + text); console.log("Boolean: " + isTrue); console.log("Null: " + isNull);

console.log("Undefined: " + undefinedVar);

// Object Data Type let person = {   firstName: "John",   lastName: "Doe",

age: 30

}; // Object

// Display Object Data Type

console.log("Person: " + person.firstName + " " + person.lastName + ", Age: " + person.age);

// Array Data Type

let colors = ["Red", "Green", "Blue"]; // Array

// Display Array Data Type

console.log("Colors: " + colors.join(", "));

// Function Data Type function greet(name) {

console.log("Hello, " + name + "!"); } // Function

// Display Function Data Type greet("Alice");

// typeof Operator let typeOfText = typeof text;

// Display Type of Variable

console.log("Type of Text: " + typeOfText); // End of JavaScript Data Types Example

In this example, various JavaScript data types are demonstrated:

1.Primitive Data Types: number (Number)

text (String) isTrue (Boolean)

isNull (Null) undefinedVar (Undefined)

2.Object Data Type: person (Object)

3.Array Data Type: colors (Array)

4.Function Data Type: greet (Function)

5.typeof Operator: typeof text is used to determine the type of a variable.

6.Displaying Data Types:

console.log("Number: " + number); console.log("Text: " + text); console.log("Boolean: " + isTrue); console.log("Null: " + isNull);

console.log("Undefined: " + undefinedVar);

console.log("Person: " + person.firstName + " " + person.lastName + ", Age: " + person.age);

console.log("Colors: " + colors.join(", ")); console.log("Type of Text: " + typeOfText);

These examples showcase the basic data types in JavaScript, including primitive types (number, string, boolean, null, and undefined), as well as object, array, and function types.

JS Functions

1.Abstraction:

Functions allow for abstraction, enabling developers to encapsulate a set of instructions into a single named entity. This promotes code organization and modularity.

2.Reusability:

Once a function is defined, it can be reused throughout the code. This reduces redundancy and promotes a more efficient and maintainable codebase.

3.Parameterization:

Functions can accept parameters, which are variables that act as placeholders for values. These parameters make functions flexible, allowing them to work with different inputs.

4.Return Values:

Functions can produce a result using the return statement. The return value can be utilized by the calling code, allowing functions to generate outputs and contribute to the overall program logic.

5.Function Invocation:

Functions are executed by invoking or calling them. This can be done by using the function's name followed by parentheses. The invocation triggers the execution of the function's code.

6.Function Scope:

Variables declared inside a function are typically scoped to that function and are not accessible outside of it. This helps in preventing naming conflicts and encapsulating variables.

7.Anonymous Functions:

JavaScript supports the creation of functions without assigning them a name. These anonymous functions are often used in scenarios where a function is used once and doesn't need a dedicated name.

1.Arrow Functions:

Introduced in ECMAScript 6 (ES6), arrow functions provide a more concise syntax for writing functions, especially for short, one-line expressions. They also handle the scoping of the this keyword differently.

2.First-Class Citizens:

In JavaScript, functions are first-class citizens, meaning they can be assigned to variables, passed as arguments to other functions, and returned as values from other functions. This allows for functional programming paradigms.

3.Closures:

Functions in JavaScript form closures, which means they retain access to variables from their containing scope even after the scope has finished executing. This enables powerful patterns in JavaScript programming.

4.Recursion:

Functions in JavaScript can call themselves, a concept known as recursion. This technique is useful for solving problems that can be broken down into smaller, similar sub-problems.

5.Callback Functions:

Callback functions are functions passed as arguments to other functions. They are commonly used in asynchronous programming, event handling, and situations where the order of execution is important.

6.Function Declarations vs. Expressions:

Function declarations are hoisted to the top of their containing scope, allowing them to be called before their declaration. Function expressions, on the other hand, are not hoisted in the same way.

7.Function Overloading:

JavaScript does not have native support for function overloading (having multiple functions with the same name but different parameter lists). However, developers can achieve similar effects by using default parameter values and checking the number or types of arguments within the function.

Understanding these aspects of JavaScript functions is crucial for becoming proficient in writing clean, efficient, and maintainable code. Functions play a central role in structuring logic and promoting code reusability in JavaScript applications.

// JavaScript Functions Example

// Function Declaration function add(x, y) {   return x + y; }

// Function Invocation let sum = add(5, 10);

// Display Result console.log("Sum: " + sum);

// Function Expression let multiply = function(a, b) {

return a * b;

};

// Function Invocation let product = multiply(4, 6);

// Display Result console.log("Product: " + product);

// Arrow Function

let subtract = (a, b) => a - b;

// Function Invocation let difference = subtract(20, 8);

// Display Result console.log("Difference: " + difference);

// Function with Default Parameter function greet(name = "Guest") {   console.log("Hello, " + name + "!"); }

// Function Invocation greet(); // Uses default parameter greet("Alice"); // Overrides default parameter // End of JavaScript Functions Example

In this example, various ways of defining functions in JavaScript are demonstrated:

1.Function Declaration: function add(x, y) { return x + y; }

2.Function Invocation: let sum = add(5, 10);

3.Function Expression: let multiply = function(a, b) { return a * b; };

4.Arrow Function:

let subtract = (a, b) => a - b;

5.Function Invocation with Default Parameter:

function greet(name = "Guest") { ... } greet(); // Uses default parameter greet("Alice"); // Overrides default parameter

6.Displaying Results:

console.log("Sum: " + sum); console.log("Product: " + product);

console.log("Difference: " + difference);

These examples illustrate different ways to define and invoke functions in JavaScript, including traditional function declarations, function expressions, arrow functions, and functions with default parameters.

JS Objects

In JavaScript, objects are a fundamental data type used to represent and organize data. They are collections of key-value pairs, where each key is a string (or a symbol), and each value can be of any data type, including other objects.

1.Key-Value Pairs:

Objects consist of key-value pairs, where each key is a unique string (or a symbol) that acts as an identifier, and each value is associated with that key. The combination of a key and its corresponding value is called a property.

2.Properties:

Properties are the individual key-value pairs within an object. Each property has a unique key that serves as its name, and the associated value can be of any data type, including numbers, strings, booleans, functions, or other objects.

3.Object Literal Notation:

The most common way to create an object in JavaScript is through object literal notation. It involves using curly braces {} and specifying the key-value pairs inside. This notation is concise and widely used for creating objects directly in the code.

4.Methods:

Functions that are associated with an object are called methods. Methods are simply properties that hold function values. They allow objects to encapsulate behavior and functionality.

5.Object Constructor:

Objects can also be created using constructor functions with the new keyword. Constructor functions are regular functions that initialize and create objects. They can be defined using the function keyword.

1.Dot Notation:

Object properties and methods are typically accessed using dot notation (object.property). This syntax allows you to retrieve or modify the values associated with a specific key.

2.Bracket Notation:

​​Alternatively, ​you ​can ​use ​bracket ​notation

(object["property"]) to access object properties. This notation is useful when the property name is dynamic or contains special characters.

3.Object Mutation:

Objects in JavaScript are mutable, meaning that their properties and methods can be modified, added, or deleted after the object is created. This dynamic nature allows for flexibility in working with data.

4.Inheritance:

Objects in JavaScript can inherit properties and methods from other objects through a mechanism known as prototype-based inheritance. This allows for the creation of object hierarchies and promotes code reuse.

5.Object Comparison:

When comparing objects in JavaScript, the comparison is based on reference equality. Two objects are considered equal only if they reference the same object in memory. This is different from primitive types, where the values themselves are compared.

6.JSON (JavaScript Object Notation):

JSON is a lightweight data interchange format that closely resembles JavaScript object literal notation. It is often used for data exchange between a server and a web application. JSON objects are strings that can be parsed into JavaScript objects.

Understanding objects is crucial for effective JavaScript programming, as they provide a versatile and powerful way to structure and represent data in your applications. Objects play a central role in organizing code and facilitating the implementation of various programming patterns.

// JavaScript Objects Example

// Object Literal let person = {   firstName: "John",   lastName: "Doe",   age: 30,   address: {     street: "123 Main St",     city: "Anytown",

zipCode: "12345"

},

hobbies: ["Reading", "Gardening", "Traveling"],

isStudent: false,   sayHello: function() {

console.log("Hello, " + this.firstName + "!");

} };

// Accessing Object Properties

console.log("First Name: " + person.firstName); console.log("Age: " + person.age); console.log("Street: " + person.address.street); console.log("Hobbies: " + person.hobbies.join(", "));

// Invoking Object Method person.sayHello();

// Object Constructor Function function Car(make, model, year) {   this.make = make;   this.model = model;   this.year = year; }

// Creating Objects using Constructor Function let car1 = new Car("Toyota", "Camry", 2022); let car2 = new Car("Honda", "Accord", 2023);

// Accessing Object Properties

console.log("Car 1: " + car1.make + " " + car1.model + ", Year: " + car1.year); console.log("Car 2: " + car2.make + " " + car2.model + ", Year: " + car2.year);

// End of JavaScript Objects Example

In this example, JavaScript objects are demonstrated using different approaches:

1.Object Literal:

let person = { ... };

2.Accessing Object Properties:

console.log("First Name: " + person.firstName); console.log("Age: " + person.age); console.log("Street: " + person.address.street); console.log("Hobbies: " + person.hobbies.join(", "));

3.Invoking Object Method: person.sayHello();

4.Object Constructor Function:

function Car(make, model, year) { ... }

5.Creating Objects using Constructor Function: let car1 = new Car("Toyota", "Camry", 2022); let car2 = new Car("Honda", "Accord", 2023);

6.Accessing Object Properties (Constructor Function):

console.log("Car 1: " + car1.make + " " + car1.model + ", Year: " + car1.year);

console.log("Car 2: " + car2.make + " " + car2.model + ", Year: " + car2.year);

These examples showcase the creation and usage of objects in JavaScript using both object literals and constructor functions. Objects can contain properties (including nested objects and arrays) and methods.

JS Events

In JavaScript, events are occurrences or happenings that take place in the browser, often as a result of user interactions or other activities. JavaScript can be used to listen for and respond to these events, allowing for dynamic and interactive web pages.

1.Event Types:

Events can be triggered by various actions, such as user interactions (e.g., clicks, keypresses, mouse movements), changes in the document (e.g., load, unload), and other browser-related activities (e.g., resizing the window, submitting a form).

2.Event Handlers:

An event handler is a function that gets executed in response to a specific event. Event handlers are registered to listen for particular events and respond accordingly.

3.Event Listeners:

Event listeners are used to attach event handlers to HTML elements. They "listen" for a specific event to occur on an element and execute the associated event handler when the event occurs.

4.Default Browser Behavior:

Many HTML elements have default behaviors associated with certain events. For example, clicking a link typically navigates to the linked page. JavaScript can be used to prevent or modify these default behaviors.

5.Bubbling and Capturing:

Event propagation in the DOM involves two phases: capturing phase and bubbling phase. Capturing occurs from the root to the target element, and bubbling occurs from the target element back up to the root. Event listeners can be set to capture or bubble, depending on the desired behavior.

1.Event Object:

When an event occurs, an event object is created that contains information about the event, such as the type of event, the target element, and any additional data related to the event.

2.Asynchronous Nature:

Events in JavaScript are often handled asynchronously. This means that event handlers do not block the execution of the rest of the program, allowing the program to continue running while waiting for events to occur.

3.Common Events:

Some common types of events include:

Click: Triggered when a mouse click occurs.

Mouseover/Mouseout: Triggered when the mouse enters or leaves an element.

Keydown/Keypress/Keyup: Triggered when a key is pressed or released.

Change: Triggered when the value of a form element changes.

Submit: Triggered when a form is submitted.

Load/Unload: Triggered when a document is fully loaded or unloaded.

4.Event Delegation:

Event delegation is a technique where a single event listener is attached to a common ancestor of multiple elements. This allows you to handle events for multiple elements with a single event listener, improving efficiency.

5.Custom Events:

In addition to native browser events, JavaScript allows the creation of custom events. Custom events enable developers to define and dispatch their own events, enhancing the flexibility and extensibility of event handling.

Understanding how to work with events in JavaScript is crucial for creating dynamic and interactive web applications. Events provide a way to respond to user actions and create a responsive and engaging user experience.

<!-- HTML Markup with JS Events Example -->

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>JS Events Example</title>

</head> <body>

<!-- Button with Click Event -->

<button id="clickButton">Click Me</button>

<!-- JavaScript Code for Events -->

<script>

// Click Event Handling

document.getElementById("clickButton").addEventListener("click", function() {     alert("Button Clicked!");

});

// Mouseover Event Handling

document.getElementById("clickButton").addEventListener("mouseover", function() {     console.log("Mouseover Event");

});

// Change Event Handling (for Input)   let inputField = document.createElement("input");

inputField.setAttribute("type", "text");   document.body.appendChild(inputField);

inputField.addEventListener("change", function(event) {     console.log("Input Changed: " + event.target.value);

});

</script>

</body>

</html>

In this example, JavaScript events are demonstrated using HTML markup and inline script:

1.Click Event Handling:

A button with the ID "clickButton" has a click event listener attached to it. When the button is clicked, an alert message is displayed.

2.Mouseover Event Handling:

The same button also has a mouseover event listener. When the mouse hovers over the button, a message is logged to the console.

3.Change Event Handling (for Input):

An input field is dynamically created and appended to the body. It has a change event listener attached to it. When the input value changes, a message is logged to the console.

These examples illustrate how to handle different types of events (click, mouseover, change) using JavaScript in an HTML document.

JS Strings

In JavaScript, strings are a fundamental data type that represents sequences of characters. Strings can include letters, numbers, symbols, and whitespace.

1.Sequence of Characters:

A string is a sequence of characters enclosed within single (' '), double (" "), or backticks (` `) quotes. Strings can include letters, numbers, symbols, and whitespace.

2.Immutable:

In JavaScript, strings are immutable, meaning their values cannot be changed once they are created. Operations that appear to modify a string actually create a new string.

3.Escape Characters:

Special characters can be represented using escape sequences, denoted by a backslash (\). For example, \n represents a newline character, and \t represents a tab character.

4.Concatenation:

Strings can be concatenated using the + operator. This involves combining two or more strings to create a new string. For example, "Hello, " + "world!" results in the string "Hello, world!".

5.Length Property:

Strings have a length property that returns the number of characters in the string. This property allows you to determine the size of a string.

6.Indexing and Access:

Individual characters within a string can be accessed using zero-based indexing. For example, str[0] retrieves the first character of the string str.

1.String Methods:

JavaScript provides a variety of built-in methods for manipulating strings. These methods include toUpperCase(), toLowerCase(), substring(), indexOf(), replace(), and more.

2.Template Literals:

Introduced in ECMAScript 6 (ES6), template literals provide a more flexible way to create strings using backticks (` `). They allow for embedded expressions and multiline strings.

3.String Comparison:

Strings can be compared using relational operators (<, >, <=, >=). Comparison is performed based on the Unicode values of the characters.

4.String Interpolation:

String interpolation refers to the embedding of expressions within strings. This can be done using concatenation or template literals.

5.Unicode Support:

JavaScript strings are encoded using UTF-16, allowing for the representation of a wide range of characters from different languages and scripts.

6.Regular Expressions:

Strings can be manipulated using regular expressions (regex). Regular expressions provide powerful pattern-matching capabilities for string manipulation.

7.String Primitives vs. String Objects:

JavaScript treats strings as primitives, but there is also a String object that provides additional methods. The distinction is often transparent due to automatic conversion between primitive strings and String objects.

8.String Immutability:

Once a string is created, its value cannot be changed. Any operation that seems to modify a string creates a new string with the modified value.

Understanding the properties and methods associated with strings in JavaScript is crucial for working with textual data and performing string manipulation tasks in web development. Strings play a vital role in handling user input, creating dynamic content, and interacting with data.

// JavaScript Strings Example

// String Declaration let greeting = "Hello, World!";

// Display String

console.log("Greeting: " + greeting);

// String Concatenation let firstName = "John"; let lastName = "Doe";

let fullName = firstName + " " + lastName;

// Display Concatenated String console.log("Full Name: " + fullName);

// String Length

let message = "This is a message."; let messageLength = message.length;

// Display String Length

console.log("Message Length: " + messageLength);

// Accessing Characters let firstChar = message[0];

let lastChar = message[message.length - 1];

// Display First and Last Characters console.log("First Character: " + firstChar); console.log("Last Character: " + lastChar);

// String Methods

let uppercaseMessage = message.toUpperCase(); let lowercaseMessage = message.toLowerCase(); let subString = message.substring(5, 10);

let replacedMessage = message.replace("message", "text");

// Display Results of String Methods

console.log("Uppercase Message: " + uppercaseMessage); console.log("Lowercase Message: " + lowercaseMessage);

console.log("Substring: " + subString); console.log("Replaced Message: " + replacedMessage);

// String Template Literal

let age = 25;

let infoMessage = `My name is ${firstName} ${lastName}. I am ${age} years old.`;

// Display String Template Literal console.log("Info Message: " + infoMessage);

// End of JavaScript Strings Example

These examples cover various string operations, including concatenation, length, character access, methods, and template literals.

JS String Methods

JavaScript provides a variety of built-in methods for manipulating strings. These methods enable developers to perform various operations on strings without having to manually iterate through characters.

1.length:

The length property returns the number of characters in a string. It allows you to determine the size of a string.

2.charAt(index):

The charAt(index) method returns the character at the specified index in a string. The index is zero-based.

3.charCodeAt(index):

The charCodeAt(index) method returns the Unicode value of the character at the specified index in a string.

4.toUpperCase():

​The toUpperCase() method converts all characters in a string to uppercase.

5.toLowerCase():

​The toLowerCase() method converts all characters in a string to lowercase.

6.substring(startIndex, endIndex):

The substring(startIndex, endIndex) method extracts a portion of a string starting from startIndex up to, but not including, endIndex.

7.slice(startIndex, endIndex):

The slice(startIndex, endIndex) method extracts a portion of a string similar to substring. If either startIndex or endIndex is negative, it counts from the end of the string.

8.indexOf(searchString, startIndex):

The indexOf(searchString, startIndex) method returns the index of the first occurrence of searchString in the string. If not found, it returns -1. The search can start from an optional startIndex.

9.lastIndexOf(searchString, startIndex):

The lastIndexOf(searchString, startIndex) method returns the index of the last occurrence of searchString in the string. If not found, it returns -1. The search can start from an optional startIndex.

1.startsWith(searchString, position):

The startsWith(searchString, position) method checks if the string starts with the specified searchString. The optional position parameter specifies where to begin the search.

2.endsWith(searchString, position):

The endsWith(searchString, position) method checks if the string ends with the specified searchString. The optional position parameter specifies where to stop the search.

3.includes(searchString, position):

The includes(searchString, position) method checks if the string contains the specified searchString. The optional position parameter specifies where to start the search.

4.replace(searchValue, replaceValue):

The replace(searchValue, replaceValue) method replaces occurrences of searchValue with replaceValue in the string.

5.trim():

The trim() method removes leading and trailing whitespaces from a string.

6.split(separator, limit):

The split(separator, limit) method splits a string into an array of substrings based on the specified separator. The optional limit parameter limits the number of splits.

7.concat(string1, string2, ...):

The concat(string1, string2, ...) method concatenates multiple strings together.

8.repeat(count):

The repeat(count) method creates a new string by repeating the original string count times.

9.match(regexp):

The match(regexp) method searches a string for a match against a regular expression and returns the matches as an array.

10.search(regexp):

The search(regexp) method searches a string for a match against a regular expression and returns the index of the first match. If no match is found, it returns -1.

These methods provide a powerful set of tools for working with strings in JavaScript, allowing developers to manipulate and extract information from textual data efficiently. Understanding these methods is essential for effective string processing in web development.

// JavaScript String Methods Example

// String Methods

let originalString = "   JavaScript String Methods   ";

let trimmedString = originalString.trim(); let uppercasedString = originalString.toUpperCase(); let lowercasedString = originalString.toLowerCase(); let subString = originalString.substring(5, 18); let replacedString = originalString.replace("Methods",

"Functions");

let splitString = originalString.split(" ");

// Display Results of String Methods console.log("Original String: " + originalString); console.log("Trimmed String: " + trimmedString); console.log("Uppercased String: " + uppercasedString); console.log("Lowercased String: " + lowercasedString); console.log("Substring: " + subString); console.log("Replaced String: " + replacedString); console.log("Split String: " + JSON.stringify(splitString));

// Chaining String Methods let modifiedString = originalString.trim().toUpperCase().replace("METHODS", "OPERATIONS");

// Display Chained Methods Result

console.log("Chained Methods Result: " + modifiedString);

// End of JavaScript String Methods Example

In this example, various JavaScript string methods are demonstrated:

1.String Trim: let trimmedString = originalString.trim();

2.String Uppercase: let uppercasedString = originalString.toUpperCase(); 3.String Lowercase:

let lowercasedString = originalString.toLowerCase();

4.Substring: let subString = originalString.substring(5, 18);

5.String Replace: let replacedString = originalString.replace("Methods",

"Functions");

6.String Split:

let splitString = originalString.split(" ");

7.Chaining String Methods:

Combining multiple string methods in a chained fashion.

8.Displaying Results:

console.log("Original String: " + originalString); console.log("Trimmed String: " + trimmedString); console.log("Uppercased String: " + uppercasedString); console.log("Lowercased String: " + lowercasedString); console.log("Substring: " + subString); console.log("Replaced String: " + replacedString); console.log("Split String: " + JSON.stringify(splitString)); console.log("Chained Methods Result: " + modifiedString); These examples showcase commonly used string methods in JavaScript and demonstrate how they can be applied to manipulate strings.

JS String Search

The JavaScript search() method is used to search for a specified pattern in a string. This method is often used with regular expressions (regex) to perform more complex search operations.

1.Method Syntax:

The search() method is invoked on a string and takes a regular expression pattern as its argument.

2.Regular Expressions:

Regular expressions are patterns that define a search or match operation on strings. They can include various characters and modifiers to create flexible and powerful search criteria.

3.Return Value:

The search() method returns the index of the first occurrence of the specified pattern in the string.

If the pattern is not found, it returns -1.

4.Case-Insensitive Search:

By default, the search() method performs a casesensitive search. To perform a case-insensitive search, you can use the i flag in the regular expression.

Use of Regular Expression Flags:

Regular expression flags such as i (case-insensitive), g (global match), and m (multiline) can be included in the regular expression pattern to modify the search behavior.

Using Capture Groups:

Regular expressions can include capture groups to extract specific portions of the matched string. This allows you to retrieve more detailed information about the match.

Finding Multiple Matches:

While the search() method returns the index of the first match, it does not find all occurrences in the string. For finding multiple matches, the match() method with the g flag is often more suitable.

Not Finding All Matches:

The search() method stops searching after the first match is found. If you need to find all matches, consider using the match() method with the g (global) flag.

Using indexOf for Simple String Search:

For simple string searches without the need for regular expressions, the indexOf() method may be more straightforward.

Case Sensitivity:

It's essential to be aware of case sensitivity when using the search() method. If a case-insensitive search is needed, consider using the appropriate regular expression flag.

Handling Absence of Matches:

If the pattern is not found, the search() method returns -1. Check for this return value to handle cases where the pattern is not present in the string.

Understanding how to use the search() method with regular expressions is valuable for performing advanced string searches and pattern matching in JavaScript. It is particularly useful when dealing with more complex search criteria that go beyond simple substring matching.

// JavaScript String Search Example

// String Search Method let originalString = "JavaScript is a powerful scripting language.";

// Using indexOf to find the position of a substring let indexOfScript = originalString.indexOf("script");

// Using includes to check if a substring exists let includesPowerful = originalString.includes("powerful");

// Using search to find the position of a substring with regular expression let searchLanguage = originalString.search(/language/i);

// Display Results console.log("Original String: " + originalString); console.log("Index of 'script': " + indexOfScript); console.log("Includes 'powerful': " + includesPowerful); console.log("Search 'language': " + searchLanguage);

// End of JavaScript String Search Example

In this example, the JavaScript string search-related methods are demonstrated:

1.indexOf:

Using indexOf to find the position of a substring ("script") in the original string.

2.includes:

Using includes to check if a substring ("powerful") exists in the original string.

3.search:

Using search to find the position of a substring ("language")               with               a               case-insensitive               regular expression.

4.Displaying Results:

console.log("Original String: " + originalString);

console.log("Index of 'script': " + indexOfScript);

console.log("Includes ​'powerful': ​" ​+ includesPowerful);

console.log("Search 'language': " + searchLanguage); These examples show how to use indexOf, includes, and search methods to perform substring searches in a

JavaScript string.

JS String Templates

JavaScript String Templates, also known as template literals, were introduced in ECMAScript 6 (ES6) to provide a more convenient way to work with strings. Template literals use backticks (` `) instead of single or double quotes and support embedded expressions and multiline strings.

1.Backticks (` `):

Template literals are delimited by backticks instead of single or double quotes. This makes them visually distinct and allows for more flexibility in working with strings.

2.Embedded Expressions:

One of the key features of template literals is the ability to embed expressions directly within the string using ${} syntax. This allows you to interpolate variables and expressions directly into the string.

3.Variable Interpolation:

Variables can be easily interpolated into a template literal by placing them inside ${}. This eliminates the need for explicit concatenation or escaping when combining variables with strings.

4.Expression Evaluation:

The expressions embedded within ${} are evaluated, and their results are converted to strings and inserted into the template. This is particularly useful for dynamic content generation.

Multiline Strings:

Template literals support multiline strings without the need for explicit newline characters (\n). Line breaks within the backticks are preserved in the resulting string.

String Formatting:

Template literals provide a cleaner and more readable way to format strings, especially when dealing with complex or dynamic content.

Tagged Templates:

Template literals can be used with tagged templates, where a function (known as a tag function) processes the template literal and its embedded expressions. This allows for advanced string manipulation and formatting.

Escape Sequences:

While template literals provide a more natural way to handle multiline strings, escape sequences (e.g., \n, \t) are still valid and can be used if needed.

No Implicit Line Continuation:

Unlike regular strings created with single or double quotes, template literals do not have an implicit line continuation when the code spans multiple lines. Each line must be explicitly included within the backticks.

Consistent Syntax:

The syntax for template literals is consistent, making it easier to read and maintain code compared to using concatenation or complex string manipulation.

HTML Templates:

Template literals are commonly used in web development for creating HTML templates, where dynamic content can be seamlessly integrated into the structure of the template. JavaScript String Templates provide a more modern and expressive way to work with strings, especially in scenarios where dynamic content or multiline strings are involved. Their concise syntax and support for expressions make them a valuable addition to the JavaScript language.

// JavaScript String Templates Example

// String Template Literal let firstName = "John"; let lastName = "Doe"; let age = 30;

let infoMessage = `My name is ${firstName} ${lastName}. I am ${age} years old.`;

// Display String Template Literal console.log("Info Message: " + infoMessage);

// String Templates with Expressions let x = 5; let y = 10; let resultMessage = `The sum of ${x} and ${y} is ${x + y}.`;

// Display String Template with Expressions console.log("Result Message: " + resultMessage);

// Multi-line String Template let multilineMessage = `   This is a multi-line   string template example.

It supports line breaks.

`;

// Display Multi-line String Template

console.log("Multi-line Message: " + multilineMessage);

// End of JavaScript String Templates Example

In this example, JavaScript string templates (template literals) are demonstrated:

1.String Template Literal:

Using backticks (`) to create a template literal with embedded variables.

2.String Templates with Expressions:

Incorporating expressions (e.g., ${x + y}) directly within the template.

3.Multi-line String Template:

​Utilizing ​backticks ​for ​creating ​multi-line ​string templates.

4.Displaying Results:

console.log("Info Message: " + infoMessage); console.log("Result Message: " + resultMessage); console.log("Multi-line Message: " + multilineMessage); These examples showcase the use of string templates to create more readable and flexible strings in JavaScript.

JS Numbers

In JavaScript, numbers are a primitive data type used to represent numerical values.

1.Numeric Types:

JavaScript numbers represent both integers and floatingpoint numbers (decimal numbers). There is no distinction between integer and floating-point types.

2.Floating-Point Representation:

All numbers in JavaScript, including integers, are internally represented as 64-bit floating-point numbers according to the IEEE 754 standard. This allows for a wide range of values but may lead to precision issues in certain calculations.

3.Arithmetic Operations:

JavaScript supports various arithmetic operations on numbers, including addition (+), subtraction (-), multiplication (*), division (/), and modulo (%).

4.Math Object:

JavaScript provides a Math object with methods for performing more complex mathematical operations, such as trigonometric functions, exponentiation, logarithms, and random number generation.

5.Infinity and -Infinity:

JavaScript represents positive infinity as Infinity and negative infinity as -Infinity. These values are used to represent mathematical concepts such as division by zero or values exceeding the maximum representable number.

6.NaN (Not-a-Number):

The special value NaN represents an undefined or unrepresentable value in JavaScript. It is often the result of invalid mathematical operations, such as dividing zero by zero.

1.Precision and Rounding:

Due to the floating-point representation, JavaScript numbers may not always be precise. Some calculations may result in rounding errors, especially when dealing with decimal fractions.

2.Integer Limits:

JavaScript numbers have a finite precision, and there are limits to the maximum and minimum integer values that can be represented accurately. These limits can be accessed using the Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER constants.

3.Parsing Numbers:

Numbers can be parsed from strings using functions like parseInt() and parseFloat(). These functions attempt to extract numeric values from string representations.

4.Number Methods:

The Number object in JavaScript provides methods such as isNaN() to check if a value is NaN, isFinite() to check if a value is a finite number, and toFixed() to round a number to a specified number of decimal places.

5.Unary Plus and Minus:

The unary plus (+) and unary minus (-) operators can be used to convert a value to a number or change its sign.

6.Exponential Notation:

JavaScript allows representing very large or very small numbers using exponential notation. For example, 1e3 represents 1000, and 1e-3 represents 0.001.

Understanding the characteristics and behaviors of JavaScript numbers is essential for accurate mathematical operations and avoiding potential pitfalls associated with floating-point precision. Developers should be aware of the limitations and quirks of numeric operations in JavaScript to write reliable and efficient code.

// JavaScript Numbers Example

// Number Declaration let integerNumber = 42; let floatingPointNumber = 3.14; let scientificNotation = 5.2e3; // 5200

// Display Numbers

console.log("Integer Number: " + integerNumber); console.log("Floating Point Number: " + floatingPointNumber); console.log("Scientific Notation: " + scientificNotation);

// Arithmetic Operations let sum = integerNumber + floatingPointNumber; let difference = integerNumber - floatingPointNumber; let product = integerNumber * floatingPointNumber; let quotient = integerNumber / floatingPointNumber; let remainder = 10 % 3; // Remainder of the division

// Display Arithmetic Results console.log("Sum: " + sum); console.log("Difference: " + difference); console.log("Product: " + product); console.log("Quotient: " + quotient); console.log("Remainder: " + remainder);

// Increment and Decrement let count = 5; count++; let newCount = count--;

// Display Increment and Decrement Results console.log("Count After Increment: " + count); console.log("New Count After Decrement: " + newCount);

// NaN (Not a Number) let resultNaN = "Hello" / 2;

// Display NaN Result

console.log("Result NaN: " + resultNaN); // End of JavaScript Numbers Example

In this example, JavaScript numbers are demonstrated with various aspects:

1.Number Declaration:

let integerNumber = 42; let floatingPointNumber = 3.14; let scientificNotation = 5.2e3; // 5200

2.Displaying Numbers:

console.log("Integer Number: " + integerNumber); console.log("Floating Point Number: " + floatingPointNumber); console.log("Scientific Notation: " + scientificNotation);

3.Arithmetic Operations:

Addition (+), Subtraction (-), Multiplication (*), Division (/), Modulus (%).

4.Displaying Arithmetic Results:

console.log("Sum: " + sum); console.log("Difference: " + difference); console.log("Product: " + product); console.log("Quotient: " + quotient); console.log("Remainder: " + remainder);

5.Increment and Decrement: count++; (Increment) count--; (Decrement)

6.Displaying Increment and Decrement Results:

console.log("Count After Increment: " + count); console.log("New Count After Decrement: " + newCount);

7.NaN (Not a Number): let resultNaN = "Hello" / 2;

8.Displaying NaN Result:

console.log("Result NaN: " + resultNaN);

These examples cover basic operations and behaviors related to numbers in JavaScript.

JS BigInt

In JavaScript, the BigInt is a relatively recent addition (introduced in ECMAScript 2020) to the language that allows for the representation of integers of arbitrary precision.

1.Arbitrary Precision:

Unlike regular JavaScript numbers, which are represented as 64-bit floating-point values, BigInt allows for the representation of integers with arbitrary precision. This means that BigInt can handle integer values of any size without loss of precision.

2.Syntax:

BigInt literals are created by appending n or N to the end of an integer literal. For example, 123n represents a BigInt with the value 123.

3.Usage:

BigInt is typically used when dealing with integers that exceed the maximum safe integer value (Number.MAX_SAFE_INTEGER) or when precision is crucial in mathematical calculations.

4.Arithmetic Operations:

BigInt supports standard arithmetic operations, such as addition, subtraction, multiplication, and division. When performing operations involving BigInt and regular numbers, the result is always a BigInt.

5.No Loss of Precision:

Regular JavaScript numbers have a finite precision, and operations involving very large or very small numbers may result in rounding errors. BigInt is not subject to this limitation, providing accurate results for integer arithmetic.

1.Math Object:

The Math object in JavaScript does not have methods that directly support BigInt. Instead, mathematical operations involving BigInt are performed using standard arithmetic operators.

2.Comparisons:

When comparing values, BigInt can be compared with other BigInt values or regular numbers. The result is based on numerical comparison without any type coercion.

3.Type Coercion:

BigInt values and regular numbers are distinct types, and operations between them result in a BigInt. However, attempts to perform operations like addition or subtraction between a BigInt and a non-integer type (e.g., a string or boolean) will result in a TypeError.

4.Limited Use Cases:

While BigInt provides a solution for cases requiring arbitrary precision integers, it's important to note that it is not a replacement for regular numbers in all situations. BigInt is not suitable for operations that involve non-integer values or require floating-point arithmetic.

5.Compatibility:

Support for BigInt is available in modern JavaScript environments, but older browsers or environments may not fully support it. It's essential to consider compatibility when using BigInt in web applications.

BigInt is a valuable addition to JavaScript, especially for scenarios where precise integer arithmetic is required, and the limitations of regular numbers need to be overcome. It provides developers with a way to handle large integers without sacrificing accuracy or encountering rounding issues.

// JavaScript BigInt Example

// BigInt Declaration let regularNumber = 42; let bigIntNumber = BigInt("9007199254740991"); // Maximum safe integer value

// Display Numbers console.log("Regular Number: " + regularNumber); console.log("BigInt Number: " + bigIntNumber);

// BigInt Operations let sumBigInt = bigIntNumber + BigInt(42); let multiplyBigInt = bigIntNumber * BigInt(3);

// Display BigInt Results console.log("Sum with BigInt: " + sumBigInt); console.log("Multiplication with BigInt: " + multiplyBigInt);

// Mixing BigInt with Regular Numbers (TypeError)

// Uncommenting the following line will result in a TypeError:

// let mixedResult = bigIntNumber + 42;

// End of JavaScript BigInt Example

In this example, JavaScript BigInt is demonstrated:

1.BigInt Declaration: ​let bigIntNumber = BigInt("9007199254740991");

2.Displaying Numbers:

console.log("Regular Number: " + regularNumber); console.log("BigInt Number: " + bigIntNumber);

3.BigInt Operations:

​​Basic arithmetic operations with BigInt.

4.Displaying BigInt Results:

console.log("Sum with BigInt: " + sumBigInt);

console.log("Multiplication ​with ​BigInt: ​" ​+ multiplyBigInt);

5.Mixing BigInt with Regular Numbers (TypeError):

Attempting to mix BigInt with regular numbers will result in a TypeError.

Note: BigInt is useful when dealing with very large integer values that exceed the safe integer range in JavaScript. Operations involving BigInts must be explicitly performed with BigInts to avoid loss of precision. Mixing BigInts with regular numbers in certain operations may result in a TypeError.

JS Number Methods

JavaScript provides a variety of methods associated with the Number object, which can be used to perform operations on numeric values.

1.isNaN(value):

The isNaN(value) method checks if a value is NaN (Not-aNumber). It returns true if the value is NaN, and false if it is a valid number or can be converted to one.

2.isFinite(value):

The isFinite(value) method checks if a value is a finite number (not Infinity or -Infinity). It returns true if the value is finite and can be represented as a number; otherwise, it returns false.

3.parseFloat(string):

The parseFloat(string) method parses a string and returns the first floating-point number it encounters. It is useful for extracting numeric values from strings.

4.parseInt(string, radix):

The parseInt(string, radix) method parses a string and returns an integer based on the provided radix (base). It is commonly used to convert strings representing numbers into integers.

5.toExponential(fractionDigits):

The toExponential(fractionDigits) method returns a string representing the number in exponential notation. The optional fractionDigits parameter specifies the number of digits after the decimal point.

6.toFixed(digits):

The toFixed(digits) method returns a string representing the number with a fixed number of digits after the decimal point. It rounds the number if necessary.

1.toPrecision(precision):

The toPrecision(precision) method returns a string representing the number with the specified precision. It includes both the integer and fractional parts of the number.

2.toString(radix):

The toString(radix) method converts a number to a string based on the specified radix (base). This is useful for representing numbers in different numeral systems, such as binary or hexadecimal.

3.valueOf():

The valueOf() method returns the primitive value of a Number object. It is automatically called by JavaScript when a numeric conversion is needed.

4.toFixed(), toPrecision(), and toExponential() for String Formatting:

These methods are often used to format numeric values for display, such as in user interfaces, where the number of decimal places or overall precision is important.

5.Mathematical Operations:

While not methods of the Number object, arithmetic operations (+, -, *, /) and the Math object provide various mathematical functions that are commonly used with numeric values.

6.Constants:

The Number object includes constants such as Number.MAX_VALUE (the maximum representable number in JavaScript), Number.MIN_VALUE (the smallest positive representable number), and others.

Understanding and utilizing these Number methods is essential for manipulating and formatting numeric values in JavaScript. These methods provide developers with tools for converting, formatting, and checking the properties of numeric values in their applications.

// JavaScript Number Methods Example

// Number Methods let originalNumber = 123.456;

let fixedNumber = originalNumber.toFixed(2); let roundedNumber = Math.round(originalNumber); let absoluteNumber = Math.abs(-5); let powerNumber = Math.pow(2, 3); let squareRoot = Math.sqrt(25); let randomDecimal = Math.random(); // Generates a random decimal between 0 and 1

let randomInteger = Math.floor(Math.random() * 10) + 1; // Generates a random integer between 1 and 10

// Display Results of Number Methods console.log("Original Number: " + originalNumber); console.log("Fixed Number (2 decimal places): " + fixedNumber); console.log("Rounded Number: " + roundedNumber); console.log("Absolute Number: " + absoluteNumber); console.log("2 to the power of 3: " + powerNumber); console.log("Square Root of 25: " + squareRoot); console.log("Random Decimal: " + randomDecimal); console.log("Random Integer (between 1 and 10): " + randomInteger);

// End of JavaScript Number Methods Example

In this example, various JavaScript number methods are demonstrated:

1.toFixed:

Rounding a number to a fixed number of decimal places. let fixedNumber = originalNumber.toFixed(2);

2.Math.round:

Rounding a number to the nearest integer. let roundedNumber = Math.round(originalNumber);

3.Math.abs:

Getting the absolute value of a number.

let absoluteNumber = Math.abs(-5);

4.Math.pow:

Calculating the power of a number.

let powerNumber = Math.pow(2, 3);

5.Math.sqrt:

Calculating the square root of a number. let squareRoot = Math.sqrt(25);

6.Math.random:

Generating random decimal and integer values.

let randomDecimal = Math.random();

let randomInteger = Math.floor(Math.random() * 10) + 1;

7.Displaying Results:

console.log("Original Number: " + originalNumber); console.log("Fixed Number (2 decimal places): " + fixedNumber);

console.log("Rounded Number: " + roundedNumber); console.log("Absolute Number: " + absoluteNumber); console.log("2 to the power of 3: " + powerNumber); console.log("Square Root of 25: " + squareRoot); console.log("Random Decimal: " + randomDecimal);

console.log("Random Integer (between 1 and 10): " + randomInteger);

These examples cover common methods for working with numbers in JavaScript, including rounding, absolute values, powers, square roots, and random number generation.

JS Number Properties

JavaScript's Number object includes several properties that provide information about numeric values and define certain limits.

Number.MAX_VALUE:

The Number.MAX_VALUE property represents the maximum positive numeric value that can be represented in JavaScript. This value is approximately

1.7976931348623157e+308.

Number.MIN_VALUE:

The Number.MIN_VALUE property represents the smallest positive numeric value greater than zero that can be represented in JavaScript. It is the positive equivalent of the smallest positive denormalized floating-point number.

The value is approximately 5e-324.

Number.POSITIVE_INFINITY:

The Number.POSITIVE_INFINITY property represents positive infinity. It is a special value used to denote results of mathematical operations that exceed the representable range for positive numbers.

Number.NEGATIVE_INFINITY:

The Number.NEGATIVE_INFINITY property represents negative infinity. Similar to positive infinity, it is used to denote results of mathematical operations that exceed the representable range for negative numbers.

1.Number.NaN:

The Number.NaN property represents the special value "Not-a-Number" (NaN). It is returned when a mathematical operation has an undefined or unrepresentable result.

2.Number.EPSILON:

The Number.EPSILON property represents the difference between 1 and the smallest representable number greater than 1. It is a tiny value that can be used to perform safe comparisons for floating-point numbers.

3.Number.MAX_SAFE_INTEGER:

The Number.MAX_SAFE_INTEGER property represents the maximum safe integer value in JavaScript. It is the largest integer that can be accurately represented without loss of precision. The value is 9007199254740991.

4.Number.MIN_SAFE_INTEGER:

The Number.MIN_SAFE_INTEGER property represents the minimum safe integer value in JavaScript. It is the smallest integer that can be accurately represented without loss of precision. The value is -9007199254740991.

5.Number.isFinite():

The Number.isFinite() method is not a property but a static method of the Number object. It checks if a value is a finite number and returns true if the value is a finite number (not NaN, Infinity, or -Infinity); otherwise, it returns false.

6.Number.isNaN():

The Number.isNaN() method is not a property but a static method of the Number object. It checks if a value is NaN and returns true if the value is NaN; otherwise, it returns false.

These properties are valuable for handling numeric values in JavaScript, and they provide information about the range, precision, and special values associated with numeric calculations. Understanding these properties is crucial for writing robust and reliable JavaScript code that involves numerical operations.

// JavaScript Number Properties Example

// Number Properties

let maxSafeInteger = Number.MAX_SAFE_INTEGER; let minSafeInteger = Number.MIN_SAFE_INTEGER; let maxNumberValue = Number.MAX_VALUE; let minNumberValue = Number.MIN_VALUE; let positiveInfinity = Number.POSITIVE_INFINITY; let negativeInfinity = Number.NEGATIVE_INFINITY; let notANumber = Number.NaN;

// Display Number Properties

console.log("Max Safe Integer: " + maxSafeInteger); console.log("Min Safe Integer: " + minSafeInteger); console.log("Max Number Value: " + maxNumberValue); console.log("Min Number Value: " + minNumberValue); console.log("Positive Infinity: " + positiveInfinity); console.log("Negative Infinity: " + negativeInfinity); console.log("Not a Number (NaN): " + notANumber); // End of JavaScript Number Properties Example

In this example, various JavaScript number properties are demonstrated:

1.Number.MAX_SAFE_INTEGER: Maximum safe integer value.

let maxSafeInteger = Number.MAX_SAFE_INTEGER;

2.Number.MIN_SAFE_INTEGER: Minimum safe integer value. let minSafeInteger = Number.MIN_SAFE_INTEGER;

3.Number.MAX_VALUE:

Maximum representable positive number value. let maxNumberValue = Number.MAX_VALUE;

4.Number.MIN_VALUE:

Minimum representable positive number value (positive but close to zero).

let minNumberValue = Number.MIN_VALUE;

5.Number.POSITIVE_INFINITY:

Positive infinity value.

let positiveInfinity = Number.POSITIVE_INFINITY;

6.Number.NEGATIVE_INFINITY:

Negative infinity value.

let negativeInfinity = Number.NEGATIVE_INFINITY;

7.Number.NaN:

Not a Number value.

let notANumber = Number.NaN;

8.Displaying Number Properties:

console.log("Max Safe Integer: " + maxSafeInteger); console.log("Min Safe Integer: " + minSafeInteger); console.log("Max Number Value: " + maxNumberValue); console.log("Min Number Value: " + minNumberValue); console.log("Positive Infinity: " + positiveInfinity); console.log("Negative Infinity: " + negativeInfinity); console.log("Not a Number (NaN): " + notANumber);

These examples showcase various properties associated with numbers in JavaScript, including maximum and minimum safe integers, maximum and minimum number values, positive and negative infinity, and the NaN (Not a Number) value.

JS Arrays

In JavaScript, an array is a data structure that allows you to store and organize multiple values in a single variable.

1.Ordered Collection:

An array is an ordered collection of values, where each value is identified by an index or a key. The index starts from 0 for the first element, 1 for the second, and so on.

2.Homogeneous or Heterogeneous Elements:

Arrays can contain values of the same type (homogeneous) or different types (heterogeneous). In JavaScript, arrays are often used to store elements of various data types.

3.Zero-Based Indexing:

The indices of array elements start at 0. The first element is at index 0, the second at index 1, and so forth. Negative indices count from the end, with -1 being the last element.

4.Dynamic Size:

Arrays in JavaScript are dynamic, meaning their size can change during runtime. You can add or remove elements from an array, and the array will automatically adjust its size.

5.Mutability:

Array elements can be modified after the array is created. You can change the value of an existing element by assigning a new value to it.

6.Length Property:

Arrays have a length property that indicates the number of elements in the array. It can be used to iterate over the elements or to determine the size of the array.

1.Common Array Operations:

Arrays support various operations, such as adding elements (push() and unshift()), removing elements (pop() and shift()), and slicing and concatenating arrays.

2.Iteration:

Arrays can be iterated using loops (e.g., for loop) or higher-order functions like forEach(), map(), filter(), and reduce().

3.Array Methods:

JavaScript provides built-in array methods for performing common operations, such as concat(), slice(), splice(), indexOf(), includes(), and more.

4.Nested Arrays:

Arrays can contain other arrays, creating nested structures. This allows for the creation of multidimensional arrays or more complex data structures.

5.Object-Like Behavior:

In JavaScript, arrays are objects with integer-based keys, and they inherit from the Array prototype. However, they also have array-specific methods and behaviors.

6.Array Literals:

Arrays can be created using array literals, which involve enclosing a list of values within square brackets ([]).

7.Sparse Arrays:

JavaScript allows for sparse arrays, where certain indices may not have corresponding elements. The length property reflects the highest index in the array.

8.Destructuring Assignment:

Array elements can be easily extracted and assigned using destructuring assignment syntax.

9.Use Cases:

Arrays are widely used for tasks such as storing collections of data, representing sequences, implementing stacks and queues, and managing ordered sets of elements.

Understanding arrays is fundamental to JavaScript programming, as they provide a versatile and efficient way to work with collections of data in a structured manner. Arrays are a key component of many algorithms and are extensively used in web development for tasks ranging from handling lists of items to managing complex data structures.

// JavaScript Arrays Example

// Array Declaration

let fruits = ["Apple", "Banana", "Orange", "Mango"];

// Accessing Array Elements let firstFruit = fruits[0];

let lastFruit = fruits[fruits.length - 1];

// Modifying Array Elements fruits[1] = "Grapes";

// Adding Elements to the End fruits.push("Pineapple");

// Removing Element from the End let removedFruit = fruits.pop();

// Display Array and Results

console.log("Fruits Array: " + JSON.stringify(fruits)); console.log("First Fruit: " + firstFruit); console.log("Last Fruit: " + lastFruit); console.log("Removed Fruit: " + removedFruit);

// End of JavaScript Arrays Example

In this example, JavaScript arrays are demonstrated:

1.Array Declaration:

​              let fruits = ["Apple", "Banana", "Orange", "Mango"];

2.Accessing Array Elements: let firstFruit = fruits[0]; let lastFruit = fruits[fruits.length - 1];

3.Modifying Array Elements: ​fruits[1] = "Grapes";

4.Adding Elements to the End: ​fruits.push("Pineapple");

5.Removing Element from the End: ​let removedFruit = fruits.pop();

6.Displaying Array and Results:

console.log("Fruits Array: " + JSON.stringify(fruits)); console.log("First Fruit: " + firstFruit); console.log("Last Fruit: " + lastFruit); console.log("Removed Fruit: " + removedFruit);

This example covers basic operations with arrays, including declaration, accessing elements, modifying elements, adding elements to the end, and removing elements from the end.

JS Array Methods

JavaScript provides a variety of built-in methods that can be used to manipulate arrays.

1.concat():

The concat() method is used to merge two or more arrays, creating a new array with the combined elements.

2.filter():

​The filter() method creates a new array containing elements that satisfy a specified condition. It does not modify the original array.

3.map():

The map() method creates a new array by applying a function to each element in the original array. It transforms each element according to the provided function.

4.find():

The find() method returns the first element in an array that satisfies a specified condition. It does not modify the original array.

5.indexOf():

​The indexOf() method returns the index of the first occurrence of a specified element in an array. If the element is not found, it returns -1.

6.includes():

The includes() method checks if an array includes a specified element. It returns true if the element is found, and false otherwise.

7.push():

The push() method adds one or more elements to the end of an array and returns the new length of the array.

8.pop():

The pop() method removes the last element from an array and returns that element. It modifies the original array.

1.shift():

The shift() method removes the first element from an array and returns that element. It modifies the original array.

2.unshift():

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

3.splice():

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

4.slice():

The slice() method returns a shallow copy of a portion of an array into a new array. It does not modify the original array.

5.reverse():

The reverse() method reverses the order of the elements in an array. It modifies the original array.

6.join():

The join() method creates a string by concatenating all the elements of an array using a specified separator.

7.sort():

The sort() method sorts the elements of an array in place. The default sort order is based on converting elements to strings and comparing their sequences of UTF-16 code units.

8.reduce():

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

9.forEach():

The forEach() method executes a provided function once for each array element. It does not return a new array.

10.splice():

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

11.some():

The some() method tests whether at least one element in the array passes the test implemented by the provided function.

12.every():

The every() method tests whether all elements in the array pass the test implemented by the provided function.

These array methods provide a powerful set of tools for working with arrays in JavaScript. They enable developers to perform common operations such as filtering, mapping, finding elements, and modifying array contents in a concise and efficient manner. Understanding these methods is essential for effective array manipulation in JavaScript.

// JavaScript Array Methods Example

// Array Declaration let numbers = [4, 2, 8, 5, 1];

// Array Methods

let sortedNumbers = numbers.sort((a, b) => a - b); let reversedNumbers = numbers.reverse(); let slicedNumbers = numbers.slice(1, 4); let indexOfNumber = numbers.indexOf(8); let includesNumber = numbers.includes(3); let mappedNumbers = numbers.map(num => num * 2); let filteredNumbers = numbers.filter(num => num > 3); let sumOfNumbers = numbers.reduce((sum, num) => sum + num, 0);

// Display Results of Array Methods console.log("Original Numbers Array: " + JSON.stringify(numbers));

console.log("Sorted Numbers Array: " + JSON.stringify(sortedNumbers)); console.log("Reversed Numbers Array: " + JSON.stringify(reversedNumbers)); console.log("Sliced Numbers Array: " + JSON.stringify(slicedNumbers));

console.log("Index of Number 8: " + indexOfNumber); console.log("Includes Number 3: " + includesNumber);

console.log("Mapped Numbers Array: " + JSON.stringify(mappedNumbers)); console.log("Filtered Numbers Array: " + JSON.stringify(filteredNumbers));

console.log("Sum of Numbers: " + sumOfNumbers); // End of JavaScript Array Methods Example

In this example, various JavaScript array methods are demonstrated:

sort:

Sorting the array in ascending order. let sortedNumbers = numbers.sort((a, b) => a - b);

reverse:

Reversing the order of elements in the array.

let reversedNumbers = numbers.reverse(); slice:

Extracting a portion of the array.

let slicedNumbers = numbers.slice(1, 4);

indexOf:

Finding the index of a specific element in the array.

let indexOfNumber = numbers.indexOf(8);

includes:

Checking if a specific element exists in the array.

let includesNumber = numbers.includes(3);

map:

Creating a new array with each element doubled.

let mappedNumbers = numbers.map(num => num * 2); filter:

Creating a new array with elements greater than 3.

let filteredNumbers = numbers.filter(num => num > 3);

reduce:

Calculating the sum of all elements in the array.

let sumOfNumbers = numbers.reduce((sum, num) => sum + num, 0); Displaying Results:

console.log("Original Numbers Array: " + JSON.stringify(numbers)); console.log("Sorted Numbers Array: " + JSON.stringify(sortedNumbers)); console.log("Reversed Numbers Array: " + JSON.stringify(reversedNumbers)); console.log("Sliced Numbers Array: " + JSON.stringify(slicedNumbers)); console.log("Index of Number 8: " + indexOfNumber); console.log("Includes Number 3: " + includesNumber); console.log("Mapped Numbers Array: " + JSON.stringify(mappedNumbers)); console.log("Filtered Numbers Array: " + JSON.stringify(filteredNumbers));

console.log("Sum of Numbers: " + sumOfNumbers);

These examples cover common methods for working with arrays in JavaScript, including sorting, reversing, slicing, searching, mapping, filtering, and reducing.

JS Array Sort

The sort() method in JavaScript is used to arrange the elements of an array in a sorted order.

1.Default Sorting:

By default, the sort() method sorts the elements of an array as strings. This means that the elements are converted to strings and sorted based on their UTF-16 code unit values.

2.In-Place Sorting:

The sort() method performs an in-place sort, meaning it modifies the original array and does not create a new array.

3.Numeric Sorting:

When sorting numeric values, the default behavior may not produce the expected result. To achieve numeric sorting, a compare function can be provided as an argument to the sort() method.

4.Compare Function:

A compare function is a callback function that defines the sort order. It takes two parameters (usually referred to as a and b) and returns a negative, zero, or positive value, indicating the relative order of the two elements.

5.Ascending Order:

If the compare function returns a negative value, a will be placed before b, resulting in ascending order.

Descending Order:

If the compare function returns a positive value, b will be placed before a, resulting in descending order.

Stability:

The sort() algorithm used by JavaScript engines is not guaranteed to be stable. This means that the order of equal elements may not be preserved.

Default Lexicographic Sorting:

For strings, the default lexicographic (dictionary) sorting may not always produce intuitive results. For more complex sorting, a custom compare function can be provided.

Unicode Sorting:

The default sorting order is based on Unicode code point values. This can lead to unexpected results when sorting strings with characters from different scripts.

Alphabetic Sorting:

To perform a case-insensitive alphabetic sort, a caseinsensitive compare function can be used.

Time Complexity:

The time complexity of the sort() method depends on the specific JavaScript engine, but it is typically O(n log n), making it efficient for moderate-sized arrays.

Edge Cases:

When sorting arrays of objects, the compare function should be tailored to the specific sorting criteria for the objects.

The sort() method is a versatile tool for arranging the elements of an array, and its behavior can be customized by providing a compare function. Understanding how to use the sort() method effectively is crucial for working with arrays in JavaScript, especially when dealing with various data types and sorting criteria.

// JavaScript Array Sort Example

// Array Declaration let fruits = ["Banana", "Apple", "Orange", "Mango"];

// Sorting Array let sortedFruits = fruits.sort();

// Display Original and Sorted Arrays console.log("Original Fruits Array: " + JSON.stringify(fruits)); console.log("Sorted Fruits Array: " + JSON.stringify(sortedFruits));

// End of JavaScript Array Sort Example

In this example, the JavaScript array sort method is demonstrated:

1.sort:

Sorting the elements of the array in lexicographical order (alphabetical order for strings). let sortedFruits = fruits.sort();

2.Displaying Results:

​console.log("Original

JSON.stringify(fruits));

Fruits
Array:
"
+

​console.log("Sorted
Fruits
Array:
"
+

JSON.stringify(sortedFruits));

These examples show how the sort method can be used to sort the elements of an array. Note that the default behavior of sort is lexicographical sorting, which works well for strings. For numerical sorting, a comparison function can be provided as an argument to the sort method.

JS Array Iteration

Array iteration in JavaScript refers to the process of visiting each element in an array and performing a specific operation on each element.

1.Loop Iteration:

Traditional loop constructs like for and while can be used for array iteration. You can iterate over the indices of the array and access each element using the index.

2.forEach():

The forEach() method is a built-in array method that provides a concise way to iterate over each element of an array. It takes a callback function as an argument, and this function is executed for each element in the array.

3.Callback Function:

The callback function passed to forEach() takes three parameters: the current element, the current index, and the array being iterated over. This allows you to perform operations on each element based on its value and position.

4.Read-Only Operation:

forEach() is primarily used for read-only operations on array elements. It's not intended for modifying the array itself, although the callback function can have side effects.

5.Return Value:

The forEach() method does not return a new array; it returns undefined. It is used for its side effects on the elements.

1.map():

The map() method is another built-in array method used for iteration. It creates a new array by applying a provided function to each element of the array and returning the results.

2.Return New Array:

Unlike forEach(), map() returns a new array that contains the results of applying the provided function to each element of the original array.

3.filter():

The filter() method is used to create a new array with elements that satisfy a specified condition. It also involves iteration over the elements of the array.

4.reduce():

The reduce() method is used for iterative computation on array elements. It applies a provided function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

5.some() and every():

The some() method tests whether at least one element in the array passes the test implemented by the provided function. The every() method tests whether all elements in the array pass the test.

6.Iterator Methods:

ES6 introduced the concept of iterable objects and iterator methods. Array iteration can be performed using for...of loops and methods like entries(), keys(), and values().

7.Callbacks and Asynchronous Iteration:

Callback functions used in array iteration can be synchronous or asynchronous. Modern JavaScript also supports asynchronous iteration using for...of and asynchronous functions.

Array iteration is a fundamental concept in JavaScript programming, and choosing the appropriate iteration method depends on the specific requirements of the task. Understanding these iteration methods is essential for effective manipulation and processing of arrays in JavaScript.

// JavaScript Array Iteration Example

// Array Declaration let numbers = [1, 2, 3, 4, 5];

// forEach Method console.log("Using forEach Method:"); numbers.forEach(function (number) {

console.log(number);

});

// map Method

console.log("\nUsing map Method:"); let doubledNumbers = numbers.map(function (number) {   return number * 2;

});

console.log("Doubled Numbers: " +

JSON.stringify(doubledNumbers));

// filter Method

console.log("\nUsing filter Method:"); let evenNumbers = numbers.filter(function (number) {   return number % 2 === 0;

});

console.log("Even Numbers: " + JSON.stringify(evenNumbers));

// reduce Method

console.log("\nUsing reduce Method:"); let sumOfNumbers = numbers.reduce(function (sum, number) {   return sum + number;

}, 0);

console.log("Sum of Numbers: " + sumOfNumbers);

// End of JavaScript Array Iteration Example

In this example, various JavaScript array iteration methods are demonstrated:

1.forEach:

Iterating over each element in the array. numbers.forEach(function (number) { console.log(number); });

2.map:

Creating a new array by applying a function to each element.

let doubledNumbers = numbers.map(function (number) { return number * 2; });

3.filter:

Creating a new array with elements that satisfy a condition.

let evenNumbers = numbers.filter(function (number) { return number % 2 === 0; });

4.reduce:

Reducing the array to a single value by applying a function.

let sumOfNumbers = numbers.reduce(function (sum, number) { return sum + number; }, 0);

5.Displaying Results:

console.log("Using forEach Method:"); console.log("Using map Method:"); console.log("Using filter Method:"); console.log("Using reduce Method:");

These examples demonstrate the use of forEach, map, filter, and reduce methods for iterating over and processing elements in a JavaScript array.

JS Array Const

In JavaScript, the const keyword is used to declare constants, which are variables whose values cannot be reassigned after they are initially set. When const is used with arrays, it doesn't make the array itself immutable; instead, it prevents the variable from being reassigned to a different array.

1.Array Reference Immutability:

When an array is declared using const, the reference to the array cannot be reassigned. This means that the variable itself (holding the reference) cannot point to a different array.

2.Array Elements Mutability:

However, using const does not make the individual elements of the array immutable. You can still modify the contents of the array, including adding, removing, or modifying elements.

3.Preventing Reassignment:

If you declare an array using const, attempting to reassign the variable to a different array will result in an error. This is useful for preventing accidental reassignment and ensuring that the variable consistently refers to the same array.

4.Block-Scoped:

Like other variables declared with const, the array variable is block-scoped. It is only accessible within the block or function where it is defined.

1.Object Properties:

If the array is an object property and declared with const, the property can still be reassigned to a different array. The immutability applies to the variable holding the reference, not the property itself.

2.Initializing with Values:

When declaring an array with const, it can be initialized with values, and those values can be modified (added, removed, or changed). The restriction is on reassigning the variable to a new array.

3.Use Cases:

const is often used for array variables when you want to ensure that the reference to the array remains constant throughout the scope of the variable. It's helpful for preventing accidental reassignment and promoting code stability.

4.Immutability Patterns:

If you need an immutable array (i.e., an array whose elements cannot be changed), you may need to use techniques like creating a new array with modified elements instead of modifying the existing array in place.

In summary, using const with arrays in JavaScript ensures that the variable holding the reference to the array cannot be reassigned to a different array. It doesn't make the array or its elements themselves immutable, so you can still modify the contents of the array while keeping the reference constant.

// JavaScript Array Const Example

// Constant Array Declaration const colors = ["Red", "Green", "Blue"];

// Attempting to Modify the Array (Will Result in Error) // Uncommenting the following line will result in a TypeError: // colors.push("Yellow");

// Displaying the Constant Array

console.log("Colors Array: " + JSON.stringify(colors));

// End of JavaScript Array Const Example

In this example, a JavaScript array is declared using the const keyword, making it a constant array. The attempt to modify the array by pushing a new element will result in a TypeError, as a constant array cannot be reassigned or modified after its initial declaration.

1.Constant Array Declaration:

​              const colors = ["Red", "Green", "Blue"];

2.Attempting to Modify the Array (Will Result in Error):

​​// colors.push("Yellow");

3.Displaying the Constant Array:

​​console.log("Colors Array: " + JSON.stringify(colors));

This example illustrates the use of the const keyword to create a constant array and the resulting error when attempting to modify it.

JS Dates

In JavaScript, the Date object is used to work with dates and times. It provides methods for creating, formatting, and manipulating dates.

1.Date Object Creation:

The Date object is created using the new Date() constructor. It can be created without any arguments, in which case it represents the current date and time, or with various arguments specifying a specific date and time.

2.Epoch Time:

Internally, dates are represented as the number of milliseconds since the "epoch," which is January 1, 1970, 00:00:00 UTC. This point in time is often referred to as

"Unix epoch" or "epoch time."

3.Date Components:

A Date object represents a specific point in time and includes components such as year, month, day, hour, minute, second, and millisecond. These components can be accessed and modified using various methods.

4.UTC vs. Local Time:

The Date object provides methods like getUTC...() and setUTC...() to work with Coordinated Universal Time (UTC) instead of local time. This is important when dealing with time zone differences.

5.Date Parsing:

Dates can be parsed from strings using the Date.parse() method or by passing a date string to the Date constructor. The date string format follows a specific syntax, and parsing behavior can vary across environments.

1.Date Formatting:

The Date object provides methods like toDateString(), toLocaleDateString(), toISOString(), etc., to obtain formatted date strings based on various conventions and locales.

2.Arithmetic Operations:

Date objects can be used in arithmetic operations. Adding or subtracting milliseconds can be used to shift the date and time.

3.Comparison:

Date objects can be compared using relational operators (<, <=, >, >=). Comparison is based on the internal representation (milliseconds since epoch).

4.Leap Years:

The Date object accounts for leap years, and it correctly handles the number of days in a month, accounting for leap years when necessary.

5.Daylight Saving Time (DST):

The Date object automatically adjusts for daylight saving time changes based on the system's time zone settings.

6.Timestamps:

The getTime() method of the Date object returns the number of milliseconds since the epoch, providing a timestamp for a specific date and time.

7.Limitations:

While the Date object is versatile, it has some limitations, such as the lack of support for time zones other than the local time zone and the reliance on the system's time zone settings.

Understanding the Date object is essential for working with dates and times in JavaScript. It provides a wide range of functionality for handling various aspects of date and time, and its methods can be used to create dynamic and interactive web applications that involve time-sensitive operations.

// JavaScript Dates Example

// Current Date

let currentDate = new Date();

console.log("Current Date: " + currentDate);

// Specific Date let specificDate = new Date("2023-12-31"); console.log("Specific Date: " + specificDate);

// Creating Date with Components let dateWithComponents = new Date(2023, 11, 31, 12, 30, 0); console.log("Date with Components: " + dateWithComponents);

// Displaying Date Components

console.log("Year: " + currentDate.getFullYear());

console.log("Month: " + (currentDate.getMonth() + 1)); // Months are zero-based

console.log("Day: " + currentDate.getDate()); console.log("Hour: " + currentDate.getHours()); console.log("Minute: " + currentDate.getMinutes()); console.log("Second: " + currentDate.getSeconds());

// End of JavaScript Dates Example

In this example, JavaScript Date objects are demonstrated:

1.Current Date: ​let currentDate = new Date();

2.Specific Date:

​​let specificDate = new Date("2023-12-31");

3.Creating Date with Components:

​let dateWithComponents = new Date(2023, 11, 31, 12, 30, 0);

4.Displaying Date Components:

console.log("Year: " + currentDate.getFullYear()); console.log("Month: " + (currentDate.getMonth() + 1)); // Months are zero-based console.log("Day: " + currentDate.getDate()); console.log("Hour: " + currentDate.getHours()); console.log("Minute: " + currentDate.getMinutes()); console.log("Second: " + currentDate.getSeconds());

These examples cover creating Date objects, specifying a specific date, creating a date with individual components, and displaying various date components using JavaScript.

JS Date Formats

In JavaScript, date formats refer to the way in which dates are presented as strings. The Date object provides methods to obtain date components, and these components can be combined to create formatted date strings.

1.Basic Components:

Date components include the year, month, day, hour, minute, second, and millisecond. These components can be obtained using methods like getFullYear(), getMonth(), getDate(), getHours(), getMinutes(), getSeconds(), and getMilliseconds().

2.Common Format Specifiers:

Format specifiers are placeholders that represent date components when constructing formatted date strings.

Common specifiers include:

%Y: Four-digit year (e.g., 2022)

%M: Two-digit month (01 to 12)

%D: Two-digit day of the month (01 to 31)

%H: Two-digit hour in 24-hour format (00 to 23)

%m: Two-digit minute (00 to 59)

%S: Two-digit second (00 to 59)

%L: Milliseconds (000 to 999)

3.Locale-Specific Formats:

The toLocaleDateString() method can be used to obtain a date string based on the user's locale. It formats the date according to the conventions of the specified locale.

1.UTC Formats:

The toUTCString(), toISOString(), and related methods return date strings in Coordinated Universal Time (UTC). These methods are useful for standardized date representations.

2.Custom Formats:

Developers can create custom date formats by manually constructing strings using date components. For example, combining %Y-%M-%D might result in a string like "2022-01-15."

3.ISO 8601:

The toISOString() method returns a date string in the ISO 8601 format, which is widely used for representing dates and times in a standardized way (e.g., "2022-0115T12:30:00.000Z").

4.Locale-Specific Long and Short Formats:

The toLocaleDateString() method supports the options options argument, allowing customization of the date format based on the locale. This includes options for specifying long or short formats.

5.Relative Time:

Some libraries and functions provide relative time formats, such as "2 hours ago" or "yesterday." These formats can be generated by calculating the difference between the current date and another date.

6.Localized Day and Month Names:

The toLocaleDateString() method also supports obtaining localized day and month names, providing options for presenting the date in a more humanreadable form.

Understanding date formats is essential for creating userfriendly interfaces, logging, and any application where presenting dates in a readable and standardized manner is important. The choice of format often depends on the requirements of the application, the expected audience, and localization considerations.

// JavaScript Date Formats Example

// Current Date let currentDate = new Date();

// Formatting Date Components let formattedDate = currentDate.toDateString(); let isoDate = currentDate.toISOString(); let localeDate = currentDate.toLocaleDateString(); let localeTime = currentDate.toLocaleTimeString(); let customFormat = currentDate.toLocaleString("en-US", {   weekday: "long",   year: "numeric",   month: "long",   day: "numeric",   hour: "numeric",   minute: "numeric",   second: "numeric",   timeZoneName: "short",

});

// Displaying Formatted Dates console.log("Formatted Date: " + formattedDate); console.log("ISO Date: " + isoDate); console.log("Locale Date: " + localeDate); console.log("Locale Time: " + localeTime); console.log("Custom Format: " + customFormat); // End of JavaScript Date Formats Example

In ​this ​example, ​various ​JavaScript ​date ​formats               are demonstrated:

1.Formatting Date Components:

let formattedDate = currentDate.toDateString(); let isoDate = currentDate.toISOString(); let localeDate = currentDate.toLocaleDateString(); let localeTime = currentDate.toLocaleTimeString(); let customFormat = currentDate.toLocaleString("en-

US", { /* options */ });

2.Displaying Formatted Dates:

console.log("Formatted Date: " + formattedDate); console.log("ISO Date: " + isoDate); console.log("Locale Date: " + localeDate); console.log("Locale Time: " + localeTime); console.log("Custom Format: " + customFormat); These               examples               show               different               ways               to               format               date components in JavaScript using methods like toDateString(), toISOString(), toLocaleDateString(), toLocaleTimeString(), and toLocaleString() with customization options.

JS Date Get Methods

In JavaScript, the Date object provides various methods for retrieving individual components of a date. These methods, often prefixed with "get," allow you to obtain information about the year, month, day, hour, minute, second, and millisecond of a Date object.

1.getFullYear():

The getFullYear() method returns the four-digit year of the date.

2.getMonth():

The getMonth() method returns the month of the date as a zero-based value (0 for January, 1 for February,

etc.).

3.getDate():

​​The getDate() method returns the day of the month (1

to 31).

4.getDay():

The getDay() method returns the day of the week as a zero-based value (0 for Sunday, 1 for Monday, etc.).

1.getHours():

​The getHours() method returns the hour of the date (0 to 23).

2.getMinutes():

The getMinutes() method returns the minutes of the date (0 to 59).

3.getSeconds():

The getSeconds() method returns the seconds of the date (0 to 59). 4.getMilliseconds():

The getMilliseconds() method returns the milliseconds of the date (0 to 999).

5.getTime():

​The ​getTime() ​method ​returns ​the ​number               of milliseconds since the epoch (January 1, 1970, 00:00:00 UTC).

6.getTimezoneOffset():

The getTimezoneOffset() method returns the time zone offset in minutes between the local time and UTC. It takes into account the current date and time.

7.UTC Methods:

Additionally, there are UTC versions of these methods, such as getUTCFullYear(), getUTCMonth(), getUTCDate(), and so on. These methods return components in Coordinated Universal Time (UTC).

8.Leap Year Check:

​While there isn't a specific "getLeapYear()" method, you can determine if a year is a leap year by checking if getMonth() returns 1 (February) with getDate() set to 29. These               "get"               methods               are               useful               for               retrieving               specific components of a date when working with the Date object in JavaScript. They allow developers to access and manipulate individual parts of a date as needed for various applications, such as date formatting, calculations, or displaying information in user interfaces.

// JavaScript Date Get Methods Example

// Create a Date Object let currentDate = new Date();

// Get Methods for Date let year = currentDate.getFullYear();

let month = currentDate.getMonth(); // Month is zero-based (0-

11)

let day = currentDate.getDate(); let hours = currentDate.getHours(); let minutes = currentDate.getMinutes(); let seconds = currentDate.getSeconds(); let milliseconds = currentDate.getMilliseconds();

let dayOfWeek = currentDate.getDay(); // Day of the week (0-6, 0 is Sunday)

// Display Results of Get Methods console.log("Current Date: " + currentDate); console.log("Year: " + year); console.log("Month: " + month); console.log("Day: " + day); console.log("Hours: " + hours); console.log("Minutes: " + minutes); console.log("Seconds: " + seconds); console.log("Milliseconds: " + milliseconds); console.log("Day of Week: " + dayOfWeek);

// End of JavaScript Date Get Methods Example

In this example, JavaScript Date object get methods are demonstrated:

1.Creating a Date Object: let currentDate = new Date();

2.Get Methods for Date:

let year = currentDate.getFullYear(); let month = currentDate.getMonth(); let day = currentDate.getDate(); let hours = currentDate.getHours(); let minutes = currentDate.getMinutes(); let seconds = currentDate.getSeconds(); let milliseconds = currentDate.getMilliseconds(); let dayOfWeek = currentDate.getDay();

3.Displaying Results of Get Methods: console.log("Current Date: " + currentDate); console.log("Year: " + year); console.log("Month: " + month); console.log("Day: " + day); console.log("Hours: " + hours); console.log("Minutes: " + minutes); console.log("Seconds: " + seconds); console.log("Milliseconds: " + milliseconds); console.log("Day of Week: " + dayOfWeek);

These examples showcase various get methods available for extracting different components of a Date object, such as year, month, day, hours, minutes, seconds, milliseconds, and day of the week.

JS Date Set Methods

In JavaScript, the Date object provides various methods for setting individual components of a date. These methods, often prefixed with "set," allow you to modify the year, month, day, hour, minute, second, and millisecond of a Date object.

1.setFullYear(year[, month[, day]]):

The setFullYear() method sets the year of the date. Optionally, you can also specify the month (0 to 11) and the day of the month (1 to 31).

2.setMonth(month[, day]):

The setMonth() method sets the month of the date. Optionally, you can also specify the day of the month (1 to 31).

3.setDate(day):

​​The setDate() method sets the day of the month (1 to

31).

4.setHours(hour[, min[, sec[, ms]]]):

The setHours() method sets the hour of the date. Optionally, you can also specify the minutes, seconds, and milliseconds.

5.setMinutes(min[, sec[, ms]]):

The setMinutes() method sets the minutes of the date. Optionally, you can also specify the seconds and milliseconds.

1.setSeconds(sec[, ms]):

The setSeconds() method sets the seconds of the date. Optionally, you can also specify the milliseconds.

2.setMilliseconds(ms):

The setMilliseconds() method sets the milliseconds of the date.

3.setTime(milliseconds):

The setTime() method sets the entire date based on the number of milliseconds since the epoch (January 1, 1970, 00:00:00 UTC).

4.UTC Methods:

There are also UTC versions of these methods, such as setUTCFullYear(), setUTCMonth(), setUTCDate(), etc. These methods set components in Coordinated

Universal Time (UTC).

5.Leap Year Adjustment:

When setting the month and day, JavaScript automatically adjusts for leap years. For example, if you set the month to February and the day to 30, JavaScript will adjust it to March 2nd.

6.Overflow Handling:

If the values provided to the set methods are out of range (e.g., month greater than 11), JavaScript automatically adjusts them. For example, setting the month to 13 will increment the year.

These "set" methods are useful for modifying specific components of a Date object when working with dates in JavaScript. They allow developers to adjust individual parts of a date as needed for various applications, such as date calculations, user interactions, or updating date values in a database.

// JavaScript Date Set Methods Example

// Create a Date Object let currentDate = new Date();

// Set Methods for Date currentDate.setFullYear(2022); currentDate.setMonth(11); // Month is zero-based (0-11) currentDate.setDate(25); currentDate.setHours(18); currentDate.setMinutes(30); currentDate.setSeconds(45); currentDate.setMilliseconds(500);

// Display Updated Date console.log("Updated Date: " + currentDate);

// End of JavaScript Date Set Methods Example

In this example, JavaScript Date object set methods are demonstrated:

1.Creating a Date Object: ​let currentDate = new Date();

2.Set Methods for Date:

currentDate.setFullYear(2022); currentDate.setMonth(11); currentDate.setDate(25); currentDate.setHours(18); currentDate.setMinutes(30); currentDate.setSeconds(45); currentDate.setMilliseconds(500);

3.Displaying Updated Date:

​              console.log("Updated Date: " + currentDate);

These examples demonstrate how to use various set methods to update specific components of a Date object, such as year, month, day, hours, minutes, seconds, and milliseconds.

JS Math

In JavaScript, the Math object provides a set of built-in mathematical methods for performing common mathematical operations. These methods are part of the core JavaScript language and can be used without the need for additional libraries.

1.Constants:

The Math object includes several mathematical constants, such as Math.PI (the ratio of the circumference of a circle to its diameter, approximately 3.14159) and Math.E (Euler's number, approximately 2.71828).

2.Basic Arithmetic Operations:

​Math provides methods for basic arithmetic operations, including:

Math.abs(x): Returns the absolute value of a number x. Math.ceil(x): Rounds a number x up to the nearest integer.

Math.floor(x): Rounds a number x down to the nearest integer.

Math.round(x): Rounds a number x to the nearest integer. Math.max(x, y, ...): Returns the largest of zero or more numbers.

Math.min(x, y, ...): Returns the smallest of zero or more numbers.

3.Exponential and Logarithmic Functions:

Math provides methods for exponential and logarithmic functions, including:

Math.pow(x, y): Returns the value of x raised to the power of y.

Math.sqrt(x): Returns the square root of x.

Math.exp(x): Returns Euler's number raised to the power of x.

Math.log(x): Returns the natural logarithm (base e) of x.

Math.log10(x): Returns the base 10 logarithm of x.

1.Trigonometric Functions:

Math provides methods for trigonometric functions, including:

Math.sin(x): Returns the sine of an angle x (in radians).

Math.cos(x): Returns the cosine of an angle x (in radians). Math.tan(x): Returns the tangent of an angle x (in radians).

Math.asin(x): Returns the arcsine (inverse sine) of x.

Math.acos(x): Returns the arccosine (inverse cosine) of x. Math.atan(x): Returns the arctangent (inverse tangent) of x.

Math.atan2(y, x): Returns the arctangent of the quotient of its arguments.

2.Random Number Generation:

​Math provides methods for generating random numbers, including:

Math.random(): Returns a pseudo-random number between 0 (inclusive) and 1 (exclusive).

3.Rounding and Precision:

Math provides methods for rounding and handling precision: Math.round(), Math.floor(), and Math.ceil() are often used for rounding numbers to integers.

Precision can be controlled using techniques such as multiplying and dividing by powers of 10.

4.Angular Unit Conversion:

​Math includes methods for converting between degrees and radians:

Math.degrees(x): Converts radians to degrees.

Math.radians(x): Converts degrees to radians.

The Math object is a versatile tool for performing mathematical operations in JavaScript. It provides a set of functions commonly used in scientific and engineering calculations, as well as basic arithmetic and rounding operations. Understanding the capabilities of the Math object is essential for working with numbers in a JavaScript application.

// JavaScript Math Object Example

// Math Constants let piValue = Math.PI; let eulerNumber = Math.E;

// Math Methods

let absoluteValue = Math.abs(-5); let squareRoot = Math.sqrt(25); let power = Math.pow(2, 3); let roundedNumber = Math.round(3.7);

let ceilValue = Math.ceil(4.2); let floorValue = Math.floor(4.8); let randomValue = Math.random(); // Generates a random decimal between 0 and 1

// Display Math Constants and Results console.log("Pi Value: " + piValue); console.log("Euler's Number: " + eulerNumber);

// Display Math Methods Results console.log("Absolute Value: " + absoluteValue); console.log("Square Root of 25: " + squareRoot); console.log("2 to the power of 3: " + power); console.log("Rounded Number: " + roundedNumber); console.log("Ceil Value of 4.2: " + ceilValue); console.log("Floor Value of 4.8: " + floorValue); console.log("Random Decimal: " + randomValue);

// End of JavaScript Math Object Example

In this example, the JavaScript Math object is demonstrated with constants and methods:

1.Math Constants:

let piValue = Math.PI; let eulerNumber = Math.E;

2.Math Methods:

let absoluteValue = Math.abs(-5); let squareRoot = Math.sqrt(25); let power = Math.pow(2, 3); let roundedNumber = Math.round(3.7);

let ceilValue = Math.ceil(4.2); let floorValue = Math.floor(4.8); let randomValue = Math.random(); (Generates a random decimal between 0 and 1)

3.Displaying Math Constants and Results:

console.log("Pi Value: " + piValue); console.log("Euler's Number: " + eulerNumber);

4.Displaying Math Methods Results:

console.log("Absolute Value: " + absoluteValue); console.log("Square Root of 25: " + squareRoot); console.log("2 to the power of 3: " + power); console.log("Rounded Number: " + roundedNumber);

console.log("Ceil Value of 4.2: " + ceilValue); console.log("Floor Value of 4.8: " + floorValue); console.log("Random Decimal: " + randomValue);

These examples illustrate the use of various constants and methods provided by the Math object in JavaScript.

JS Random

In JavaScript, the Math.random() method is used to generate pseudo-random floating-point numbers between 0 (inclusive) and 1 (exclusive).

1.Pseudo-Random Numbers:

The numbers generated by Math.random() are considered pseudo-random because they are determined by an algorithm and are not truly random. However, for many practical purposes, they exhibit randomness and are suitable for various applications.

2.Range:

The values returned by Math.random() fall within the range [0, 1), meaning that 0 is included, but 1 is not. The generated numbers can be any decimal value between 0 (inclusive) and 1 (exclusive).

3.Uniform Distribution:

The distribution of values from Math.random() is uniform, meaning that each possible value within the range has an equal chance of being generated. There is no bias toward certain values.

4.Scaling and Shifting:

The range and starting point of the random numbers can be adjusted by scaling and shifting the result. For example, to generate random integers within a specific range, you can use Math.floor(Math.random() * (max min + 1)) + min.

1.Seeding:

JavaScript's Math.random() doesn't support seeding (providing an initial value to the random number generator). If more control over the randomness is needed, external libraries or custom algorithms may be used.

2.Usage in Applications:

Math.random() is commonly used in applications that require randomness, such as games, simulations, or any scenario where unpredictable values are needed.

3.Deterministic Behavior:

While the values are pseudo-random, the sequence of numbers generated by Math.random() is deterministic and can be reproduced if the same seed is used. However, JavaScript does not provide a built-in mechanism for seeding the random number generator.

4.Cryptographic Use:

Math.random() is not suitable for cryptographic purposes where true randomness and unpredictability are essential. For cryptographic applications, the crypto API or external libraries are recommended.

5.Mathematics Behind the Scenes:

The specific algorithm used by Math.random() is implementation-dependent and not specified by the ECMAScript standard. Different JavaScript engines may use different algorithms.

Understanding how to use and manipulate random numbers is important for a variety of programming tasks. While Math.random() is a simple and convenient method for basic randomness, more sophisticated applications may require additional considerations and, in some cases, the use of external libraries or APIs.

// JavaScript Random Number Example

// Generate a Random Number between 1 and 10 let randomNumber = Math.floor(Math.random() * 10) + 1;

// Display Random Number

console.log("Random Number between 1 and 10: " + randomNumber);

// End of JavaScript Random Number Example

In this example, a JavaScript random number is generated within a specific range:

1.Generate a Random Number between 1 and 10:

​              let randomNumber = Math.floor(Math.random() * 10) + 1;

2.Display Random Number: console.log("Random Number between 1 and 10: " + randomNumber);

This example demonstrates how to use the Math.random() method to generate a random decimal between 0 (inclusive) and 1 (exclusive), then scale and shift the result to get a random integer within a specific range.

JS Booleans

In JavaScript, a boolean is a data type that represents one of two possible values: true or false. Booleans are often used in programming for making decisions, controlling the flow of a program, and evaluating conditions.

1.Two Possible Values:

The boolean data type has only two possible values: true and false. These values represent the binary logic of true or false, on or off, yes or no.

2.Logical Operations:

Booleans are fundamental to logical operations. Conditions, comparisons, and boolean operators (such as &&, ||, and !) return boolean values.

3.Conditional Statements:

Booleans are commonly used in conditional statements, such as if, else if, and else blocks. The code inside these blocks is executed based on whether a condition evaluates to true or false.

4.Comparison Operators:

Comparison operators, like ===, !==, <, >, <=, and >=, compare values and return a boolean result. They are often used to make decisions based on the relationship between values.

5.Logical Operators:

Logical operators (&&, ||, !) are used to combine or negate boolean values. They are essential for creating complex conditions and controlling the flow of a program.

1.Boolean Functions:

Functions can return boolean values based on certain conditions. For example, a function might check if a number is even and return true or false accordingly.

2.Truthy and Falsy Values:

In JavaScript, values are categorized as either "truthy" or "falsy" when used in boolean contexts. All values are considered truthy except for a few special cases like false, 0, "" (empty string), null, undefined, and NaN, which are falsy.

3.Boolean Objects:

While the boolean data type has only two primitive values (true and false), there is also a Boolean object wrapper in JavaScript that can be used to create boolean objects. However, it's rarely used in practice.

4.Default Boolean Values:

In some contexts, a variable might be implicitly converted to a boolean value. For example, in an if statement, the condition is implicitly converted to a boolean, and non-boolean values are treated as truthy or falsy.

Understanding booleans is fundamental to writing effective and logical code in JavaScript. Booleans are at the core of decision-making and control flow, and they play a crucial role in creating conditions and determining the behavior of a program based on different scenarios.

// JavaScript Booleans Example

// Boolean Declaration let isTrue = true; let isFalse = false;

// Boolean Operations let resultAnd = true && false; let resultOr = true || false; let resultNot = !true;

// Display Boolean Values and Results console.log("True Boolean: " + isTrue); console.log("False Boolean: " + isFalse);

console.log("Result of AND Operation: " + resultAnd); console.log("Result of OR Operation: " + resultOr); console.log("Result of NOT Operation: " + resultNot);

// End of JavaScript Booleans Example

In this example, JavaScript booleans are demonstrated:

1.Boolean Declaration: let isTrue = true; let isFalse = false;

2.Boolean Operations:

​              Logical AND (&&), Logical OR (||), Logical NOT (!).

3.Display Boolean Values and Results: console.log("True Boolean: " + isTrue); console.log("False Boolean: " + isFalse); console.log("Result of AND Operation: " + resultAnd); console.log("Result of OR Operation: " + resultOr); console.log("Result of NOT Operation: " + resultNot); This example covers basic operations with boolean values, including declaration, logical AND, logical OR, and logical NOT.

JS Comparisons

In JavaScript, comparisons are fundamental operations that allow you to compare values and make decisions based on their relationships.

1.Equality Operators:

​The equality operators are used to compare values for equality:

== (loose equality): Checks if values are equal after type coercion. It may convert types before making the comparison.

=== (strict equality): Checks if values are equal without type coercion. It requires both the value and the type to be the same.

2.Inequality Operators:

The inequality operators are used to check if values are not equal:

!= (loose inequality): Checks if values are not equal after type coercion.

!== (strict inequality): Checks if values are not equal without type coercion.

3.Relational Operators:

Relational operators are used to compare the numerical values of two expressions:

<: Less than

>: Greater than

<=: Less than or equal to >=: Greater than or equal to

4.Truthy and Falsy Values:

In boolean contexts, values are implicitly converted to boolean values. All values are considered truthy except for a few special cases like false, 0, "" (empty string), null, undefined, and NaN, which are falsy.

1.String Comparisons:

When comparing strings, JavaScript uses lexicographical (dictionary) order. It compares individual characters based on their Unicode values.

2.Logical Operators:

Logical operators (&&, ||, !) are used to combine and manipulate boolean values. They are often used in conjunction with comparisons to create complex conditions.

3.Chaining Comparisons:

You can chain multiple comparisons using logical operators to create compound conditions. For example, a > b && b > c checks if a is greater than b and b is greater than c.

4.Implicit Type Coercion:

In some cases, JavaScript performs implicit type coercion when comparing values of different types. For example, when using the loose equality operator (==), the values are coerced to a common type before the comparison.

5.NaN and isNaN():

NaN (Not a Number) is a special value representing the result of an invalid mathematical operation. The isNaN() function checks if a value is NaN.

6.Object Comparisons:

When comparing objects, the equality operators (== and ===) compare references, not the content of the objects. Two objects are considered equal only if they reference the same underlying object.

Understanding how comparisons work in JavaScript is crucial for creating conditions and making decisions in your code. Whether you're comparing numbers, strings, or other types of values, having a solid understanding of JavaScript's comparison operators is essential for writing reliable and logical code.

// JavaScript Comparisons Example

// Numeric Comparisons

let isEqualNumeric = 5 == "5"; // true (loose equality) let isStrictEqualNumeric = 5 === "5"; // false (strict equality) let isNotEqualNumeric = 10 != "10"; // false (loose inequality) let isNotStrictEqualNumeric = 10 !== "10"; // true (strict inequality) let isGreater = 8 > 5; // true let isLess = 3 < 7; // true let isGreaterOrEqual = 5 >= 5; // true let isLessOrEqual = 4 <= 3; // false

// String Comparisons

let isEqualString = "hello" == "world"; // false let isNotEqualString = "apple" != "orange"; // true let isLexicographicallyGreater = "apple" > "banana"; // false let isLexicographicallyLess = "orange" < "pear"; // true

// Boolean Comparisons

let isEqualBoolean = true == false; // false let isNotEqualBoolean = true != false; // true

// Display Comparison Results console.log("Numeric Comparisons:"); console.log("Equal (Loose): " + isEqualNumeric); console.log("Equal (Strict): " + isStrictEqualNumeric); console.log("Not Equal (Loose): " + isNotEqualNumeric); console.log("Not Equal (Strict): " + isNotStrictEqualNumeric); console.log("Greater: " + isGreater); console.log("Less: " + isLess);

console.log("Greater or Equal: " + isGreaterOrEqual); console.log("Less or Equal: " + isLessOrEqual);

console.log("\nString Comparisons:"); console.log("Equal: " + isEqualString); console.log("Not Equal: " + isNotEqualString); console.log("Lexicographically Greater: " + isLexicographicallyGreater); console.log("Lexicographically Less: " + isLexicographicallyLess);

console.log("\nBoolean Comparisons:"); console.log("Equal: " + isEqualBoolean); console.log("Not Equal: " + isNotEqualBoolean); // End of JavaScript Comparisons Example

In this example, various JavaScript comparison operators are demonstrated:

1.Numeric Comparisons:

Equal (==, ===), Not Equal (!=, !==), Greater (>), Less (<), Greater or Equal (>=), Less or Equal (<=).

2.String Comparisons:

Equal (==), Not Equal (!=), Lexicographically Greater (>), Lexicographically Less (<).

3.Boolean Comparisons:

​              Equal (==), Not Equal (!=).

4.Display Comparison Results:

Results of the numeric, string, and boolean comparisons are displayed using console.log.

This example illustrates how to use various comparison operators in JavaScript for numeric, string, and boolean values.

JS If Else

In JavaScript, the if statement and the else statement are control flow structures that allow you to execute different blocks of code based on a specified condition.

1.if Statement:

The if statement is used to conditionally execute a block of code based on a specified condition. If the condition evaluates to true, the code inside the if block is executed. If the condition is false, the code inside the if block is skipped.

2.else Statement:

The else statement is used in conjunction with the if statement to provide an alternative block of code to be executed when the if condition is false. If the if condition is true, the code inside the else block is skipped. If the if condition is false, the code inside the else block is executed.

3.Exclusive Execution:

Either the code inside the if block or the code inside the else block is executed, but not both. This provides an exclusive choice based on the truthiness or falsiness of the condition.

1.else if Statement (Optional):

To handle multiple conditions, you can use the else if statement. It allows you to check additional conditions if the previous if or else if conditions are false. The code inside the first matching condition block is executed.

2.Nested if Statements:

You can nest if statements inside each other to handle more complex conditions. The inner if statements are only evaluated if the conditions of the outer if statements are true.

3.Order of Evaluation:

Conditions are evaluated from top to bottom. Once a condition is true, the corresponding block of code is executed, and subsequent conditions are not evaluated.

4.Truthy and Falsy Values:

The condition inside an if statement is evaluated based on whether it is truthy or falsy. Truthy values evaluate to true, and falsy values evaluate to false.

5.Ternary Operator (Alternative):

In some cases, a simple if and else statement can be replaced by the ternary operator (? :). It provides a more concise way to express conditional statements.

Understanding how to use if and else statements is crucial for creating decision-making structures in your JavaScript code. These statements allow you to control the flow of your program based on conditions, enabling you to create dynamic and responsive applications.

// JavaScript If-Else Example

// Numeric Comparison let num1 = 10; let num2 = 5;

// If-Else Statement if (num1 > num2) {

console.log(num1 + " is greater than " + num2);

} else {

console.log(num1 + " is not greater than " + num2); }

// String Comparison let string1 = "apple"; let string2 = "orange";

// If-Else Statement for Strings if (string1 === string2) {     console.log(string1 + " is equal to " + string2);

} else {

console.log(string1 + " is not equal to " + string2); }

// Boolean Comparison let booleanValue = true;

// If-Else Statement for Boolean if (booleanValue) {

console.log("The boolean value is true.");

} else {

console.log("The boolean value is false."); }

// End of JavaScript If-Else Example

In ​this ​example, ​JavaScript ​if-else ​statements               are demonstrated:

1.Numeric Comparison:

​              If-Else statement to check if num1 is greater than num2.

2.String Comparison:

​              If-Else statement to check if string1 is equal to string2.

3.Boolean Comparison:

​If-Else ​statement ​to ​check ​the ​truthiness ​of booleanValue.

4.Displaying Results:

​Results of each if-else statement are displayed using console.log.

This example shows how to use the if-else statement to conditionally execute code based on the evaluation of a comparison expression.

JS Switch

In JavaScript, the switch statement is a control flow statement that allows a program to evaluate an expression and execute different blocks of code based on the value of that expression.

1.Expression Evaluation:

The switch statement begins with an expression (often a variable or an expression) inside the parentheses. The value of this expression is then evaluated.

2.Case Blocks:

Following the switch statement, there are one or more case blocks. Each case block contains a specific value or a set of values that the evaluated expression is compared against.

3.Matching Cases:

When the evaluated expression matches the value specified in a case block, the code inside that case block is executed. If there is no match, the program moves to the next case block.

4.break Statement:

After the code in a case block is executed, the break statement is used to exit the switch statement. This prevents the program from falling through to the next case block.

1.default Case (Optional):

The default case is optional and is used to specify the code that should be executed if none of the case blocks match the evaluated expression. It is similar to the "else" statement in an if-else structure.

2.Fall-Through Behavior:

Unlike some other programming languages, JavaScript's switch statement has fall-through behavior. If a case block doesn't contain a break statement, execution will "fall through" to the next case block, regardless of whether the condition is met.

3.Strict Equality Comparison:

The comparisons in a switch statement are strict (using ===). This means that not only the values but also the types must match for a case block to be executed.

4.Multiple Cases:

You can group multiple values together in a single case block by separating them with a comma. If any of the values match the evaluated expression, the code inside that case block will be executed.

The switch statement is particularly useful when there are multiple conditions to check against a single variable or expression. It provides a cleaner alternative to using multiple ifelse statements in situations where the code execution depends on the value of a single variable.

// JavaScript Switch Statement Example

// Day of the Week let day = "Monday"; let dayType;

// Switch Statement switch (day) {     case "Monday":     case "Tuesday":     case "Wednesday":     case "Thursday":     case "Friday":

dayType = "Weekday";

break;     case "Saturday":     case "Sunday":

dayType = "Weekend";

break;     default:

dayType = "Invalid Day"; }

// Display Result console.log("Day: " + day); console.log("Day Type: " + dayType);

// End of JavaScript Switch Statement Example

In this example, a JavaScript switch statement is demonstrated:

1.Day of the Week:

​The variable day represents a day of the week (e.g., "Monday").

2.Switch Statement:

The switch statement checks the value of day and assigns a corresponding dayType based on whether it is a weekday, weekend, or an invalid day.

3.Displaying Result:

The result, including the day and its type, is displayed using console.log.

This example showcases how to use the switch statement for handling multiple cases based on the value of a variable.

JS Loop For

In JavaScript, the for loop is a control flow statement that allows you to repeatedly execute a block of code for a specified number of times.

1.Initialization:

The for loop begins with an initialization statement. This statement is typically used to declare and initialize a loop control variable, which is often a counter.

2.Condition:

After the initialization statement, there is a condition. The loop continues to execute as long as the condition evaluates to true. If the condition becomes false, the loop terminates, and the program moves on to the next statement after the loop.

3.Iteration Expression:

Following the condition, there is an iteration expression. This expression is evaluated after each iteration of the loop and is usually used to update the loop control variable. It allows you to control how the loop progresses.

4.Code Block:

Inside the for loop, there is a block of code enclosed in curly braces {}. This block contains the statements that are executed in each iteration of the loop.

1.Loop Control Variable:

The loop control variable is often used to keep track of the current iteration. It is modified in the iteration expression to control when the loop should terminate.

2.Scope:

The loop control variable is scoped to the for loop, which means it is only accessible within the loop block. This helps prevent unintended side effects outside the loop.

3.Initialization Once:

The initialization statement is executed only once at the beginning of the loop. It initializes the loop control variable before the loop starts.

4.Condition Checked Before Each Iteration:

Before each iteration, the condition is checked. If the condition is true, the code inside the loop block is executed. If it is false, the loop terminates, and the program moves to the next statement after the loop.

5.Iteration Expression After Each Iteration:

After each iteration, the iteration expression is evaluated. This step allows you to modify the loop control variable, potentially affecting the loop's behavior in subsequent iterations.

The for loop is a versatile and widely used construct for implementing iteration in JavaScript. It provides a concise and organized way to perform repetitive tasks, especially when the number of iterations is known or can be determined based on a condition.

// JavaScript For Loop Example

// Iterate from 1 to 5

console.log("Counting from 1 to 5:");

for (let i = 1; i <= 5; i++) {     console.log(i); }

// Iterate through an array

let fruits = ["Apple", "Banana", "Orange", "Mango"]; console.log("\nFruits:"); for (let j = 0; j < fruits.length; j++) {     console.log(fruits[j]); }

// End of JavaScript For Loop Example

In this example, a JavaScript for loop is demonstrated:

1.Iterate from 1 to 5:

A simple loop that counts from 1 to 5 using the loop variable i.

2.Iterate through an array:

​The loop iterates through an array (fruits) and prints each element.

3.Displaying Results:

The results of both loops are displayed using console.log. This example illustrates how to use a for loop to iterate over a range of values and through the elements of an array.

JS Loop For In

In JavaScript, the for...in loop is a specialized loop designed for iterating over the enumerable properties of an object.

1.Iterating over Properties:

The primary purpose of the for...in loop is to iterate over the enumerable properties of an object. It is particularly useful for objects where the keys are strings.

2.Object Enumeration:

The for...in loop iterates over the object's own and inherited enumerable properties. It does not include non-enumerable properties or properties defined on the object's prototype chain.

3.Syntax:

The syntax of the for...in loop is for (variable in object) { ... }, where variable is a variable that will be assigned the property key on each iteration, and object is the object being iterated.

4.Variable Assignment:

On each iteration, the for...in loop assigns the key of the current property to the specified variable. You can then use this variable to access the corresponding property value.

1.Iterating Over Object Properties:

The for...in loop is commonly used with objects (not arrays) to iterate over their properties. However, it's important to note that the order of iteration is not guaranteed, and it may vary between different

JavaScript engines.

2.Enumeration Order:

The order of enumeration is based on the order in which properties were added to the object, but this is not guaranteed, and it may vary between different

JavaScript engines.

3.Property Attributes:

The for...in loop only iterates over properties with the enumerable attribute set to true. Properties created with certain methods, like Object.defineProperty() with enumerable: false, will not be included.

4.Arrays and Array-Like Objects:

While for...in can be used with arrays, it's generally not recommended because it iterates over keys (including array indices) rather than values. The for...of loop is often preferred for arrays.

5.Avoid Modifying Object During Iteration:

Modifying the object being iterated over inside a for...in loop can lead to unexpected behavior. It's generally a good practice to avoid modifying the object's structure during iteration.

The for...in loop is suitable for scenarios where you need to inspect or manipulate the properties of an object. However, for iterating over values in arrays or array-like objects, the for...of loop is often preferred for its more straightforward syntax and behavior.

// JavaScript For...In Loop Example

// Object with Key-Value Pairs let person = {     name: "John",     age: 30,

city: "New York"

};

// For...In Loop to Iterate Over Object Properties console.log("Person Details:"); for (let key in person) {

console.log(key + ": " + person[key]); }

// Array of Colors

let colors = ["Red", "Green", "Blue"];

// For...In Loop to Iterate Over Array Indices console.log("\nColors:"); for (let index in colors) {

console.log(index + ": " + colors[index]); }

// End of JavaScript For...In Loop Example

In this example, a JavaScript for...in loop is demonstrated:

1.Object with Key-Value Pairs:

The object person contains key-value pairs representing a person's details.

2.For...In Loop to Iterate Over Object Properties:

The for...in loop iterates over the keys (properties) of the person object and prints each key-value pair.

3.Array of Colors:

​​The array colors contains color names.

4.For...In Loop to Iterate Over Array Indices:

The for...in loop iterates over the indices of the colors array and prints each index-color pair.

5.Displaying Results:

​The results of both for...in loops are displayed using console.log.

This example illustrates how to use the for...in loop to iterate over the properties of an object and the indices of an array.

JS Loop For Of

In JavaScript, the for...of loop is a modern iteration statement introduced in ECMAScript 2015 (ES6). It provides a concise and expressive way to iterate over the values of iterable objects, such as arrays, strings, maps, sets, and more.

1.Iterable Objects:

The for...of loop is specifically designed for iterating over iterable objects. Iterable objects are objects that implement the iterable protocol, allowing them to be looped over using the for...of loop.

2.Syntax:

The syntax of the for...of loop is for (variable of iterable) { ... }, where variable is a variable that will be assigned the value of each element in the iterable on each iteration, and iterable is the object being iterated.

3.Array Iteration:

One of the most common use cases for for...of is iterating over the elements of an array. The loop automatically retrieves the values, simplifying the code compared to using a traditional for loop with array indices.

4.String Iteration:

Strings are also iterable objects in JavaScript, and the for...of loop can be used to iterate over the characters of a string.

1.Iterable Objects:

Besides arrays and strings, other iterable objects like maps, sets, and certain built-in objects can be iterated using for...of. Custom objects can also be made iterable by implementing the iterable protocol.

2.No Need for Index Variable:

Unlike traditional for loops, the for...of loop eliminates the need for an index variable. It directly provides the values of the iterable, making the code more readable and concise.

3.Does Not Iterate Over Object Properties:

The for...of loop is specifically designed for iterating over iterable values and does not iterate over the properties of an object. To iterate over the properties of an object, the for...in loop is more appropriate.

4.Break and Continue:

The for...of loop supports the break and continue statements, allowing you to control the flow of the loop similarly to traditional for loops.

5.Generator Functions:

for...of works seamlessly with generator functions, allowing for the iteration of values produced by a generator.

6.Support for Custom Iterators:

Objects can implement a custom iterator using the iterable protocol, which involves defining a Symbol.iterator method. This enables custom objects to be used with the for...of loop.

The for...of loop is a powerful and convenient tool for iterating over the values of iterable objects. It enhances code readability and is especially beneficial when dealing with arrays and other iterable data structures in modern JavaScript development.

// JavaScript For...Of Loop Example

// Array of Fruits

let fruits = ["Apple", "Banana", "Orange", "Mango"];

// For...Of Loop to Iterate Over Array Elements console.log("Fruits:"); for (let fruit of fruits) {     console.log(fruit); }

// String let message = "Hello";

// For...Of Loop to Iterate Over String Characters console.log("\nCharacters in the String:"); for (let char of message) {     console.log(char); }

// Map

let population = new Map([     ["New York", 8400000],

["Los Angeles", 3990000],

["Chicago", 2716000]

]);

// For...Of Loop to Iterate Over Map Entries console.log("\nPopulation:"); for (let [city, pop] of population) {     console.log(city + ": " + pop); }

// End of JavaScript For...Of Loop Example

In this example, a JavaScript for...of loop is demonstrated:

1.Array of Fruits:

The array fruits contains fruit names.

2.For...Of Loop to Iterate Over Array Elements:

The for...of loop iterates over the elements of the fruits array and prints each fruit.

3.String:

The variable message is a string.

4.For...Of Loop to Iterate Over String Characters:

The for...of loop iterates over the characters of the string and prints each character.

5.Map:

The population map contains city-population pairs.

6.For...Of Loop to Iterate Over Map Entries:

The for...of loop iterates over the entries of the map and prints each city-population pair.

7.Displaying Results:

​The results of each for...of loop are displayed using console.log.

This example illustrates how to use the for...of loop to iterate over elements in an array, characters in a string, and entries in a Map.

JS Loop While

In JavaScript, the while loop is a control flow statement that allows you to repeatedly execute a block of code as long as a specified condition evaluates to true.

1.Condition:

The while loop starts with a condition that is evaluated before each iteration. If the condition is true, the code inside the loop block is executed; if the condition is false, the loop terminates, and the program continues with the next statement after the loop.

2.Initialization Outside the Loop:

Unlike the for loop, the while loop does not have an initialization statement within the loop syntax.

Initialization is typically done before the loop.

3.Loop Block:

Inside the while loop, there is a block of code enclosed in curly braces {}. This block contains the statements that are executed in each iteration of the loop.

4.Condition Evaluation:

After executing the code in the loop block, the condition is re-evaluated. If the condition is still true, the loop continues to the next iteration; if it is false, the loop terminates.

5.Iteration Control:

The responsibility for updating the loop control variable or expression is typically placed within the loop block. This ensures that the condition changes over the course of the loop iterations, eventually leading to termination.

1.Dynamic Condition:

The condition in a while loop is dynamic, meaning that it can depend on various factors, including user input, data from external sources, or calculations within the loop.

2.Infinite Loop Risk:

Be cautious when using a while loop, as there is a risk of creating an infinite loop if the condition never evaluates to false. This can lead to the program running indefinitely, and it may become unresponsive.

3.Pre-check Condition:

The condition is checked before the loop block is executed. If the condition is initially false, the loop block is skipped entirely.

4.Use Cases:

while loops are often used when the number of iterations is not known beforehand and depends on runtime conditions. They are suitable for situations where the loop termination is determined by external factors.

5.Entry Control Loop:

The while loop is an entry control loop, meaning that the condition is checked before entering the loop block. If the condition is initially false, the loop block is skipped entirely.

The while loop provides flexibility for scenarios where the number of iterations is not fixed and depends on runtime conditions. It is a fundamental looping construct in JavaScript, and understanding its use cases and behavior is essential for effective programming.

// JavaScript While Loop Example

// Count from 1 to 5 with a While Loop

let count = 1;

console.log("Counting from 1 to 5 with a While Loop:"); while (count <= 5) {     console.log(count);     count++; }

// Sum of Numbers up to 10 with a While Loop let sum = 0; let number = 1;

console.log("\nSum of Numbers up to 10 with a While Loop:"); while (number <= 10) {     sum += number;

number++;

}

console.log("Sum: " + sum);

// End of JavaScript While Loop Example

In this example, a JavaScript while loop is demonstrated:

1.Count from 1 to 5 with a While Loop:

A simple while loop that counts from 1 to 5 using the loop variable count.

2.Sum of Numbers up to 10 with a While Loop:

Another while loop that calculates the sum of numbers from 1 to 10.

3.Displaying Results:

​The results of both while loops are displayed using console.log.

This example illustrates how to use the while loop to repeatedly execute a block of code as long as a specified condition is true.

JS Break

In JavaScript, the break statement is a control flow statement used to terminate the execution of a loop prematurely.

1.Loop Termination:

The primary purpose of the break statement is to exit a loop prematurely. When the break statement is encountered within the body of a loop, it immediately terminates the loop, and control is transferred to the statement following the loop.

2.Use in Loops:

The break statement is commonly used in conjunction with loops, such as for, while, and do...while. It allows you to exit the loop based on a certain condition, even if the loop's normal exit condition hasn't been met.

3.Switch Statement:

Apart from loops, the break statement is also used in the switch statement. When a break statement is encountered within a switch case, it exits the switch block, preventing the execution of subsequent cases.

4.Nested Loops:

In nested loops, a break statement is typically used to exit the innermost loop when a specific condition is met. This allows you to control the flow of execution within nested loop structures.

1.Labeling Loops:

In JavaScript, you can label loops using a label identifier. The break statement can then be used with a label to specify which loop should be terminated when there are nested loops.

2.Loop Skipping:

In some cases, the break statement is used not only to exit a loop but also to skip the remaining iterations of the loop. This is particularly useful when a specific condition is met, and further iterations are unnecessary.

3.Avoiding Infinite Loops:

In certain situations, the break statement is used as a safety mechanism to avoid infinite loops. By incorporating a conditional check, the loop can be exited when a certain condition is met, preventing the program from running indefinitely.

4.Conditional Terminations:

The decision to use a break statement is often based on a condition that, when true, indicates that further iterations are unnecessary or undesirable. This condition might be determined by external factors, user input, or specific calculations within the loop.

5.Versatility:

The break statement provides versatility in controlling the flow of a program. It allows for the flexible termination of loops and is a crucial tool in managing program execution paths.

It's important to use the break statement judiciously to ensure that the intended logic is maintained and that the program behavior is predictable. Misuse of break statements, especially in nested loops, can lead to unexpected results and bugs.

// JavaScript Break Statement Example

// While Loop with Break Statement

let count = 1;

console.log("Counting with a While Loop and Break Statement:"); while (true) {     console.log(count);     count++;     if (count > 5) {

break;

}

}

// For Loop with Break Statement

console.log("\nCounting with a For Loop and Break Statement:"); for (let i = 1; i <= 10; i++) {

console.log(i);     if (i === 5) {

break;

}

}

// End of JavaScript Break Statement Example

In this example, the JavaScript break statement is demonstrated within while and for loops:

1.While Loop with Break Statement:

A while loop that counts using the loop variable count and breaks out of the loop when count is greater than 5.

2.For Loop with Break Statement:

A for loop that counts using the loop variable i and breaks out of the loop when i is equal to 5.

3.Displaying Results:

The results of both loops with the break statement are displayed using console.log.

This example shows how the break statement can be used to exit a loop prematurely when a certain condition is met.

JS Iterables

In JavaScript, an iterable is an object that implements the iterable protocol, allowing it to be iterated over using the for...of loop. Iterables are a fundamental concept in modern JavaScript and are commonly used with various data structures.

1.Iterable Protocol:

The iterable protocol is a set of rules that an object must follow to be considered iterable. An iterable object must have a method with the key Symbol.iterator, which returns an iterator object.

2.Symbol.iterator:

The Symbol.iterator is a symbol that serves as a key for a method on an object. When this method is called, it should return an iterator object.

3.Iterator Object:

An iterator object is an object with a next method. The next method returns an object with two properties: value (the current value in the iteration) and done (a boolean indicating whether the iteration is complete).

4.for...of Loop:

The for...of loop is a syntax in JavaScript specifically designed for iterating over iterable objects. It abstracts away the details of working with iterators, making the code more readable and concise.

5.Examples of Iterables:

Common examples of iterable objects in JavaScript include arrays, strings, maps, sets, and certain built-in objects like NodeList and arguments.

1.Arrays:

Arrays are perhaps the most commonly used iterable objects. They hold an ordered collection of values, and the for...of loop allows you to iterate over each element in the array.

2.Strings:

Strings are also iterable in JavaScript. When you iterate over a string using for...of, you get each character in the string one by one.

3.Maps and Sets:

Maps and sets are iterable data structures introduced in ECMAScript 2015 (ES6). They allow you to store keyvalue pairs (in the case of maps) or unique values (in the case of sets).

4.Custom Iterables:

Developers can create custom iterable objects by implementing the iterable protocol. This involves defining a Symbol.iterator method that returns an iterator object with a next method.

5.Iterating Once:

Iterables are typically designed to be iterated over once. Once the iterator reaches the end of the sequence, subsequent calls to next will return an object with done set to true.

6.Iterator Exhaustion:

Iterables and iterators maintain internal state to keep track of the current position in the sequence. After reaching the end, attempting to iterate further will not yield additional values.

Understanding the concept of iterables is crucial for working with modern JavaScript features like the for...of loop and for leveraging the benefits of iterable data structures. Iterables provide a unified and convenient way to work with various collections of data in JavaScript.

// JavaScript Iterables and for...of Loop Example

// Array

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

// for...of Loop to Iterate Over Array Elements console.log("Fruits:"); for (let fruit of fruits) {     console.log(fruit); }

// String let message = "Hello";

// for...of Loop to Iterate Over String Characters console.log("\nCharacters in the String:"); for (let char of message) {     console.log(char); }

// Map let population = new Map([     ["New York", 8400000],

["Los Angeles", 3990000],

["Chicago", 2716000]

]);

// for...of Loop to Iterate Over Map Entries console.log("\nPopulation:"); for (let [city, pop] of population) {     console.log(city + ": " + pop); }

// Set

let uniqueNumbers = new Set([1, 2, 3, 4, 5]);

// for...of Loop to Iterate Over Set Elements console.log("\nUnique Numbers:"); for (let number of uniqueNumbers) {     console.log(number); }

// End of JavaScript Iterables and for...of Loop Example

In this example, JavaScript iterables are demonstrated using the for...of loop:

1.Array:

The array fruits contains fruit names.

2.for...of Loop to Iterate Over Array Elements:

The for...of loop iterates over the elements of the fruits array and prints each fruit.

3.String:

The variable message is a string.

4.for...of Loop to Iterate Over String Characters:

The for...of loop iterates over the characters of the string and prints each character.

5.Map:

The population map contains city-population pairs.

6.for...of Loop to Iterate Over Map Entries:

The for...of loop iterates over the entries of the map and prints each citypopulation pair.

7.Set:

The uniqueNumbers set contains unique numbers.

8.for...of Loop to Iterate Over Set Elements:

The for...of loop iterates over the elements of the set and prints each unique number.

9.Displaying Results:

​              The results of each for...of loop are displayed using console.log.

This example illustrates how to use the for...of loop to iterate over elements in an array, characters in a string, entries in a Map, and elements in a Set.

JS Sets

In JavaScript, a Set is a built-in object that represents an unordered collection of unique values.

1.Uniqueness:

A Set can only contain unique values. It means that any given value can only appear once in a Set. If you attempt to add a duplicate value, it will be ignored.

2.No Duplicate Values:

The uniqueness of values is determined using the "SameValueZero" algorithm, which considers all values, including NaN and undefined, as distinct.

3.No Key-Value Pairs:

Unlike objects or maps, a Set doesn't store key-value pairs. It only stores individual values. The value itself is the key, and it is used to check for uniqueness.

4.No Index:

Set elements do not have indices. They are not stored in any specific order, and there is no direct way to access elements by index. However, you can iterate over the elements using the for...of loop.

5.Iterable:

Sets are iterable, meaning you can use the for...of loop, the forEach method, or the spread operator (...) to iterate over the values stored in a Set.

1.No Size Limit:

Sets can grow dynamically, and there is no predefined size limit. They can contain any number of unique values.

2.Methods for Adding and Removing Elements:

Sets provide methods like add to add new elements, delete to remove elements, and clear to remove all elements.

3.Checking for Existence:

The has method allows you to check whether a specific value exists in the Set.

4.Use Cases:

Sets are useful when you need to store a collection of unique values without the need for associated keys or when the order of elements is not important.

5.Comparison to Arrays:

While arrays are ordered and can contain duplicate values, sets are unordered and can only contain unique values. The choice between them depends on the specific requirements of your data.

6.Conversion from Array:

You can create a Set from an array using the Set constructor. The constructor automatically removes duplicate values from the array.

7.Common Set Methods:

Apart from the methods mentioned earlier, sets also have methods like size to get the number of elements, and the values method (or keys method, which is an alias) to get an iterator for the values.

Sets are a versatile data structure in JavaScript, especially when dealing with a collection of unique values. They provide efficient methods for checking existence, adding and removing elements, and are well-suited for scenarios where the order of elements is not critical.

// JavaScript Set Example

// Creating a Set

let uniqueNumbers = new Set([1, 2, 3, 4, 5]);

// Adding Elements to the Set uniqueNumbers.add(6); uniqueNumbers.add(7);

// Checking Set Size

console.log("Set Size: " + uniqueNumbers.size);

// Checking if an Element Exists in the Set

console.log("Does the Set contain 3? " + uniqueNumbers.has(3));

// Deleting an Element from the Set uniqueNumbers.delete(2);

// Iterating Over Set Elements console.log("\nSet Elements:"); for (let number of uniqueNumbers) {

console.log(number); }

// Clearing the Set uniqueNumbers.clear();

// Checking Set Size After Clearing

console.log("\nSet Size After Clearing: " + uniqueNumbers.size);

// End of JavaScript Set Example

In this example, JavaScript Set is demonstrated:

1.Creating a Set:

The uniqueNumbers set is created with initial values.

2.Adding Elements to the Set:

Elements (6 and 7) are added to the set using the add method.

3.Checking Set Size:

The size of the set is checked using the size property.

4.Checking if an Element Exists in the Set:

The has method is used to check if the set contains a specific element (3 in this case).

5.Deleting an Element from the Set:

​The delete method is used to remove an element (2) from the set.

6.Iterating Over Set Elements:

The for...of loop is used to iterate over the elements of the set.

7.Clearing the Set:

The clear method is used to remove all elements from the set.

8.Checking Set Size After Clearing:

The size of the set is checked again after clearing it.

This example demonstrates basic operations with a JavaScript Set, including creation, addition, deletion, checking size, checking for element existence, iteration, and clearing.

JS Maps

In JavaScript, a Map is a built-in object that allows you to store key-value pairs, where both the keys and the values can be of any data type.

1.Key-Value Pairs:

A Map is a collection of key-value pairs, where each key is unique. This means that you can use any data type, including objects and primitive values, as both keys and values.

2.Unordered:

Unlike objects, the order of key-value pairs in a Map is guaranteed to be the order in which they were added. Iterating over the entries in a Map will follow the insertion order.

3.Any Data Type as Key:

Unlike object keys, which are automatically converted to strings, Map keys can be of any data type, including objects and primitive values. This allows for more flexible data structuring.

4.Iterating Over Entries:

Map provides methods like entries, keys, and values for iterating over the key-value pairs, keys, and values, respectively. The for...of loop is commonly used for this purpose.

5.Dynamic Size:

A Map can grow or shrink dynamically as key-value pairs are added or removed. There is no predefined size limit.

1.No Need for String Keys:

In objects, keys are always converted to strings. In contrast, a Map allows you to use any data type as a key without automatic type conversion.

2.Equality of Keys:

Map uses the "SameValueZero" algorithm to determine the equality of keys, which considers all values, including NaN and undefined, as distinct.

3.Methods for Adding and Removing Entries:

Map provides methods like set for adding key-value pairs, get for retrieving values based on keys, delete for removing entries, and clear for removing all entries.

4.Checking for Existence:

The has method allows you to check whether a specific key exists in the Map.

5.Use Cases:

Map is useful when you need to associate arbitrary values with keys, and you want to maintain the order of insertion. It is commonly used when the keys are not known beforehand or when the keys can be of various data types.

6.Comparison to Objects:

While objects are also used for key-value pairs, Map objects provide advantages in terms of flexibility, iteration order, and key type handling.

7.Conversion from Array:

You can create a Map from an array of key-value pairs using the Map constructor. This is often convenient for initializing a Map with initial data.

Maps are a versatile data structure in JavaScript, providing a flexible way to work with key-value pairs. They are commonly used in scenarios where the order of entries is important, and keys can be of various data types.

// JavaScript Map Example

// Creating a Map let population = new Map([     ["New York", 8400000],

["Los Angeles", 3990000],

["Chicago", 2716000]

]);

// Adding Entries to the Map population.set("Houston", 2328000); population.set("Phoenix", 1827000);

// Checking Map Size

console.log("Map Size: " + population.size);

// Checking if a Key Exists in the Map

console.log("Does the Map contain 'Los Angeles'? " + population.has("Los Angeles"));

// Getting the Value for a Key

console.log("Population of 'Chicago': " + population.get("Chicago"));

// Deleting an Entry from the Map population.delete("New York");

// Iterating Over Map Entries console.log("\nMap Entries:"); for (let [city, pop] of population) {     console.log(city + ": " + pop); }

// Clearing the Map population.clear();

// Checking Map Size After Clearing

console.log("\nMap Size After Clearing: " + population.size);

// End of JavaScript Map Example

In this example, JavaScript Map is demonstrated:

1.Creating a Map:

The population map is created with initial key-value pairs.

2.Adding Entries to the Map:

Entries (Houston and Phoenix) are added to the map using the set method.

3.Checking Map Size:

The size of the map is checked using the size property.

4.Checking if a Key Exists in the Map:

The has method is used to check if the map contains a specific key ("Los Angeles" in this case).

5.Getting the Value for a Key:

The get method is used to retrieve the population value for a specific key ("Chicago" in this case).

6.Deleting an Entry from the Map:

The delete method is used to remove an entry with a specific key ("New York" in this case) from the map.

7.Iterating Over Map Entries:

The for...of loop is used to iterate over the entries of the map.

8.Clearing the Map:

The clear method is used to remove all entries from the map.

9.Checking Map Size After Clearing:

The size of the map is checked again after clearing it.

This example demonstrates basic operations with a JavaScript Map, including creation, addition, deletion, checking size, checking for key existence, getting values, iteration, and clearing.

JS Typeof

In JavaScript, the typeof operator is a built-in operator that is used to determine the data type of a given expression or variable.

1.Data Type Identification:

The primary purpose of the typeof operator is to identify the data type of a value. It returns a string indicating the type of the operand.

2.Unary Operator:

typeof is a unary operator, meaning it operates on only one operand. It is followed by the operand whose type is to be determined.

3.String Result:

The result of the typeof operator is always a string. It returns a string representation of the data type of the operand.

4.Possible Return Values:

The possible return values include:

"undefined": Indicates that the operand is an undefined value.

​"boolean": Indicates that the operand is a boolean value.

"number": Indicates that the operand is a numeric value, including integers and floating-point numbers. "string": Indicates that the operand is a string value. "symbol": Indicates that the operand is a symbol value (introduced in ECMAScript 6).

"object": Indicates that the operand is an object, function, or null.

​              "function": Indicates that the operand is a function.

1.Note on Arrays and null:

Arrays and null have a typeof result of "object". This is a quirk in the language and is often considered a limitation of the typeof operator.

2.Checking for undefined:

One common use of typeof is to check if a variable is undefined. For example, typeof someVariable === 'undefined' is a common pattern to check if a variable is declared but not assigned a value.

3.Avoiding null Check:

When checking for null, it's often recommended to use a direct equality check (someVariable === null) instead of relying on typeof.

4.Use in Conditional Statements:

The typeof operator is often used in conditional statements or type-checking scenarios where different actions need to be taken based on the type of a variable.

5.Dynamic Typing:

JavaScript is a dynamically typed language, meaning that variables can hold values of different types during the execution of a program. The typeof operator provides a way to dynamically inspect and handle different types of values.

Understanding the typeof operator is fundamental for checking and handling different types of values in JavaScript. It's commonly used in scenarios where dynamic type checking is required, and the code needs to adapt to different types of data at runtime.

// JavaScript typeof Example

// Variables of Different Types let numberVar = 42; let stringVar = "Hello, World!"; let booleanVar = true; let arrayVar = [1, 2, 3]; let objectVar = { key: "value" }; let functionVar = function() {};

// Using typeof Operator

console.log("Type of numberVar: " + typeof numberVar); console.log("Type of stringVar: " + typeof stringVar); console.log("Type of booleanVar: " + typeof booleanVar); console.log("Type of arrayVar: " + typeof arrayVar); console.log("Type of objectVar: " + typeof objectVar); console.log("Type of functionVar: " + typeof functionVar);

// End of JavaScript typeof Example

In ​this ​example, ​the ​JavaScript ​typeof ​operator               is demonstrated:

1.Variables of Different Types:

Variables are declared with values of different types, including number, string, boolean, array, object, and function.

2.Using typeof Operator:

The typeof operator is used to determine the type of each variable.

3.Displaying Results:

The results of the typeof operator for each variable are displayed using console.log.

This example shows how to use the typeof operator to determine the data type of a variable in JavaScript.

JS Type Conversion

In JavaScript, type conversion refers to the process of converting a value from one data type to another. This can happen implicitly or explicitly, depending on the context.

1.Implicit Type Conversion (Coercion):

Implicit type conversion, also known as coercion, occurs automatically when an operation between values of different types is performed. JavaScript tries to convert one or both of the operands to a common type before performing the operation.

2.Example of Implicit Type Conversion:

An example of implicit type conversion is when you use the + operator with a string and a number. The number is implicitly converted to a string, and concatenation occurs instead of addition.

3.Explicit Type Conversion (Casting):

Explicit type conversion, also known as casting, is when you intentionally convert a value from one type to another using functions or methods provided by the language. This allows you to control and specify the desired type.

4.Example of Explicit Type Conversion:

An example of explicit type conversion is using functions like String(), Number(), or Boolean() to convert values to strings, numbers, or booleans, respectively.

5.String Conversion:

To convert a value to a string, you can use the String() function or the toString() method. This is often done when you want to concatenate a value with a string or perform string-related operations.

1.Numeric Conversion:

To convert a value to a number, you can use the Number() function or the parseInt() and parseFloat() functions. This is useful when you want to perform mathematical operations.

2.Boolean Conversion:

To convert a value to a boolean, you can use the Boolean() function. In JavaScript, many values have inherent truthy or falsy values, and this conversion is often used in conditional statements.

3.Note on Falsy Values:

In conditional contexts, values that are considered falsy (e.g., 0, null, undefined, NaN, empty string) are implicitly converted to false, while truthy values are converted to true.

4.Complex Operations:

In complex operations, where different types are involved, both implicit and explicit type conversions may occur. Understanding how JavaScript handles type conversion is essential for avoiding unexpected behavior.

5.Consideration for NaN:

Be aware that certain operations can result in NaN (Not a Number), which is a special numeric value representing the result of an undefined or unrepresentable mathematical operation.

6.Handling Type Conversion Errors:

When explicitly converting types, it's important to handle potential errors, especially if the conversion may not be successful.

Type conversion is a fundamental aspect of JavaScript, and understanding how it occurs, both implicitly and explicitly, is crucial for writing reliable and predictable code. It's important to be mindful of the potential pitfalls and nuances associated with type conversion in different contexts.

// JavaScript Type Conversion Example

// Implicit Type Conversion (Coercion) let numString = "42"; let resultImplicit = 10 + numString;

// Explicit Type Conversion let numExplicit = Number(numString); let resultExplicit = 10 + numExplicit;

// Displaying Results

console.log("Implicit Type Conversion: " + resultImplicit); // Concatenation

console.log("Explicit Type Conversion: " + resultExplicit); // Addition

// End of JavaScript Type Conversion Example

In this example, JavaScript type conversion is demonstrated:

1.Implicit Type Conversion (Coercion):

The variable numString is a string containing the characters "42". When it is used in an operation with the + operator and the number 10, JavaScript performs implicit type conversion (coercion) and treats it as concatenation, resulting in the string "1042".

2.Explicit Type Conversion:

The Number function is used for explicit type conversion to convert the string "42" to a numeric value (numExplicit). When used in an operation with the + operator and the number 10, JavaScript performs addition, resulting in the numeric value 52.

3.Displaying Results:

The results of both implicit and explicit type conversion are displayed using console.log.

This example illustrates the concepts of implicit and explicit type conversion in JavaScript. Implicit type conversion occurs automatically, while explicit type conversion involves using functions like Number, String, or Boolean to convert values intentionally.

JS Bitwise

1.In JavaScript, bitwise operations are operations that directly manipulate individual bits of binary representations of integers. These operations treat their operands as sequences of 32 bits (zeros and ones).

2.Bitwise AND (&):

a.The bitwise AND operation is denoted by the & operator. It compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the resulting bit is 1; otherwise, it is 0.

3.Bitwise OR (|):

a.The bitwise OR operation is denoted by the | operator. It compares each bit of the first operand to the corresponding bit of the second operand. If at least one of the bits is 1, the resulting bit is 1; otherwise, it is 0.

4.Bitwise XOR (^):

a.The bitwise XOR (exclusive OR) operation is denoted by the ^ operator. It compares each bit of the first operand to the corresponding bit of the second operand. If the bits are different, the resulting bit is 1; if they are the same, it is 0.

5.Bitwise NOT (~):

a.The bitwise NOT operation is denoted by the ~ operator. It flips each bit of its operand. That is, 1 becomes 0, and 0 becomes 1. Note that this operation also changes the sign of the number.

6.Left Shift (<<):

a.The left shift operation is denoted by the << operator. It shifts the bits of the first operand to the left by a specified number of positions. Zeros are shifted in from the right.

1.Right Shift (>>):

The right shift operation is denoted by the >> operator. It shifts the bits of the first operand to the right by a specified number of positions. For positive numbers, zeros are shifted in from the left. For negative numbers, the behavior may depend on the implementation.

2.Unsigned Right Shift (>>>):

The unsigned right shift operation is denoted by the >>> operator. It shifts the bits of the first operand to the right by a specified number of positions. Zeros are shifted in from the left, and the sign bit is filled with zero.

3.Use Cases:

Bitwise operations are often used in low-level programming, cryptography, and optimization where manipulation at the bit level is required. They can be used to set or clear specific bits, check the parity of numbers, and perform other bitwise manipulations.

4.Performance Considerations:

In some cases, bitwise operations can lead to more efficient code in terms of execution speed. However, they should be used judiciously, as they can make the code less readable and more error-prone.

5.Binary Representation:

Understanding the binary representation of numbers is essential when working with bitwise operations. The operations directly manipulate the binary bits of integers.

Bitwise operations are a low-level feature in JavaScript and are not as commonly used as other types of operations. They are often employed in specific scenarios where bitwise manipulation is necessary for specific algorithmic or optimization purposes.

// JavaScript Bitwise Operators Example

// Bitwise AND (&) let bitwiseANDResult = 5 & 3;

// Bitwise OR (|) let bitwiseORResult = 5 | 3;

// Bitwise XOR (^) let bitwiseXORResult = 5 ^ 3;

// Bitwise NOT (~) let bitwiseNOTResult = ~5;

// Left Shift (<<) let leftShiftResult = 5 << 1;

// Right Shift (>>) let rightShiftResult = 5 >> 1;

// Unsigned Right Shift (>>>) let unsignedRightShiftResult = -5 >>> 1;

// Displaying Results

console.log("Bitwise AND: " + bitwiseANDResult); console.log("Bitwise OR: " + bitwiseORResult); console.log("Bitwise XOR: " + bitwiseXORResult); console.log("Bitwise NOT: " + bitwiseNOTResult); console.log("Left Shift: " + leftShiftResult); console.log("Right Shift: " + rightShiftResult);

console.log("Unsigned Right Shift: " + unsignedRightShiftResult);

// End of JavaScript Bitwise Operators Example

In this example, JavaScript bitwise operators are demonstrated:

1.Bitwise AND (&):

The & operator performs a bitwise AND operation between the binary representations of the numbers 5 and 3.

2.Bitwise OR (|):

​The | operator performs a bitwise OR operation between the binary representations of the numbers 5 and 3.

3.Bitwise XOR (^):

The ^ operator performs a bitwise XOR (exclusive OR) operation between the binary representations of the numbers 5 and 3.

4.Bitwise NOT (~):

The ~ operator performs a bitwise NOT (complement) operation on the binary representation of the number 5.

5.Left Shift (<<):

The << operator shifts the binary representation of the number 5 one position to the left.

6.Right Shift (>>):

The >> operator shifts the binary representation of the number 5 one position to the right.

7.Unsigned Right Shift (>>>):

The >>> operator shifts the binary representation of the negative number -5 one position to the right, filling the leftmost positions with zeros.

8.Displaying Results:

The results of each bitwise operation are displayed using console.log. This example illustrates the use of bitwise operators in JavaScript for performing operations at the binary level.