Javascript

Introduction
Where To
JavaScript Output
JS Statements
JS Syntax
JS Comments
JS Variables
JS Let
JS Const
JS Operators
JS Assignment

JS Introduction

JavaScript is a versatile programming language for web development, enhancing websites with interactivity and dynamic features.

JavaScript Can Change HTML Content

One of the JavaScript HTML methods is getElementById().

The below example "finds" an HTML element (with id="Introduction"), and changes the element content (innerHTML) to "Hello JavaScript":

<!DOCTYPE html>
<html>
<body>
<h2>span>What Can JavaScript Do?</h2>
<p id="Introduction">JavaScript can change HTML content.</p>
<button type="button" onclick='document.getElementById("Introduction").innerHTML = "Hello JavaScript!"'>Click Me!</button>
</body>
</html>
JavaScript accepts both double and single quotes:

What Can JavaScript Do?

JavaScript can change HTML content.

JS Can Hide HTML Elements

You can set element.style.display = "none" to completely remove an element or element.style.visibility = "hidden" to hide it while preserving layout space.

<!DOCTYPE html>
<html>
<body>
<h2>What Can JS Do?</h2>
<p id="output">JS can hide HTML elements.</p>
<button type="button" onclick="document.getElementById('output').style.display='none'">Click Me!</button> </body>
</html>

JS Can Show HTML Elements

You can set element.style.display = "block" or element.style.visibility = "visible" to make the element visible again. This allows dynamic, interactive web pages.

<!DOCTYPE html>
<html>
<body>
<h2>What Can JS Do?</h2>
<p>JS can show hidden HTML elements.</p>
<p id="output" style="display:none">Hello JS!</p>
<button type="button" onclick="document.getElementById('output').style.display='block'">Click Me!</button> </body>
</html>

JS Where To

JavaScript can be included in an HTML document using the <script> element.

You have several options for where to place your JavaScript code:

JS Tags

In HTML, the <script> tag is used to include JavaScript code in a web page. Here are some important points about the </script> tag:

Element:-

<!DOCTYPE html>
<html>
<body>
<h2>This is JS in body</h2>
<p id ="output"></p>
<script>document.getElementById("output").innerHTML = "This is my First JS";</script>
<body>
<html>

Inline JavaScript:

You can use the <script> tag to include JavaScript code directly within an HTML document. This code can be placed either in the <head> section or at the end of the <body> section.

External JavaScript:

The <script> tag is also used to link to external JavaScript files. This is a best practice for organizing and reusing code in larger projects.

Example:-

<!DOCTYPE html>
<html>
<head>
<!-- Inline JavaScript -->
<script type="text/javascript">
function myFunction() { alert("Hello from inline JavaScript!");}
</script>
<!-- External JavaScript -->
<script src="external-script.js" type="text/javascript"></script>
</head>
<body>
<button onclick="myFunction()">Click me</button>
</body>
<html>

Attributes:

The <script> tag can have various attributes, including:

  • "src": Used to specify the source file for an external JavaScript file.
  • "type": Specifies the scripting language (e.g., "text/javascript" for JavaScript).
  • "async" and "defer": Attributes for controlling how the script is executed in relation to the page loading process.

Advantages:

  • Improved code organization and maintainability.
  • Faster page loading through caching.
  • Reduced page size for quicker load times.
  • Facilitates collaboration in web development.
  • Efficient debugging and error resolution.

JS Output

JavaScript can produce output in several ways:

  • Alerts
  • Console
  • write
  • Alerts: You can use the 'alert()' function to display a dialog box with a message to the user.
  • Ex:

    <!DOCTYPE html>
    <html>
    <body>
    <script>
    alert("Hello, JavaScript!");
    </script>
    <body>
    <html>

  • Console:Output can be logged to the browser's console using 'console.log()' for debugging and development purposes.
  • Ex:

    <!DOCTYPE html>
    <html>
    <body>
    <script>
    console.log("This message will appear in the console.");
    </script>
    <body>
    <html>

  • Writing to the Document: You can write directly to the HTML document using methods like 'document.write()', although this is used less frequently.
  • Ex:

    <!DOCTYPE html>
    <html>
    <body>
    <script>
    document.write("This will be written in the document.");
    </script>
    <body>
    <html>

  • Response Handling: In server-side JavaScript (Node.js), you can send output to a client in response to HTTP requests, often in the form of JSON, HTML, or other data.
  • JavaScript's output methods are versatile and can be used for various purposes, from user notifications to debugging and updating web page content dynamically.

