docs

1. Basic

JavaScript is a dynamic programming language that is widely used for building interactive and dynamic web applications. It allows developers to create complex functionalities on web pages, handle user events, and manipulate the DOM (Document Object Model). JavaScript is interpreted by browsers, and it runs on both the client side and server side.

Key Concepts:

Example:

let message = "Hello, World!";
console.log(message); // Outputs: Hello, World!

function greet(name) {
  return `Hello, ${name}!`;
}

console.log(greet("Alice")); // Outputs: Hello, Alice!

2. Declaration

In JavaScript, variables are declared using three keywords: var, let, and const. These keywords have different scopes and behaviors.

2.1. var Declaration

Example:

function varExample() {
  console.log(x); // Outputs: undefined (due to hoisting)
  var x = 10;
  console.log(x); // Outputs: 10
}
varExample();

2.2. let Declaration

Example:

function letExample() {
  if (true) {
    let y = 20;
    console.log(y); // Outputs: 20
  }
  // console.log(y); // Uncaught ReferenceError: y is not defined
}
letExample();

2.3. const Declaration

Example:

const z = 30;
// z = 40; // Uncaught TypeError: Assignment to constant variable
const arr = [1, 2, 3];
arr.push(4); // Modifies the array but doesn't reassign it
console.log(arr); // Outputs: [1, 2, 3, 4]

3. Data Structures and Types

JavaScript supports several data types, broadly categorized into primitive types and reference types (objects). It also supports complex data structures such as arrays and objects.

3.1. Primitive Data Types

Example:

let name = "Alice"; // String
let age = 25; // Number
let isStudent = true; // Boolean
let noValue = null; // Null
let notAssigned; // Undefined

console.log(typeof name); // Outputs: string
console.log(typeof age); // Outputs: number

3.2. Reference Data Types

Example (Object and Array):

let person = {
  name: "John",
  age: 30,
};

let numbers = [1, 2, 3, 4, 5];
console.log(person.name); // Outputs: John
console.log(numbers[0]); // Outputs: 1

4. Literals

In JavaScript, literals represent fixed values that are directly written into the code. These include:

Example:

let numberLiteral = 42; // Number literal
let stringLiteral = "Hello!"; // String literal
let booleanLiteral = true; // Boolean literal

let objectLiteral = {
  // Object literal
  firstName: "Alice",
  lastName: "Doe",
};

let arrayLiteral = [1, 2, 3]; // Array literal

console.log(objectLiteral.firstName); // Outputs: Alice
console.log(arrayLiteral[1]); // Outputs: 2

Summary:

You can find more detailed explanations and examples on the MDN page JavaScript Guide - Grammar and Types.

1. Block Statement

A block statement (also called a compound statement) is used to group multiple statements together. It is enclosed within curly braces {}. Blocks can contain zero or more statements, and they are commonly used in control flow statements like if, while, or for to define multiple lines of code that should be executed together.

Key Points:

Example:

if (true) {
  let x = 5;
  console.log(x); // Outputs: 5
}
// console.log(x);  // Uncaught ReferenceError: x is not defined (block-scoped variable)

In this example, the block groups the statements for let declaration and console.log into a single unit that executes only if the if condition is true.

2. Conditional Statement

Conditional statements are used to perform different actions based on different conditions. In JavaScript, you have multiple types of conditional statements:

2.1. if Statement

The if statement is used to execute a block of code if a specified condition evaluates to true. If the condition is false, the block is skipped.

Example:

let age = 18;
if (age >= 18) {
  console.log("You are an adult.");
}

2.2. if...else Statement

The if...else statement provides an alternate block of code to execute if the condition is false.

Example:

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

2.3. else if Ladder

The else if statement is used to test multiple conditions sequentially. Once a condition is true, the corresponding block is executed, and the rest of the ladder is ignored.

Example:

let score = 85;
if (score >= 90) {
  console.log("A grade");
} else if (score >= 75) {
  console.log("B grade");
} else {
  console.log("C grade");
}

2.4. switch Statement

The switch statement is used to execute one of many blocks of code based on the value of an expression.

Example:

let day = 3;
switch (day) {
  case 1:
    console.log("Monday");
    break;
  case 2:
    console.log("Tuesday");
    break;
  case 3:
    console.log("Wednesday");
    break;
  default:
    console.log("Invalid day");
}

Key Points:

3. Exception Handling Statement

Exception handling is a way to handle errors or exceptional situations in your code. JavaScript uses try...catch statements for exception handling, allowing you to catch and handle errors without crashing your application.

3.1. try...catch Statement

The try block contains code that may throw an error. If an error occurs, it is caught and handled in the catch block.

Syntax:

try {
  // Code that may throw an error
} catch (error) {
  // Code to handle the error
}

Example:

try {
  let result = someUndefinedVariable + 10; // This will throw a ReferenceError
} catch (error) {
  console.log("An error occurred: " + error.message); // Outputs: An error occurred: someUndefinedVariable is not defined
}

3.2. finally Block

The finally block can be added after the try...catch block. The code inside the finally block will always execute, regardless of whether an error was thrown or not.

Example:

try {
  let result = 10 / 0; // No error, but division by zero returns Infinity
} catch (error) {
  console.log("Error: " + error.message);
} finally {
  console.log("This will always run."); // Always executes
}

Key Points:

3.3. throw Statement

The throw statement allows you to create custom errors. When you throw an error, the current execution is halted, and control is passed to the nearest catch block.

Example:

function checkAge(age) {
  if (age < 18) {
    throw new Error("You must be 18 or older.");
  } else {
    console.log("Access granted.");
  }
}

try {
  checkAge(15); // Will throw an error
} catch (error) {
  console.log("Error: " + error.message); // Outputs: Error: You must be 18 or older.
}

Summary:

For more details, you can refer to the MDN documentation on JavaScript Control Flow and Error Handling.

1. for Statement

The for loop is one of the most common ways to repeat a block of code a specific number of times. It includes three expressions: initialization, condition, and final expression (increment/decrement), which control the loop’s execution.

Syntax:

for (initialization; condition; increment / decrement) {
  // Code to execute repeatedly
}

Example:

for (let i = 0; i < 5; i++) {
  console.log(i); // Outputs: 0, 1, 2, 3, 4
}

Explanation:


2. do...while Statement

The do...while loop is similar to the while loop, except that it executes the block of code once before checking the condition. This ensures that the loop runs at least once, regardless of the condition.

Syntax:

do {
  // Code to execute
} while (condition);

Example:

let i = 0;
do {
  console.log(i); // Outputs: 0
  i++;
} while (i < 1);

Explanation:


3. while Statement

The while loop repeats a block of code as long as the specified condition evaluates to true. It checks the condition before each iteration, meaning it may not execute the block at all if the condition is false initially.

Syntax:

while (condition) {
  // Code to execute repeatedly
}

Example:

let i = 0;
while (i < 3) {
  console.log(i); // Outputs: 0, 1, 2
  i++;
}

Explanation:


4. Labeled Statement

A labeled statement allows you to label a block of code (or loop) so that it can be referenced by the break or continue statements. It is useful for breaking out of nested loops or specific blocks of code.

Syntax:

labelName: {
  // Code or loop
}

Example:

outerLoop: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    if (i === 1 && j === 1) {
      break outerLoop; // Exits both loops
    }
    console.log(`i: ${i}, j: ${j}`);
  }
}

Explanation:


5. break Statement

The break statement is used to exit a loop or switch statement early. When encountered, it immediately stops the execution of the current loop and moves to the next block of code after the loop.

Syntax:

break;

Example:

for (let i = 0; i < 5; i++) {
  if (i === 3) {
    break; // Exits the loop when i is 3
  }
  console.log(i); // Outputs: 0, 1, 2
}

Explanation:


6. continue Statement

The continue statement skips the current iteration of a loop and continues with the next iteration. It does not stop the loop, just skips the rest of the code for the current iteration.