JS Statements

JavaScript consists of a variety of statements that are the building blocks of your code. Here are some common JavaScript statements:

  1. Variable Declaration:
  2. <!DOCTYPE html>
    <html>
    <body>
    <script>
    let x; // Declaring a variable 'x'
    </script>
    <body>
    <html>
  3. Assignment:
  4. <!DOCTYPE html>
    <html>
    <body>
    <script>
    x = 5; // Assigning the value 5 to 'x'
    </script>
    <body>
    <html>
  5. Conditional Statements:
    • 'if', 'else if', 'else'
    • 'switch', 'case', 'default'
  6. Loops:
    • 'for'
    • 'while'
    • 'do...while'
    • 'for...in'
    • 'for...of'
  7. Function Declaration:
  8. function myFunction() { // Function body }
  9. Return Statement:
  10. return result; // Returning a value from a function
  11. Break and Continue:
    • 'break': Exits a loop or switch statement.
    • 'continue': Skips the current iteration of a loop.
  12. Throw Statement:
  13. throw new Error("An error occurred."); // Throws an exception
  14. Try...Catch...Finally:
    • 'try': Contains code that may cause an exception.
    • 'catch': Handles exceptions.
    • 'finally': Contains code that runs regardless of whether an exception is thrown.
  15. Alert and Console Output:y:
  16. alert("This is an alert."); // Displays a popup alert
    console.log("Log this message."); // Outputs to the browser console

JS Syntax

JavaScript follows a specific syntax that must be adhered to for your code to work correctly.

Here are some fundamental components of JavaScript syntax:

  1. Statements: JavaScript programs are composed of individual statements, each ending with a semicolon (;) or a line break.
  2. Variables: Declare variables using 'var', 'let', or 'const', followed by a variable name. For example: 'let myVar';
  3. Data Types: JavaScript supports various data types, including numbers, strings, booleans, objects, arrays, and functions.
  4. Comments: You can add single-line comments using '//' or multi-line comments with '/* ... */'.
  5. Operators: JavaScript provides operators for arithmetic, comparison, logical operations, and more, such as '+', '-', '*' & '/' etc.
  6. Conditional Statements: Use if, else if, and else for conditional execution of code.
  7. Loops: JavaScript supports for, while, and do...while loops for repetitive execution of code.
  8. Functions: You can define functions using the 'function' keyword. For example: 'function myFunction() { ... }'
  9. Objects: Objects are a fundamental data structure in JavaScript, often created using curly braces, e.g., '{ key: value }'.
  10. Arrays: Arrays are collections of data, created with square brackets, e.g., 'let myArray = [1, 2, 3];'
  11. Events: Event handlers allow you to respond to user interactions (e.g., 'addEventListener' for handling events).
  12. DOM Manipulation: You can access and modify HTML elements in the Document Object Model (DOM) using JavaScript.
  13. String Manipulation: JavaScript provides methods for working with strings, such as concatenation and substring extraction.
  14. Error Handling: Use 'try...catch' for handling exceptions and errors.
  15. ES6 Features: Modern JavaScript (ES6 and beyond) includes features like arrow functions, template literals, destructuring, and more.

JS Syntax Ex:-

Variable Declaration:

let age;

Variable Assignment:

age = 30;

Operators:

document.getElementById("output").innerHTML = (2 + 5) * 2;
document.getElementById("output").innerHTML = (100 - 80) / 2;
document.getElementById("output").innerHTML = "BOBS" + " " + "COMMERCE";

Conditional Statement (if...else):

var age = 20; if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}