Syntax:

continue;

Example:

for (let i = 0; i < 5; i++) {
  if (i === 2) {
    continue; // Skips when i is 2
  }
  console.log(i); // Outputs: 0, 1, 3, 4
}

Explanation:


7. for...in Statement

The for...in statement iterates over the enumerable properties of an object. It loops through the keys (property names) of an object.

Syntax:

for (variable in object) {
  // Code to execute
}

Example:

const person = { name: "Alice", age: 25, city: "New York" };

for (let key in person) {
  console.log(`${key}: ${person[key]}`);
}
// Outputs: name: Alice, age: 25, city: New York

Explanation:


8. for...of Statement

The for...of statement iterates over the values of an iterable object, such as arrays, strings, or Set and Map objects. It loops through the values of an iterable rather than its keys.

Syntax:

for (variable of iterable) {
  // Code to execute
}

Example:

const arr = ["apple", "banana", "cherry"];

for (let fruit of arr) {
  console.log(fruit); // Outputs: apple, banana, cherry
}

Explanation:


Summary:

For more detailed information, you can refer to the MDN documentation on JavaScript Loops and Iteration.

1. Defining Functions

In JavaScript, functions are reusable blocks of code that can be defined once and executed multiple times. There are multiple ways to define functions, but the most common approaches are function declarations and function expressions.

Function Declaration:

A function is declared using the function keyword, followed by a name, a parameter list (optional), and a block of code.

Syntax:

function functionName(parameter1, parameter2) {
  // Code to execute
}

Example:

function greet(name) {
  return `Hello, ${name}!`;
}

In this example, the function greet takes one argument (name) and returns a greeting message.

Function Expression:

A function can also be defined as part of an expression, commonly used when assigning a function to a variable.

Example:

const greet = function (name) {
  return `Hello, ${name}!`;
};

Here, the function is assigned to the variable greet.


2. Calling Functions

A function is executed or “called” by writing its name followed by parentheses, which may include arguments. You can call a function as many times as needed.

Syntax:

functionName(arguments);

Example:

console.log(greet("Alice")); // Outputs: Hello, Alice!
console.log(greet("Bob")); // Outputs: Hello, Bob!

In this example, the greet function is called twice with different arguments.


3. Function Scope

Scope refers to the visibility or accessibility of variables. There are two main scopes in JavaScript: global scope and local (function) scope.

Example:

let globalVar = "Global";

function testScope() {
  let localVar = "Local";
  console.log(globalVar); // Accessible
  console.log(localVar); // Accessible
}

testScope();
console.log(globalVar); // Accessible
console.log(localVar); // Error: localVar is not defined

In this example, localVar is not accessible outside the function.


4. Scope and the Function Stack

JavaScript uses a function stack to manage function calls and scopes. When a function is called, a new execution context is created and pushed onto the stack. As each function finishes execution, its context is popped off the stack.

Example:

function first() {
  second(); // Calls the second function
}

function second() {
  console.log("Second function");
}

first();

In this example, the call to first() puts it on the stack, and inside first(), second() is called, which adds second() to the stack.


5. Closures

A closure is a function that retains access to its outer (enclosing) function’s variables even after the outer function has finished execution. This is because functions in JavaScript form “closures” around the environment they were created in.

Example:

function outer() {
  let outerVar = "I'm outside!";

  return function inner() {
    console.log(outerVar); // Accesses outerVar from the outer scope
  };
}

const innerFunc = outer(); // outer() returns the inner function
innerFunc(); // Outputs: I'm outside!

In this example, the inner function retains access to outerVar even after outer() has finished executing.


6. Using the arguments Object

The arguments object is an array-like object that contains all the arguments passed to a function, even if the function does not have defined parameters. It is useful when you don’t know how many arguments will be passed to the function.

Example:

function sum() {
  let total = 0;
  for (let i = 0; i < arguments.length; i++) {
    total += arguments[i];
  }
  return total;
}

console.log(sum(1, 2, 3)); // Outputs: 6

In this example, the arguments object holds all the arguments passed to the sum function.


7. Function Parameters

Function parameters are variables defined in the function definition that act as placeholders for the values (arguments) passed to the function when it is called.

Default Parameters:

You can assign default values to parameters in case they are not provided during the function call.

Syntax:

function functionName(param1 = defaultValue1, param2 = defaultValue2) {
  // Code to execute
}

Example:

function greet(name = "Guest") {
  return `Hello, ${name}!`;
}

console.log(greet()); // Outputs: Hello, Guest!
console.log(greet("Alice")); // Outputs: Hello, Alice!

In this example, if no argument is passed, the parameter name defaults to "Guest".


8. Arrow Functions

Arrow functions are a shorter syntax for writing functions introduced in ES6. They have a more concise syntax and handle the this keyword differently from traditional functions.

Syntax:

const functionName = (param1, param2) => {
  // Code to execute
};

If there is only one parameter, the parentheses can be omitted, and if the function body contains a single expression, the curly braces and return keyword can also be omitted.

Example:

const greet = (name) => `Hello, ${name}!`;

console.log(greet("Alice")); // Outputs: Hello, Alice!

Explanation:

Example with this:

function Person() {
  this.age = 0;

  setInterval(() => {
    this.age++; // Arrow function retains 'this' from the surrounding context
    console.log(this.age);
  }, 1000);
}

const person = new Person();

In this example, the arrow function inside setInterval retains the this value from the Person function.


Summary:

1. Assignment Operators

Assignment operators are used to assign values to variables. The basic assignment operator is =, but there are several compound assignment operators that combine assignment with another operation.

Basic Assignment Operator:

Compound Assignment Operators:

Example:

let x = 10;
x += 5; // x = 15
x *= 2; // x = 30
x -= 10; // x = 20

2. Comparison Operators

Comparison operators compare two values and return a boolean value (true or false). They are useful for making decisions in control structures.

Operators:

Example:

console.log(5 == "5"); // true (type coercion)
console.log(5 === "5"); // false (different types)
console.log(10 > 5); // true
console.log(5 <= 5); // true

3. Arithmetic Operators

Arithmetic operators perform mathematical operations on numbers. They are fundamental for calculations in JavaScript.

Operators:

Example:

let a = 10;
let b = 5;
console.log(a + b); // Outputs: 15
console.log(a - b); // Outputs: 5
console.log(a * b); // Outputs: 50
console.log(a / b); // Outputs: 2
console.log(a % b); // Outputs: 0
console.log(a ** b); // Outputs: 100000

4. Bitwise Operators

Bitwise operators perform operations on binary representations of numbers. They are often used for low-level programming and optimization.

Operators:

Example:

let x = 5; // Binary: 0101
let y = 3; // Binary: 0011
console.log(x & y); // Outputs: 1 (Binary: 0001)
console.log(x | y); // Outputs: 7 (Binary: 0111)
console.log(x ^ y); // Outputs: 6 (Binary: 0110)
console.log(~x); // Outputs: -6 (Binary: 1010)
console.log(x << 1); // Outputs: 10 (Binary: 1010)
console.log(x >> 1); // Outputs: 2 (Binary: 0010)

5. Logical Operators

Logical operators are used to combine or negate boolean values. They are often used in conditional statements.

Operators:

Example:

let a = true;
let b = false;
console.log(a && b); // Outputs: false
console.log(a || b); // Outputs: true
console.log(!a); // Outputs: false

6. BigInt Operators

BigInt is a built-in object that provides a way to represent whole numbers larger than the maximum limit of the Number type in JavaScript. BigInts are created by appending n to the end of an integer or using the BigInt constructor.

Example:

const bigInt1 = BigInt(123456789012345678901234567890);
const bigInt2 = 123456789012345678901234567890n;

console.log(bigInt1 + bigInt2); // Outputs: 246913578024691357802469135780n

Operators:

You can use arithmetic operators with BigInt, but you cannot mix BigInt with regular numbers without explicit conversion.