Loop (for):

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

Function Declaration:

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

Array and Iteration:

let colors = ["red", "green", "blue"];
for (let color of colors) {
console.log("Color: " + color);
}

Object and Property Access:

let person = { name: "Alice", age: 25 };
console.log("Name: " + person.name + ", Age: " + person.age);

String Manipulation:

let message = "Hello, " + "world!";

Event Handling (addEventListener):

document.getElementById("myButton").addEventListener("click", function() {,
console.log("Button clicked!");
});

Error Handling (try...catch):

try {
// Code that might throw an error
} catch (error) {
console.error("An error occurred: " + error);
}

JS Values

Number:

Numeric values, including integers and floating-point numbers.

let age = 30;
let price = 19.99;

String:

Textual values enclosed in single or double quotes.

let name = "John";
let message = 'Hello, world!';

Boolean:

Represents true or false.

let isApproved = true;
let isStudent = false;

Array:

Ordered lists of values.

let colors = ["red", "green", "blue"];

Object:

A collection of key-value pairs.

let person = { name: "Alice", age: 25 };

Null:

Represents the absence of value.

let emptyValue = null;

Undefined:

A variable that has been declared but has not been assigned a value.

let age;

Symbol (ES6):

Unique and immutable values often used as object property keys.

const uniqueKey = Symbol("description");

BigInt (ES11):

Represents large integers that exceed the maximum safe integer in JavaScript.

const bigNumber = 1234567890123456789012345678901234567890n;

Rules for Identifiers:

  1. Character Set: Identifiers can contain letters (a-z, A-Z), digits (0-9), underscores (_), and dollar signs ($).
  2. Starting Character: Identifiers must begin with a letter, underscore (_), or dollar sign ($) and cannot start with a digit.
  3. Case Sensitivity: Identifiers are case-sensitive, meaning that "myVariable" and "myvariable" are distinct.

Conventions for Identifiers:

  1. Camel Case: Common for variable and function names. Begin with a lowercase letter and capitalize the first letter of subsequent words (e.g., myVariable, calculateTotalAmount).
  2. Pascal Case (Upper Camel Case): Used for constructors and classes. Start with an uppercase letter and capitalize the first letter of subsequent words (e.g., Person, EmployeeDetails).
  3. Underscore Prefix: Occasionally used to indicate privacy or that an entity is internal (e.g., _privateVar, _internalFunction).
  4. Dollar Sign Prefix: Rarely used, mainly for special purposes, such as jQuery variables (e.g., $element).

Valid Identifiers Examples:

let firstName = "John";
let _privateVar = 42;
function calculateTotalAmount() { // Function code here }
class Product { constructor(name) { this.name = name; } }
let $specialVar = 100;

Invalid Identifiers Examples:

let 123invalid = "Invalid"; // Starts with a digit
let my-variable = "Invalid"; // Contains a hyphen
let this = "Invalid"; // "this" is a reserved keyword

JS Comments

They provide explanations and context about code, making it easier for developers to understand and work with the codebase.

Comments can mark sections for future reference or indicate areas that require attention, helping developers manage and maintain the code effectively.

There are two types:-

  • Single Line Comments
  • Multi-line Comments

Single Line Comments

Single-line comments in JavaScript are used to add explanations or notes to a single line of code. They begin with '//' and extend to the end of the line.

Example:-

let x = 5; // Initialize the variable 'x' with the value 5
// Calculate the sum
let sum = num1 + num2; // Store the result in the 'sum' variable
console.log("The sum is: " + sum); // Output the result to the console

Multi-line Comments

Multi-line comments in JavaScript are used to add explanations or notes that span multiple lines. They are enclosed in '/*' to start the comment and '*/' to end it. Multi-line comments are ignored by the JavaScript interpreter and are often used for more extensive comments or explanations.

Example:-

/* This is a multi-line comment.
It can span multiple lines and is often used for
providing detailed explanations or disclaimers.
These comments do not affect the code's execution.
*/
let x = 5;
let y = 10;

JS Variables

Declaring Variables: Variables are declared using the 'var', 'let', or 'const' keyword, followed by a variable name.

  • 'var' (less commonly used) for declaring variables with function scope.
  • 'let' for declaring variables with block scope (recommended for most cases).
  • 'const' for declaring variables with block scope, which cannot be reassigned (use for constants).

Variable Names (Identifiers): Variable names, also known as identifiers, must follow specific rules:

  • Start with a letter, underscore (_), or dollar sign ($).
  • Can contain letters, digits, underscores, and dollar signs.
  • Are case-sensitive (e.g., 'myVariable' and 'myvariable' are different).

Global Variables

Global variables are declared outside of functions or code blocks and can be accessed from anywhere in your code.

Example:-

// This is a global variable
let globalVar = 10;
function useGlobalVar() {
// Global variable accessible in the function
console.log("Global Variable: " + globalVar);
}
useGlobalVar(); // Output: Global Variable: 10
console.log("Global Variable: " + globalVar); // Output: Global Variable: 10

Local Variables

Local variables are declared inside functions or code blocks and are only accessible within the scope where they are defined.

Example:-

function useLocalVar() {
// This is a local variable
let localVar = 5;
console.log("Local Variable: " + localVar);
}
useLocalVar(); // Output: Local Variable: 5
// Attempting to access a local variable outside its scope results in an error
console.log("Local Variable: " + localVar); // Error: localVar is not defined

Local & Global Variables

Example:-

<!DOCTYPE html>
<html>
<body>
<p id ="g_output1"></p>
<p id ="g_output2"></p>
<p id ="g_output3"></p>

<script>
// This is a global variable
let x, y, z;
x = 5;
y = 20;
z = x + y;
document.getElementById('g_output1').innerHTML = x ;
document.getElementById('g_output2').innerHTML = i ;
//NOTE: 'i' is local variable not allowed in this script.
</script>

<button type="button" onclick="my()">Click</button>

<script>
// This is a local variable
// But in this script 'x' is global variable 'i' is local variable.
function my() {
let i = 10;
j = 15;
k = i + j ;
document.getElementById('g_output3').innerHTML = x +' ' + i ;
}
</script>

</body>
</html>

More Then One Variables

In JavaScript, you can declare and work with multiple variables in several ways:

Example:-


var x, y, z;

var a = 5, b = "Hello", c = true;

let variable1 = 10, variable2 = "World";
const PI = 3.14, isMonday = true;

const [first, second] = [1, 2];
// first = 1, second = 2

var person = { firstName: "John", lastName: "Doe", age: 30 };
var { firstName, lastName, age } = person;

var colors = ["red", "green", "blue"];
var [color1, color2, color3] = colors;

Algebra in JavaScript

Algebra in JavaScript involves manipulating variables with operators to solve mathematical expressions and perform computations in web development.

Example:-

// JavaScript code for algebraic operations
// Define variables
var x = 5;
var y = 8;
// Perform algebraic operations
var sum = x + y;
var difference = x - y;
var product = x * y;
var quotient = x / y;
// Display results
console.log("Sum:", sum);
console.log("Difference:",
difference);
console.log("Product:", product);
console.log("Quotient:", quotient);

Identifiers

JavaScript identifiers are names used to represent variables, functions, and other elements in code. They must follow specific rules:

  • Naming Rules: Start with a letter, underscore (_), or dollar sign ($) followed by letters, digits, underscores, or dollar signs. For example: 'myVar', '_count', '$totalAmount'.
  • Case-Sensitivity: Identifiers are case-sensitive. 'total' and 'Total' are considered different.
  • Reserved Words: Avoid using reserved words like 'if', 'else', .function' as identifiers.

Examples of valid identifiers:-

var myVariable;
var myVariable;
var firstName;
var calculateTotal;
var user_id;
var _counter;
var $totalAmount;
function calculateTotal() { /* function body */ }
var firstName;

Examples of invalid identifiers:

// Cannot start with a number
var 1stPlace;
// Contains an invalid character
var user@name;
// Reserved word
var if; // Not allowed

JS Let

In JavaScript, the let keyword is block-scoped, which means it cannot be redeclared within the same block or scope. This is in contrast to the var keyword, which can be redeclared within the same scope.

Let Cannot be Redeclared in javascript,
Here's an example illustrating how let cannot be redeclared
:

Example:-

// Example 1
let x = 10;
// Error: Identifier 'x' has already been declared
let x = 20;
// Example 2
function exampleFunction() {
let y = 30;
// Error: Identifier 'y' has already been declared
let y = 40;
}

Var Can be Redeclared in javascript,
Here's an example illustrating how var can be redeclared
:

Example:-

var x = 10;
var x = 20; // Redeclaration of 'x'
console.log(x); // 20
function exampleFunction() {
var y = 30;
var y = 40; // Redeclaration of 'y'
console.log(y); // 40
}
exampleFunction();

Global Scope and Function Scope

Block scope refers to the area within code blocks, such as those denoted by curly braces {} in JavaScript. Variables declared with let and const are block-scoped, meaning their visibility is limited to the block in which they are defined.

  1. Global Scope:

    • Variables declared outside of any function or block have global scope.
    • They are accessible throughout the entire code, including within functions and blocks.

    Example:-

    // Example:1
    // Declaring a variables inside a bock {}.
    {
    var x = 5;
    }
    // You can be use 'x' outside the block.

    // Example:2
    var globalVar = "I am global"; // Global scope
    function exampleFunction() {
    console.log(globalVar); // Accessible
    }
    exampleFunction();

  2. Function Scope:

    • Variables declared inside a function have function scope.
    • They are only accessible within that function.

    Example:-

    // Example:1
    // Declaring a variables inside a bock {}.
    {
    let x = 5;
    }
    // You cannot be use 'x' outside the block.
    // Example:2

    function exampleFunction() {
    var localVar = "I am local"; // Function scope
    console.log(localVar); // Accessible
    }
    exampleFunction(); // Attempting to access localVar here would result in an error
    // console.log(localVar); // Error: localVar is not defined

Redeclaring Let & Var

In JavaScript, the ability to redeclare variables depends on whether they were declared using 'let' or 'var'.

  1. 'let' (Block-Scoped):

    • Variables declared with 'let' are block-scoped, meaning they are confined to the block, statement, or expression where they are defined.
    • Attempting to redeclare a variable with 'let' within the same block or scope results in an error.

    Example:-

    let x = 10;
    // Error: Identifier 'x' has already been declared
    let x = 20;

  2. 'var' (Function-Scoped):

    • Variables declared with 'var' are function-scoped or globally-scoped, and they can be redeclared within the same scope.

    Example:-

    var y = 30;
    var y = 40; // Redeclaration of 'y'

JS Const

JavaScript 'const' is a keyword used to declare variables with a constant value. Once assigned, the value of a 'const' variable cannot be reassigned or redeclared.

  1. Constant Value:
    • Once a value is assigned to a 'const' variable, it cannot be changed.

    Example:

    const PI = 3.14;
    // Error: Assignment to constant variable
    PI = 3.14159;
  2. Block Scope:
    • 'const' is block-scoped, similar to 'let'.

    Example:

    if (true) {
    const blockConst = 42;
    console.log(blockConst); // Accessible within the block
    }
    // Error: blockConst is not defined here
    console.log(blockConst);
  3. Object and Array Mutability:
    • While the variable itself cannot be reassigned, the contents of an object or array declared with 'const' can be modified.

    Example:

    const numbers = [1, 2, 3];
    numbers.push(4); // Valid, modifies the array
    numbers[0] = 10; // Valid, modifies the array
    const person = { name: 'John', age: 30 };
    person.age = 31; // Valid, modifies the object
  4. Naming Conventions:
    • It's a common convention to use 'const' for values that are not expected to change, enhancing code readability and signaling the intent of immutability.

    Example:

    const DAYS_IN_WEEK = 7;
    const API_KEY = 'your-api-key';

JS Operators & Arithmetic Operators

JavaScript operators are symbols or keywords that perform operations on operands (values or variables). Here are some common JavaScript operators with examples:

<!DOCTYPE html>
<html>
<body>
<h4>Example:-</h4>
<p id="output"></p>

<script>
let x, y, z;
x = 30;
y = 3;
// You can use below conditons one by one
z = x + y;
// z = x - y;
// z = x * y;
// z = x / y;
document.getElementById("output").innerHTML = z;
</script>

<body>
<html>
  1. Arithmetic Operators:
    • Perform mathematical operations like addition, subtraction, multiplication, division, and modulus.

    Example:-

    let a = 5;
    let b = 2;

    let sum = a + b; // Addition
    let difference = a - b; // Subtraction
    let product = a * b; // Multiplication
    let quotient = a / b; // Division
    let remainder = a % b; // Modulus

  2. Comparison Operators:
    • Compare values and return a Boolean result, such as greater than, less than, equal to, and not equal to.

    Example:-

    let x = 10;
    let y = 5;

    console.log(x > y); // Greater than
    console.log(x < y); // Less than
    console.log(x === y); // Equal to
    console.log(x !== y); // Not equal to

  3. Logical Operators:
    • Perform logical operations like AND, OR, and NOT on Boolean values.

    Example:-

    let isTrue = true;
    let isFalse = false;

    console.log(isTrue && isFalse); // Logical AND
    console.log(isTrue || isFalse); // Logical OR
    console.log(!isTrue); // Logical NOT

  4. Assignment Operators:
    • Assign values to variables, often combined with arithmetic or other operations.

    Example:-

    let num = 10;

    num += 5; // Equivalent to: num = num + 5;
    num -= 3; // Equivalent to: num = num - 3;

  5. Unary Operators:
    • Operate on a single operand, such as increment (++) and decrement (--).

    Example:-

    let count = 5;

    count++; // Increment by 1
    count--; // Decrement by 1

  6. Conditional (Ternary) Operator:
    • A shorthand for an if-else statement, providing a concise way to make decisions.

    Example:-

    let age = 20;
    let status = (age >= 18) ? "Adult" : "Minor";

  7. String Operators:
    • In JavaScript, string operators are used to perform operations specifically on strings.

    Example:-

    //Concatenation Operator (+):

    let firstName = "BABS";
    let lastName = "COMMERCE";
    let fullName = firstName + " " + lastName; // Concatenation

    //String Assignment Operator (+=):

    let greeting = "Hello, ";
    let name = "World";
    greeting += name; // Concatenation and assignment

    //String Comparison Operator (== and ===):

    let str1 = "Hello";
    let str2 = "World";
    console.log(str1 == str2); // Equality comparison

    //String Length Operator (length):

    let message = "BABS, COMMERCE!";
    console.log(message.length); // Output: 15

  8. Bitwise Operators:
    • In JavaScript, bitwise operators are used for low-level, binary operations on integers.
      Here's a brief description of common bitwise operators:
    • A shorthand for an if-else statement, providing a concise way to make decisions.

    Example:-

    //Bitwise AND (&):
    let result = 5 & 3; // Bitwise AND of 5 (binary 101) and 3 (binary 011)
    // Result in binary: 001 (Decimal: 1)

    //Bitwise OR (|):
    let result = 5 | 3; // Bitwise OR of 5 (binary 101) and 3 (binary 011)
    // Result in binary: 111 (Decimal: 7)

    //Bitwise XOR (^):
    let result = 5 ^ 3; // Bitwise XOR of 5 (binary 101) and 3 (binary 011)
    // Result in binary: 110 (Decimal: 6)

    //Bitwise NOT (~):
    let result = ~5; // Bitwise NOT of 5 (binary 101)
    // Result in binary:
    1111111111111111111111111111111111111111111111111111111111111010 (32-bit representation)

    //Left Shift (<<):
    let result = 5 << 1; // Left shift of 5 (binary 101) by 1 position
    // Result in binary: 1010 (Decimal: 10)

    //Sign-Propagating Right Shift (>>):
    let result = 5 >> 1; // Sign-propagating right shift of 5 (binary 101) by 1 position
    // Result in binary: 10 (Decimal: 2)

    //Zero-Fill Right Shift (>>>):
    let result = -5 >>> 1; // Zero-fill right shift of -5 (binary -101) by 1 position
    // Result in binary:
    1111111111111111111111111111111111111111111111111111111111111110 (32-bit representation)

  9. Remainder Operation with Modulus Operator %:
    • The modulus operator calculates the remainder when the left operand is divided by the right operand.

    Example:-

    let dividend = 17;
    let divisor = 5;

    let remainder = dividend % divisor;
    console.log(remainder); // Output: 2

  10. Increment & Decrement Operator (++) (--):
    • In JavaScript, incrementing and decrementing are operations used to increase or decrease the value of a variable by a specific amount.

    Example:-

    //Increment Operator (++):
    let count = 5;
    count++; // Increment by 1
    console.log(count); // Output: 6

    // (++count)
    let count = 5;
    let result = ++count;
    console.log(result); // Output: 6

    //Decrement Operator (--):
    let count = 5;
    count--; // Decrement by 1
    console.log(count); // Output: 4

    //(--count)
    let count = 5;
    let result = --count;
    console.log(result); // Output: 4

  11. Exponentiation Operator (**):
    • The exponentiation operator calculates the power of a number.

    Example:-

    let base = 2;
    let exponent = 3;

    let result = base ** exponent;
    console.log(result); // Output: 8 (2^3 = 8)

JS Assignment

In JavaScript, assignment operators are used to assign values to variables.
Here's a short description with examples of common assignment operators:

  1. Assignment:
    • Assigns the value on the right-hand side to the variable on the left-hand side.

    Example:-

    let x = 10;

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

    Example:-

    let y = 5;
    y += 3; // Equivalent to: y = y + 3;

  3. Subtraction Assignment (-=):
    • Subtracts the right operand from the left operand and assigns the result to the left operand.

    Example:-

    let z = 8;
    z -= 2; // Equivalent to: z = z - 2;

  4. Multiplication Assignment (*=):
    • Multiplies the left operand by the right operand and assigns the result to the left operand.

    Example:-

    let a = 4;
    a *= 2; // Equivalent to: a = a * 2;

  5. Division Assignment (/=):
    • Divides the left operand by the right operand and assigns the result to the left operand.

    Example:-

    let b = 16;
    b /= 4; // Equivalent to: b = b / 4;

  6. Remainder Assignment (%=):
    • Calculates the remainder of the division of the left operand by the right operand and assigns the result to the left operand.

    Example:-

    let c = 17;
    c %= 5; // Equivalent to: c = c % 5;

  7. Left Shift Assignment (<<=):
    • In this example, num <<= 2 performs a left shift of the binary representation of num by 2 positions. The result is equivalent to multiplying num by 2 raised to the power of 2 (num * 2^2), which is 20.

    Example:-

    let num = 5;

    // Left shift by 2 positions and assign the result to num
    num <<= 2; // Equivalent to: num = num << 2;

    console.log(num); // Output: 20 (Binary: 10100)

  8. Right Shift Assignment (>>=):
    • In this example, num >>= 2 performs a right shift of the binary representation of num by 2 positions. The result is equivalent to dividing num by 2 raised to the power of 2 (num / 2^2), which is 4.

    Example:-

    let num = 16;

    // Right shift by 2 positions and assign the result to num
    num >>= 2; // Equivalent to: num = num >> 2;

    console.log(num); // Output: 4 (Binary: 100)