7. String Operators

In JavaScript, the primary operator for string manipulation is the concatenation operator +. This operator combines two or more strings.

Example:

let str1 = "Hello";
let str2 = "World";
let greeting = str1 + " " + str2; // Outputs: "Hello World"

You can also use template literals (backticks) to create strings that can include variables and expressions.

Example:

let name = "Alice";
let greeting = `Hello, ${name}!`; // Outputs: "Hello, Alice!"

8. Conditional (Ternary) Operator

The conditional (ternary) operator is a shorthand for an if...else statement. It takes three operands and is often used to perform simple conditional logic.

Syntax:

condition ? expressionIfTrue : expressionIfFalse;

Example:

let age = 18;
let status = age >= 18 ? "Adult" : "Minor"; // Outputs: "Adult"

In this example, if age is 18 or older, status is set to “Adult”; otherwise, it is set to “Minor”.


9. Comma Operator

The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand. It is rarely used but can be useful in certain scenarios.

Syntax:

let result = (expression1, expression2, ..., expressionN);

Example:

let a = (1, 2, 3); // Outputs: 3
console.log(a);

In this example, the value of a will be 3, as it is the last operand evaluated.


10. Unary Operators

Unary operators operate on a single operand. They can be used to perform various operations, including negation and increment/decrement.

Common Unary Operators:

Example:

let x = 5;
console.log(+x); // Outputs: 5 (converts to number)
console.log(-x); // Outputs: -5 (negates)
console.log(++x); // Outputs: 6 (increments)
console.log(--x); // Outputs: 5 (decrements)

11. Relational Operators

Relational operators are used to compare values. They return a boolean value indicating whether the comparison is true or false.

Operators:

Example:

console.log(5 > 3); // Outputs: true
console.log(5 < 3); // Outputs: false
console.log(5 >= 5); // Outputs: true
console.log(5 <= 3); // Outputs: false

12. Basic Expressions

Expressions are combinations of values, variables, operators, and functions that evaluate to a single value. An expression can be as simple as a single value or variable or as complex as a combination of various operations.

Examples:

Example:

let x = 10;
let y = 5;

let result = (x + y) * 2; // Outputs: 30
console.log(result);

Summary:

+=`, etc.).

1. Numbers

In JavaScript, numbers are a primitive data type that represent both integer and floating-point values. JavaScript uses the IEEE 754 standard for representing numbers, meaning all numbers are stored as 64-bit floating-point values. This allows for a wide range of numeric values but comes with some limitations regarding precision.

Key Characteristics:

Example:

let a = 42; // Integer
let b = 3.14; // Floating-point number
let c = Infinity; // Infinity
let d = NaN; // Not-a-Number
console.log(typeof a); // Outputs: number
console.log(typeof b); // Outputs: number
console.log(c); // Outputs: Infinity
console.log(d); // Outputs: NaN

2. Number Object

The Number object is a built-in JavaScript object that provides methods and properties for working with numbers. It allows for more complex number manipulations and conversions.

Key Properties:

Key Methods:

Example:

console.log(Number.MAX_VALUE); // Outputs: 1.7976931348623157e+308
console.log(Number.MIN_VALUE); // Outputs: 5e-324
console.log(Number.isFinite(42)); // Outputs: true
console.log(Number.isFinite(Infinity)); // Outputs: false
console.log(Number.parseFloat("3.14")); // Outputs: 3.14
console.log(Number.parseInt("10", 2)); // Outputs: 2 (binary to decimal)

3. Math Object

The Math object is a built-in object in JavaScript that provides a collection of mathematical functions and constants. It does not require instantiation and is always available.

Key Properties:

Key Methods:

Example:

console.log(Math.PI); // Outputs: 3.141592653589793
console.log(Math.abs(-5)); // Outputs: 5
console.log(Math.ceil(4.3)); // Outputs: 5
console.log(Math.floor(4.7)); // Outputs: 4
console.log(Math.round(4.5)); // Outputs: 5
console.log(Math.random()); // Outputs a random number between 0 and 1
console.log(Math.max(1, 2, 3)); // Outputs: 3
console.log(Math.min(1, 2, 3)); // Outputs: 1

4. BigInts

BigInt is a built-in object in JavaScript that allows you to represent and manipulate whole numbers larger than the maximum safe integer limit of the Number type (Number.MAX_SAFE_INTEGER, which is 2^53 - 1). BigInts are useful for working with large numbers that exceed the limitations of standard number representation.

Key Characteristics:

Example:

const bigInt1 = BigInt(123456789012345678901234567890);
const bigInt2 = 123456789012345678901234567890n;

console.log(bigInt1); // Outputs: 123456789012345678901234567890n
console.log(bigInt2); // Outputs: 123456789012345678901234567890n
console.log(bigInt1 + bigInt2); // Outputs: 246913578024691357802469135780n

// Mixing BigInt with Number
let num = 10;
// console.log(bigInt1 + num); // Error: Cannot mix BigInt and other types
console.log(bigInt1 + BigInt(num)); // Outputs: 123456789012345678901234567900n

5. Date Object

The Date object in JavaScript is a built-in object used for handling dates and times. It provides various methods to create, manipulate, and format dates.

Creating a Date Object:

You can create a Date object in several ways:

Example:

let currentDate = new Date(); // Current date and time
let specificDate = new Date("2024-10-15"); // Specific date
let anotherDate = new Date(2024, 9, 15); // Year, month (0-indexed), day

console.log(currentDate); // Outputs the current date and time
console.log(specificDate); // Outputs: Tue Oct 15 2024 ...
console.log(anotherDate); // Outputs: Tue Oct 15 2024 ...

Key Methods:

Example:

let date = new Date("2024-10-15");
console.log(date.getFullYear()); // Outputs: 2024
console.log(date.getMonth()); // Outputs: 9 (October)
console.log(date.getDate()); // Outputs: 15
console.log(date.getHours()); // Outputs: 0 (midnight)
console.log(date.getMinutes()); // Outputs: 0
console.log(date.getSeconds()); // Outputs: 0
console.log(date.getTime()); // Outputs: Milliseconds since epoch

Formatting Dates:

You can format dates in various ways using the Date object’s methods or by converting the date to a string using the toDateString(), toTimeString(), or toISOString() methods.

Example:

console.log(date.toDateString()); // Outputs: Tue Oct 15 2024
console.log(date.toTimeString()); // Outputs: 00:00:00 GMT...
console.log(date.toISOString()); // Outputs: 2024-10-15T00:00:00.000Z

Summary:

Strings

In JavaScript, a string is a sequence of characters used to represent text. Strings are a fundamental data type in JavaScript, and they can be created using single quotes ('), double quotes ("), or backticks (`).

Characteristics of Strings:

Creating Strings:

Strings can be created in several ways:

let singleQuoted = "Hello, World!";
let doubleQuoted = "Hello, World!";
let backtickQuoted = `Hello, World!`;

console.log(singleQuoted); // Outputs: Hello, World!
console.log(doubleQuoted); // Outputs: Hello, World!
console.log(backtickQuoted); // Outputs: Hello, World!

String Methods:

JavaScript provides a variety of built-in methods for manipulating strings. Some of the most commonly used methods include:

Example:

let message = "   Hello, World!   ";

console.log(message.length); // Outputs: 15
console.log(message.trim()); // Outputs: "Hello, World!"
console.log(message.toUpperCase()); // Outputs: "   HELLO, WORLD!   "
console.log(message.indexOf("World")); // Outputs: 8
console.log(message.replace("World", "JavaScript")); // Outputs: "   Hello, JavaScript!   "
console.log(message.split(",")); // Outputs: [ '   Hello', ' World!   ' ]
console.log(message.includes("Hello")); // Outputs: true

Internationalization (i18n)

Internationalization (often abbreviated as i18n) is the process of designing software applications to support multiple languages and regional differences. In JavaScript, this involves handling strings, numbers, currencies, and dates in a way that accommodates various cultural conventions.

Importance of Internationalization:

Internationalization Features in JavaScript:

JavaScript provides several built-in objects and methods to assist with internationalization:

  1. Intl Object: The Intl object is a namespace that provides language-sensitive functionality, such as number formatting, date and time formatting, and string comparison.

    • Number Formatting: The Intl.NumberFormat object allows you to format numbers based on locale.

      let number = 1234567.89;
      let formatter = new Intl.NumberFormat("en-US");
      console.log(formatter.format(number)); // Outputs: "1,234,567.89"
      
      formatter = new Intl.NumberFormat("de-DE");
      console.log(formatter.format(number)); // Outputs: "1.234.567,89"
      
    • Date and Time Formatting: The Intl.DateTimeFormat object is used for formatting dates and times.

      let date = new Date();
      let dateFormatter = new Intl.DateTimeFormat("en-US");
      console.log(dateFormatter.format(date)); // Outputs: e.g., "10/15/2024"
      
      dateFormatter = new Intl.DateTimeFormat("fr-FR");
      console.log(dateFormatter.format(date)); // Outputs: e.g., "15/10/2024"
      
    • Collation (String Comparison): The Intl.Collator object provides methods to compare strings based on locale-specific rules.

      let collator = new Intl.Collator("en-US");
      console.log(collator.compare("a", "b")); // Outputs: -1 (meaning 'a' comes before 'b')
      
  2. Locale-Sensitive Functions: JavaScript also includes several functions that automatically adapt to the user’s locale, such as toLocaleString(), toLocaleDateString(), and toLocaleTimeString() for numbers and dates.

    Example:

    let num = 1234567.89;
    console.log(num.toLocaleString("en-US")); // Outputs: "1,234,567.89"
    console.log(num.toLocaleString("de-DE")); // Outputs: "1.234.567,89"
    
    let today = new Date();
    console.log(today.toLocaleDateString("en-US")); // Outputs: e.g., "10/15/2024"
    console.log(today.toLocaleDateString("fr-FR")); // Outputs: e.g., "15/10/2024"
    

Summary

Regular Expressions in JavaScript

Regular expressions (regex) are powerful tools used for matching patterns in strings. They are essential for searching, validating, and manipulating text based on specific patterns. JavaScript provides a robust way to work with regular expressions through its built-in RegExp object and regex literals.


1. Creating a Regular Expression

There are two ways to create a regular expression in JavaScript:

Example:

// Using a regex literal
let regexLiteral = /abc/;

// Using the RegExp constructor
let regexConstructor = new RegExp("abc");

2. Writing a Regular Expression Pattern

A regular expression pattern consists of characters that specify the search criteria. Here are some common elements used in regex patterns:

Example:

let pattern = /^[a-zA-Z0-9]{5,10}$/; // Matches a string that is 5 to 10 characters long and contains only letters and numbers.

3. Using Regular Expressions in JavaScript

Regular expressions can be used with various string methods and the RegExp object. Some common methods include:

Example:

let str = "Hello, World!";

// Using test()
let regex = /hello/i; // 'i' flag for case insensitive
console.log(regex.test(str)); // Outputs: true

// Using exec()
let result = regex.exec(str);
console.log(result); // Outputs: [ 'hello', index: 0, input: 'Hello, World!', groups: undefined ]

// Using match()
console.log(str.match(/World/)); // Outputs: [ 'World', index: 7, input: 'Hello, World!', groups: undefined ]

// Using replace()
let newStr = str.replace(/World/, "JavaScript");
console.log(newStr); // Outputs: Hello, JavaScript!

// Using search()
console.log(str.search(/World/)); // Outputs: 7

// Using split()
let splitStr = str.split(/[\s,]+/); // Splits on whitespace and commas
console.log(splitStr); // Outputs: [ 'Hello', 'World!' ]

4. Examples

Here are some practical examples of using regular expressions in JavaScript:


5. Tools

Several tools can assist in creating, testing, and debugging regular expressions:


Summary