DEV Community

Cover image for Web Dev Day 6: JavaScript Guide
Bhupesh Kumar
Bhupesh Kumar

Posted on • Edited on

Web Dev Day 6: JavaScript Guide

What is a Variable?

A variable in JavaScript is a named container that holds a value. It allows us to store, update, and retrieve data dynamically.

JavaScript provides three ways to declare variables:

  • var (old syntax)
  • let (modern)
  • const (for constants)
let name = "Bhupesh"; 
const age = 25; 
var country = "Canada";
Enter fullscreen mode Exit fullscreen mode

Data Types in JS

JavaScript has primitive and non-primitive data types.

Primitive Data Types

These are immutable and stored directly in memory:

  • String"Hello"
  • Number42
  • Booleantrue, false
  • Undefinedlet x; (not assigned)
  • Nulllet y = null; (empty value)
  • BigInt12345678901234567890123n
  • SymbolSymbol('unique')

Non-Primitive Data Types

These are reference types and stored as objects:

  • Objects{ name: "John", age: 30 }
  • Arrays["apple", "banana", "cherry"]
  • Functions
  function greet() { 
      console.log("Hello!"); 
  }
Enter fullscreen mode Exit fullscreen mode

Numbers in JavaScript

JavaScript has only one type for numbers: floating-point numbers.

Example:

let a = 10;       // Integer
let b = 10.5;     // Float
let c = 1e3;      // Scientific notation (1000)
Enter fullscreen mode Exit fullscreen mode

Special Number Values:

  • Infinity → console.log(1 / 0);
  • -Infinity → console.log(-1 / 0);
  • NaN (Not-a-Number) → console.log("hello" * 2);

Operations in JavaScript

JavaScript supports the following operators:

  • Arithmetic Operators: +, -, *, /, %, **
  • Comparison Operators: ==, ===, !=, !==, >, <, >=, <=
  • Logical Operators: &&, ||, !
  • Bitwise Operators: &, |, ^, ~, <<, >>
  • Ternary Operator: condition ? trueValue : falseValue

Example:

console.log(5 + 2);  // 7
console.log(10 / 2); // 5
console.log(3 ** 2); // 9 (Exponentiation)
Enter fullscreen mode Exit fullscreen mode

NaN in JavaScript

NaN stands for "Not-a-Number." It occurs when an operation does not yield a valid number.

Example:

console.log("hello" * 2); // NaN
console.log(0 / 0);       // NaN
Enter fullscreen mode Exit fullscreen mode

Operator Precedence in JavaScript

Operator precedence determines how expressions are evaluated in JavaScript.

Operator Type Operators Precedence
Parentheses () Highest
Exponentiation ** 2
Multiplication, Division, Modulus *, /, % 3
Addition, Subtraction +, - 4
Relational <, >, <=, >= 5
Equality ==, ===, !=, !== 6
Logical AND && 7
Logical OR `

Example:

{% raw %}

console.log(5 + 3 * 2);    // 11 (Multiplication first)
console.log((5 + 3) * 2);  // 16 (Parentheses first)
Enter fullscreen mode Exit fullscreen mode

let Keyword

The let keyword was introduced in ES6. It has the following properties:

  • Block-scoped (Only accessible within the block {} it is declared in).
  • Can be reassigned but cannot be redeclared within the same scope.

Example:

let x = 10;
x = 20;  // ✅ Allowed

let x = 30; // ❌ Error (Cannot redeclare)
Enter fullscreen mode Exit fullscreen mode

const Keyword

The const keyword has the following properties:

  • Block-scoped (Like let, it is confined within the block {} it is declared in).
  • Cannot be reassigned after declaration.
  • Cannot be redeclared in the same scope.
  • Must be initialized when declared.

Example:

const PI = 3.1416;
PI = 3.14; // ❌ Error (Cannot reassign)
Enter fullscreen mode Exit fullscreen mode

var Keyword (Old Syntax)

The var keyword is function-scoped, meaning:

  • Can be redeclared and reassigned.
  • Not recommended in modern JavaScript due to scoping issues.

Example:

var name = "Alice";
var name = "Bob";  // ✅ Allowed (but not good practice)
Enter fullscreen mode Exit fullscreen mode

Assignment Operators in JavaScript

Assignment operators are used to assign values to variables.

Operator Example Meaning
= x = 5 Assigns 5 to x
+= x += 2 x = x + 2
-= x -= 3 x = x - 3
*= x *= 4 x = x * 4
/= x /= 5 x = x / 5
%= x %= 2 x = x % 2

Unary Operators in JavaScript

Unary operators operate on a single operand.

Operator Description Example Output
+ (Unary plus) Converts value to a number +"42" 42
- (Unary minus) Negates a number -10 -10
++ (Increment) Increases value by 1 let x = 1; x++ 2
-- (Decrement) Decreases value by 1 let y = 2; y-- 1
typeof Returns the type of a value typeof 42 "number"

Identifiers Rule in JavaScript

Identifiers are names used for variables, functions, and objects. JavaScript follows these rules:

Valid Identifiers:

  • Can include letters, digits, underscores (_), and dollar signs ($).
  • Cannot start with a digit.
  • JavaScript is case-sensitive.

Valid Identifiers:

let firstName;
let _privateVar;
let $price;
Enter fullscreen mode Exit fullscreen mode

Invalid Identifiers in JavaScript

JavaScript has strict rules for naming identifiers. The following are invalid identifiers:

let 2name;    // ❌ Error (Cannot start with a digit)
let my-name;  // ❌ Error (Hyphens are not allowed)
Enter fullscreen mode Exit fullscreen mode

camelCase Naming Convention in JavaScript

JavaScript follows the camelCase naming convention, where:

  • The first word is lowercase.
  • Each subsequent word starts with an uppercase letter.

Example:

let userName;
let totalAmount;
let firstName;
Enter fullscreen mode Exit fullscreen mode

Boolean in JavaScript

A Boolean represents either true or false.

Example:

let isLoggedIn = true;
let hasDiscount = false;
Enter fullscreen mode Exit fullscreen mode

Boolean Conversion:

console.log(Boolean(0));        // false
console.log(Boolean("Hello"));  // true
Enter fullscreen mode Exit fullscreen mode

What is TypeScript?

TypeScript is a superset of JavaScript that:

  • Adds static typing to JavaScript.
  • Prevents runtime errors by catching issues during development.
  • Compiles to JavaScript, making it compatible with all JS environments.

Static vs. Dynamic Typing:

  • TypeScript is statically typed, meaning variable types are checked at compile time.
  • JavaScript is dynamically typed, meaning types are inferred at runtime.

Example:

let age: number = 25;  // TypeScript
Enter fullscreen mode Exit fullscreen mode

String in JavaScript

A string is a sequence of characters enclosed in quotes ("" or '').

Example:

let greeting = "Hello, World!";
console.log(greeting.length); // 13
Enter fullscreen mode Exit fullscreen mode

String Indices in JavaScript

Each character in a string has an index, starting from 0.

Example:

let str = "JavaScript";
console.log(str[0]);             // "J"
console.log(str[str.length - 1]); // "t"
Enter fullscreen mode Exit fullscreen mode

String Concatenation in JavaScript

Concatenation is the process of joining two or more strings together.

Methods of Concatenation:

  1. Using the + operator (Most common)
  2. Using the .concat() method (Less common)

Example:

console.log("Hello" + " " + "World"); // "Hello World"
console.log("Hi".concat(" there!"));  // "Hi there!"
Enter fullscreen mode Exit fullscreen mode

null and undefined in JavaScript

In JavaScript, null and undefined are special values that represent the absence of a value, but they have different meanings.


undefined

  • A variable is undefined when it is declared but not assigned a value.
  • It is the default value of an uninitialized variable.

Example:

let x;
console.log(x); // undefined
Enter fullscreen mode Exit fullscreen mode

null in JavaScript

In JavaScript, null represents an intentional absence of any object value.

  • It signifies that a variable intentionally holds no value.
  • null must be explicitly assigned.

Example:

let y = null;
console.log(y); // null
Enter fullscreen mode Exit fullscreen mode

console.log() in JavaScript

console.log() is a built-in JavaScript method used to print output to the console.


Usage:

console.log("Hello, World!"); // Output: Hello, World!
console.log(5 + 3);          // Output: 8
Enter fullscreen mode Exit fullscreen mode

Linking a JavaScript File to HTML

To use JavaScript in an HTML file, you need to link an external JavaScript file using the <script> tag.


How to Link an External JavaScript File

  1. Create an HTML file (index.html)
  2. Create a JavaScript file (script.js)
  3. Link the JavaScript file in the HTML file

Example:

index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Linking</title>
</head>
<body>
    <h1>Welcome to JavaScript</h1>

    <!-- Linking JavaScript -->
    <script src="script.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Template Literals in JavaScript

Template literals (also called template strings) allow for easier string manipulation using backticks () instead of quotes.


Syntax:

This is a template literal

String Interpolation
Use ${} to insert variables or expressions directly into a string.

let name = "Alice";
let age = 25;

console.log(`My name is ${name} and I am ${age} years old.`);
// Output: My name is Alice and I am 25 years old.
Enter fullscreen mode Exit fullscreen mode

Multi-line Strings
Template literals allow multi-line strings without needing \n.

let message = `This is line 1
This is line 2
This is line 3`;

console.log(message);
Enter fullscreen mode Exit fullscreen mode

Expression Evaluation
You can use expressions inside ${}.

let a = 5, b = 10;

console.log(`The sum of ${a} and ${b} is ${a + b}.`);
// Output: The sum of 5 and 10 is 15.
Enter fullscreen mode Exit fullscreen mode

Operators in JavaScript

JavaScript supports various operators to perform operations on variables and values.


Arithmetic Operators

Used to perform mathematical operations.

Operator Description Example Output
+ Addition 5 + 3 8
- Subtraction 10 - 4 6
* Multiplication 2 * 5 10
/ Division 10 / 2 5
% Modulus (Remainder) 10 % 3 1
** Exponentiation (Power) 3 ** 2 9

Example:

console.log(5 + 2);  // 7
console.log(10 / 2); // 5
console.log(3 ** 2); // 9 (Exponentiation)
Enter fullscreen mode Exit fullscreen mode

Assignment Operators in JavaScript

Assignment operators are used to assign values to variables.

List of Assignment Operators

Operator Example Meaning
= x = 5 Assigns 5 to x
+= x += 2 x = x + 2
-= x -= 3 x = x - 3
*= x *= 4 x = x * 4
/= x /= 5 x = x / 5
%= x %= 2 x = x % 2

🔹 Example Usage

let x = 10;
x += 5;   // x = 15
x *= 2;   // x = 30
console.log(x); // Output: 30
Enter fullscreen mode Exit fullscreen mode

Comparison Operators in JavaScript

Comparison operators are used to compare values and return a Boolean (true or false).


List of Comparison Operators

Operator Description Example Output
== Equal to (loose comparison) 5 == "5" true
=== Strictly equal (Type + Value) 5 === "5" false
!= Not equal 5 != "5" false
!== Strictly not equal 5 !== "5" true
> Greater than 10 > 5 true
< Less than 3 < 5 true
>= Greater than or equal to 10 >= 10 true
<= Less than or equal to 3 <= 5 true

Example Usage

console.log(5 == "5");  // true (loose comparison)
console.log(5 === "5"); // false (strict comparison)
Enter fullscreen mode Exit fullscreen mode

5 == '5' in JavaScript

In JavaScript, the expression 5 == '5' evaluates to true.

This happens because == is the loose equality operator, which performs type coercion before comparing values.


Loose Equality (==) vs. Strict Equality (===)

Expression Result Explanation
5 == '5' true Loose equality (==) converts types before comparison. The string '5' is converted to a number 5.
5 === '5' false Strict equality (===) does not perform type conversion. Since 5 (number) and '5' (string) have different types, the result is false.

Example Usage

console.log(5 == '5');  // true (loose comparison with type coercion)
console.log(5 === '5'); // false (strict comparison without type coercion)
Enter fullscreen mode Exit fullscreen mode

Logical Operators in JavaScript

Logical operators are used to combine conditions and return a Boolean (true or false).


List of Logical Operators

Operator Description Example Output
&& Logical AND true && false false
` ` Logical OR
! Logical NOT !true false

Example Usage

console.log(true && false);  // false
console.log(true || false);  // true
console.log(!true);          // false
Enter fullscreen mode Exit fullscreen mode

Bitwise Operators in JavaScript

Bitwise operators are used to perform binary calculations by manipulating bits directly.


List of Bitwise Operators

Operator Description Example
& AND 5 & 1
' ' OR
^ XOR 5 ^ 1
~ NOT ~5
<< Left shift 5 << 1
>> Right shift 5 >> 1

Example Usage

console.log(5 & 1);  // 1  (AND operation)
console.log(5 | 1);  // 5  (OR operation)
console.log(5 ^ 1);  // 4  (XOR operation)
console.log(~5);     // -6 (NOT operation)
console.log(5 << 1); // 10 (Left shift)
console.log(5 >> 1); // 2  (Right shift)
Enter fullscreen mode Exit fullscreen mode

Ternary Operator in JavaScript

The ternary operator is a shorthand for if...else statements.

It allows writing conditional logic in a compact and readable way.

Syntax:

condition ? trueValue : falseValue;
Enter fullscreen mode Exit fullscreen mode

Comparisons for Non-Numbers in JavaScript

JavaScript allows comparisons not only for numbers but also for strings, Booleans, and other data types.

When comparing non-numeric values, JavaScript applies type conversion rules.

Comparing Strings

  • JavaScript compares strings lexicographically (alphabetical order) based on Unicode values.
  • Uppercase letters (A-Z) come before lowercase letters (a-z).

Example:

console.log("apple" > "banana");  // false (because "a" comes before "b")
console.log("Zoo" > "apple");     // false (uppercase "Z" comes before lowercase "a")
console.log("Hello" > "hello");   // false (uppercase "H" < lowercase "h")
Enter fullscreen mode Exit fullscreen mode

Comparing Booleans in JavaScript

In JavaScript, Booleans (true and false) are converted to numbers when used in comparisons:

  • false is treated as 0
  • true is treated as 1

Example:

console.log(true > false);  // true (1 > 0)
console.log(false == 0);    // true (false → 0)
console.log(true == 1);     // true (true → 1)
console.log(false < true);  // true (0 < 1)
Enter fullscreen mode Exit fullscreen mode

Comparing null and undefined in JavaScript

JavaScript treats null and undefined differently in comparisons.

Example:

console.log(null == undefined);  // true (special case)
console.log(null === undefined); // false (strict comparison)
console.log(null > 0);           // false
console.log(null == 0);          // false
console.log(null >= 0);          // true (strange behavior)
console.log(undefined > 0);      // false
console.log(undefined == 0);     // false
console.log(undefined >= 0);     // false
Enter fullscreen mode Exit fullscreen mode

Comparing Objects in JavaScript

In JavaScript, objects are not directly comparable.

They are compared by reference, not by value.

Example:

let obj1 = { name: "Alice" };
let obj2 = { name: "Alice" };

console.log(obj1 == obj2);  // false (different memory references)
console.log(obj1 === obj2); // false (even though they look the same)
Enter fullscreen mode Exit fullscreen mode

Conditional Statements in JavaScript

Conditional statements allow a program to make decisions based on conditions.

JavaScript provides multiple ways to handle conditions.

if Statement

The if statement executes code only if a condition is true.

Syntax:

if (condition) {
    // Code to execute if the condition is true
}
Enter fullscreen mode Exit fullscreen mode

if...else Statement in JavaScript

The if...else statement executes one block of code if the condition is true and another block if it is false.

Example:

let age = 16;

if (age >= 18) {
    console.log("You can vote.");
} else {
    console.log("You cannot vote.");
}
// Output: "You cannot vote."
Enter fullscreen mode Exit fullscreen mode

if...else if...else Statement in JavaScript

The if...else if...else statement is used when multiple conditions need to be checked sequentially.

JavaScript evaluates each condition in order, and the first condition that evaluates to true gets executed.

Example:

let score = 85;

if (score >= 90) {
    console.log("Grade: A");
} else if (score >= 80) {
    console.log("Grade: B");
} else if (score >= 70) {
    console.log("Grade: C");
} else {
    console.log("Grade: F");
}
// Output: "Grade: B"
Enter fullscreen mode Exit fullscreen mode

Ternary Operator (? :) in JavaScript

The ternary operator is a shorter and more concise way to write an if...else statement.

It is useful for simple conditions where you want to assign a value or execute a statement based on a condition.

Syntax:

condition ? trueValue : falseValue;
Enter fullscreen mode Exit fullscreen mode

switch Statement in JavaScript

The switch statement is used when a variable needs to be compared against multiple values.

It is often used as a cleaner alternative to multiple if...else if...else statements.

Syntax:

switch (expression) {
    case value1:
        // Code to execute if expression === value1
        break;
    case value2:
        // Code to execute if expression === value2
        break;
    default:
        // Code to execute if no cases match
}
Enter fullscreen mode Exit fullscreen mode

Nested if...else in JavaScript

A nested if...else statement is an if...else inside another if or else.

It allows checking multiple conditions in a hierarchical manner.

Syntax:

if (condition1) {
    if (condition2) {
        // Code to execute if both conditions are true
    } else {
        // Code to execute if condition1 is true but condition2 is false
    }
} else {
    // Code to execute if condition1 is false
}
Enter fullscreen mode Exit fullscreen mode

Logical Operators in JavaScript

Logical operators are used to combine multiple conditions and return a Boolean (true or false).

They are essential for making decisions in conditional statements.

List of Logical Operators

Operator Description Example Output
&& Logical AND true && false false
` ` Logical OR
! Logical NOT !true false

Example Usage

console.log(true && false);  // false
console.log(true || false);  // true
console.log(!true);          // false
Enter fullscreen mode Exit fullscreen mode

Truthy and Falsy Values in JavaScript

In JavaScript, every value is either "truthy" or "falsy" when evaluated in a Boolean context.

  • Truthy values behave like true when used in a condition.
  • Falsy values behave like false when used in a condition.

Falsy Values

A falsy value is a value that evaluates to false in a Boolean context.

JavaScript has exactly 8 falsy values:

Falsy Value Description
false Boolean false itself
0 Number zero
-0 Negative zero
0n BigInt zero
"" Empty string
null Absence of a value
undefined Uninitialized variable
NaN Not-a-Number

Example:

if (0) {
    console.log("Truthy");
} else {
    console.log("Falsy");
}
// Output: "Falsy"

if ("") {
    console.log("Truthy");
} else {
    console.log("Falsy");
}
// Output: "Falsy"
Enter fullscreen mode Exit fullscreen mode

Truthy Values in JavaScript

A truthy value is any value that is not falsy.

In JavaScript, all values are truthy unless they are in the list of falsy values (false, 0, "", null, undefined, NaN, etc.).

Common Truthy Values

Truthy Value Example
Non-empty strings "hello", "false", "0"
Numbers except 0 42, -1, 3.14
Non-empty arrays []
Non-empty objects {}
Functions function() {}
Special values " " (space), "0" (string zero)

Example:

if ("Hello") {
    console.log("Truthy");
} else {
    console.log("Falsy");
}
// Output: "Truthy"

if (42) {
    console.log("Truthy");
} else {
    console.log("Falsy");
}
// Output: "Truthy"
Enter fullscreen mode Exit fullscreen mode

Alerts and Prompts in JavaScript

JavaScript provides built-in methods to interact with users using alerts, prompts, and confirmations.

alert()

The alert() method displays a pop-up message to the user.

Syntax:

alert("This is an alert!");

prompt() in JavaScript

The prompt() method is used to ask the user for input via a pop-up dialog.

It returns the user input as a string, or null if the user clicks "Cancel".

Syntax:

let userInput = prompt("Enter your name:");

confirm() in JavaScript

The confirm() method displays a pop-up asking for user confirmation.

It returns:

  • true if the user clicks "OK".
  • false if the user clicks "Cancel".

Syntax:

let result = confirm("Are you sure?");

String Methods in JavaScript

JavaScript provides many built-in methods to manipulate and work with strings.

These methods help in searching, replacing, slicing, and modifying strings efficiently.

Common String Methods

Method Description Example
.length Returns the string length "Hello".length5
.toUpperCase() Converts to uppercase "hello".toUpperCase()"HELLO"
.toLowerCase() Converts to lowercase "HELLO".toLowerCase()"hello"
.charAt(index) Returns character at index "JavaScript".charAt(4)"S"
.indexOf("str") Returns first occurrence index "hello".indexOf("l")2
.lastIndexOf("str") Returns last occurrence index "hello".lastIndexOf("l")3
.includes("str") Checks if string contains substring "hello".includes("he")true
.startsWith("str") Checks if string starts with substring "hello".startsWith("he")true
.endsWith("str") Checks if string ends with substring "hello".endsWith("lo")true
.slice(start, end) Extracts substring (end not included) "JavaScript".slice(0, 4)"Java"
.substring(start, end) Similar to .slice(), but can't accept negative indexes "JavaScript".substring(0, 4)"Java"
.substr(start, length) Extracts substring of specific length "JavaScript".substr(4, 6)"Script"
.replace("old", "new") Replaces first match "hello world".replace("world", "JS")"hello JS"
.replaceAll("old", "new") Replaces all occurrences "apple apple".replaceAll("apple", "banana")"banana banana"
.split("delimiter") Splits into an array "one,two,three".split(",")["one", "two", "three"]
.trim() Removes spaces from start & end " hello ".trim()"hello"
.repeat(n) Repeats string n times "Hi ".repeat(3)"Hi Hi Hi "

Example Usage:

let text = "JavaScript is fun!";

console.log(text.length);          // 18
console.log(text.toUpperCase());   // "JAVASCRIPT IS FUN!"
console.log(text.toLowerCase());   // "javascript is fun!"
console.log(text.charAt(0));       // "J"
console.log(text.includes("fun")); // true
console.log(text.startsWith("Java")); // true
console.log(text.endsWith("fun!"));  // true
console.log(text.slice(0, 10));     // "JavaScript"
console.log(text.replace("fun", "awesome")); // "JavaScript is awesome!"
console.log(text.split(" "));      // ["JavaScript", "is", "fun!"]
console.log("  hello  ".trim());   // "hello"
Enter fullscreen mode Exit fullscreen mode

trim() Method in JavaScript

The trim() method removes whitespace from both ends of a string (start & end), without affecting the spaces inside the string.

Syntax:

string.trim();

Enter fullscreen mode Exit fullscreen mode

Strings are Immutable in JavaScript

In JavaScript, strings are immutable, meaning they cannot be changed after they are created.

Any operation that appears to modify a string actually returns a new string, leaving the original string unchanged.

Example:

let str = "Hello";
str[0] = "J";  // Attempt to change the first letter
console.log(str);  
// Output: "Hello" (unchanged)
Enter fullscreen mode Exit fullscreen mode

String Methods with Arguments in JavaScript

Many string methods in JavaScript accept arguments, allowing you to manipulate strings dynamically.

Common String Methods with Arguments

Method Description Example
.charAt(index) Returns the character at a specific index "JavaScript".charAt(4)"S"
.slice(start, end) Extracts a substring (end not included) "JavaScript".slice(0, 4)"Java"
.substring(start, end) Extracts substring (similar to .slice()) "JavaScript".substring(4, 10)"Script"
.substr(start, length) Extracts a substring of specific length "JavaScript".substr(4, 6)"Script"
.replace("old", "new") Replaces the first occurrence "hello world".replace("world", "JS")"hello JS"
.replaceAll("old", "new") Replaces all occurrences "apple apple".replaceAll("apple", "banana")"banana banana"
.split("delimiter") Splits into an array based on a delimiter "one,two,three".split(",")["one", "two", "three"]
.repeat(n) Repeats the string n times "Hi ".repeat(3)"Hi Hi Hi "

indexOf() Method in JavaScript

The indexOf() method returns the first occurrence index of a specified substring within a string.

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

Syntax:

string.indexOf(searchValue, startIndex);

Method Chaining in JavaScript

Method chaining is a technique in JavaScript where multiple methods are called on an object in a single statement.

This makes the code cleaner and more readable.

Example:

let text = "  JavaScript Method Chaining  ";

let result = text.trim().toUpperCase().replace("CHAINING", "MAGIC");

console.log(result);
// Output: "JAVASCRIPT METHOD MAGIC"
Enter fullscreen mode Exit fullscreen mode

slice() Method in JavaScript

The slice() method extracts a portion of a string and returns a new string without modifying the original string.

Syntax:

string.slice(startIndex, endIndex);

replace() Method

The replace() method searches for a specified substring and replaces it with a new value.

By default, it only replaces the first occurrence unless you use replaceAll().

Syntax:

string.replace(searchValue, newValue);

repeat() Method in JavaScript

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

Syntax:

string.repeat(n);

Array Data Structure in JavaScript

An array in JavaScript is a data structure that allows storing multiple values in a single variable.

It can hold elements of different data types, including numbers, strings, objects, and even other arrays.

Creating an Array

Using Square Brackets [] (Most Common)

let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits);
// Output: ["Apple", "Banana", "Cherry"]
Enter fullscreen mode Exit fullscreen mode

Creating an Array Using new Array() in JavaScript

JavaScript allows you to create arrays using the new Array() constructor.

This method is less commonly used than square brackets [], but it's useful in certain cases.

Syntax:

let arrayName = new Array(element1, element2, ...);

Mixed Arrays in JavaScript

A mixed array in JavaScript is an array that contains multiple data types, including:

  • Numbers
  • Strings
  • Booleans
  • Objects
  • Arrays
  • Functions

Creating a Mixed Array

JavaScript allows arrays to hold multiple data types in the same array.

let mixedArray = [42, "Hello", true, { name: "Alice" }, [1, 2, 3], function() { return "Hi!"; }];

console.log(mixedArray);
// Output: [42, "Hello", true, {name: "Alice"}, [1, 2, 3], function]
Enter fullscreen mode Exit fullscreen mode

Accessing Characters in a String Inside an Array

In JavaScript, when you store a string inside an array, you can access individual characters using indexing.

Example:

let arr = ["bhupesh", 1, 2];

console.log(arr[0][0]); // "b"
console.log(arr[0][1]); // "h"
console.log(arr[0][2]); // "u"
Enter fullscreen mode Exit fullscreen mode

Arrays are Mutable in JavaScript

In JavaScript, arrays are mutable, meaning their elements can be modified, added, or removed without changing their reference in memory.

Example: Modifying an Array

let numbers = [1, 2, 3, 4];

numbers[1] = 99;  // Changing the value at index 1

console.log(numbers);
// Output: [1, 99, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Array Methods in JavaScript

JavaScript provides various built-in array methods to manipulate and process arrays efficiently.

Common Array Methods

Method Description Example
.push(value) Adds an element to the end arr.push("Mango")
.pop() Removes the last element arr.pop()
.unshift(value) Adds an element to the beginning arr.unshift("First")
.shift() Removes the first element arr.shift()
.indexOf(value) Returns index of value arr.indexOf("Apple")
.includes(value) Checks if array contains value arr.includes("Banana")true
.slice(start, end) Returns a portion of an array arr.slice(1, 3)
.splice(start, deleteCount, item) Removes or adds elements arr.splice(2, 1, "New")
.reverse() Reverses the array arr.reverse()
.sort() Sorts array alphabetically arr.sort()
.concat(arr2) Combines two arrays arr.concat(arr2)
.join(separator) Converts array to string arr.join(", ")
.map(fn) Creates a new array by applying function arr.map(x => x * 2)
.filter(fn) Returns elements that match a condition arr.filter(x => x > 5)
.reduce(fn, initialValue) Reduces array to a single value arr.reduce((sum, num) => sum + num, 0)
.forEach(fn) Iterates over each element arr.forEach(x => console.log(x))

Example Usage:

Adding & Removing Elements

let fruits = ["Apple", "Banana", "Cherry"];

fruits.push("Mango");  // Adds to the end
fruits.unshift("Mango"); // Adds to the beginning

console.log(fruits);
// Output: ["Mango", "Apple", "Banana", "Cherry"]
Enter fullscreen mode Exit fullscreen mode

Extracting a Portion of an Array (slice())

The slice() method extracts a portion of an array without modifying the original array.

Example:

let colors = ["Red", "Green", "Blue", "Yellow"];

let slicedColors = colors.slice(1, 3);
console.log(slicedColors);
// Output: ["Green", "Blue"]
Enter fullscreen mode Exit fullscreen mode

Modifying an Array Using splice() in JavaScript

The splice() method allows you to add, remove, or replace elements in an array by modifying the original array.

Syntax:

array.splice(startIndex, deleteCount, item1, item2, ...);
Enter fullscreen mode Exit fullscreen mode

Transforming an Array Using map() in JavaScript

The map() method creates a new array by applying a function to each element of an existing array.

It does not modify the original array.

Syntax:

array.map(function(element, index, array) {
    return modifiedElement;
});
Enter fullscreen mode Exit fullscreen mode

Filtering an Array (filter())

The filter() method returns a new array containing only elements that match a specified condition.

Syntax:

array.filter(function(element, index, array) {
    return condition;
});
Enter fullscreen mode Exit fullscreen mode

Reducing an Array Using reduce() in JavaScript

The reduce() method reduces an array to a single value by applying a function.

It is commonly used for summation, finding maximum/minimum values, and more.

Syntax:

array.reduce(function(accumulator, element, index, array) {
    return newAccumulator;
}, initialValue);
Enter fullscreen mode Exit fullscreen mode

Issue with Sorting Numbers Using sort() in JavaScript

By default, the sort() method in JavaScript treats numbers as strings,

leading to incorrect sorting results.

Incorrect Sorting (Default Behavior)

Example:

let numbers = [10, 5, 40, 25, 1];

console.log(numbers.sort());
// Output: [1, 10, 25, 40, 5] (Incorrect)
Enter fullscreen mode Exit fullscreen mode
  • The sort() method converts numbers to strings before sorting.
  • When sorting strings, JavaScript compares character by character (lexicographical order).
  • Since "1" comes before "5", "10" is placed before "5".

Array References in JavaScript

In JavaScript, arrays are reference types, meaning they are stored by reference rather than by value.

This affects how arrays are assigned, compared, and modified.

Example: Arrays Are Stored by Reference

let arr1 = [1, 2, 3];
let arr2 = arr1;  // Both variables point to the same array

arr2.push(4);

console.log(arr1); // Output: [1, 2, 3, 4]
console.log(arr2); // Output: [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Constant Arrays in JavaScript (const Arrays)

In JavaScript, arrays declared with const are not immutable.

You cannot reassign a const array, but you can modify its contents.

Declaring a Constant Array

const numbers = [1, 2, 3, 4];

console.log(numbers); 
// Output: [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Nested Arrays in JavaScript (Multi-Dimensional Arrays)

A nested array (or multi-dimensional array) is an array that contains other arrays as elements.

These are useful for representing grids, tables, or hierarchical data structures.

Creating a Nested Array

let matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

console.log(matrix);
// Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Enter fullscreen mode Exit fullscreen mode

for Loops in JavaScript

A for loop in JavaScript is used to execute a block of code multiple times.

It is commonly used for iterating over arrays, objects, and performing repetitive tasks.

Basic Syntax:

for (initialization; condition; iteration) {
    // Code to execute
}
Enter fullscreen mode Exit fullscreen mode

Nested for Loops in JavaScript

A nested for loop is a loop inside another loop.

It is commonly used for working with multi-dimensional arrays, tables, and grids.

Basic Syntax:

for (initialization; condition; iteration) {
    for (initialization; condition; iteration) {
        // Code to execute
    }
}
Enter fullscreen mode Exit fullscreen mode

while Loops in JavaScript

A while loop in JavaScript executes a block of code repeatedly as long as the condition remains true.

It is useful when the number of iterations is not known beforehand.

Basic Syntax:

while (condition) {
    // Code to execute
}
Enter fullscreen mode Exit fullscreen mode

break Keyword in JavaScript

The break keyword in JavaScript is used to exit a loop or switch statement prematurely.

It immediately stops execution and exits the loop.

Basic Syntax:

for (initialization; condition; iteration) {
    if (exitCondition) {
        break;  // Exit the loop
    }
}
Enter fullscreen mode Exit fullscreen mode

Looping Through Arrays in JavaScript

JavaScript provides multiple ways to iterate over arrays using different loops.

Each method has its own use case, performance, and readability.

Using a for Loop (Traditional Way)

The for loop gives full control over iteration using an index.

let fruits = ["Apple", "Banana", "Cherry"];

for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}
Enter fullscreen mode Exit fullscreen mode

/* Output:
Apple
Banana
Cherry
*/

Looping Through Nested Arrays in JavaScript

A nested array (or multi-dimensional array) is an array that contains other arrays as elements.

To iterate over nested arrays, you need nested loops.

Example: Looping Through a 2D Array Using a for Loop

let matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

for (let i = 0; i < matrix.length; i++) {
    for (let j = 0; j < matrix[i].length; j++) {
        console.log(matrix[i][j]);
    }
}

Enter fullscreen mode Exit fullscreen mode

/* Output:
1
2
3
4
5
6
7
8
9
*/

for...of Loop in JavaScript

The for...of loop in JavaScript is used to iterate over iterable objects like:

  • Arrays
  • Strings
  • Maps
  • Sets
  • NodeLists

Basic Syntax:

for (let variable of iterable) {
    // Code to execute
}
Enter fullscreen mode Exit fullscreen mode

Nested for...of Loop in JavaScript

A nested for...of loop is used to iterate over multi-dimensional arrays or nested structures.

It is commonly used when working with nested arrays (2D arrays), objects inside arrays, or matrices.

Basic Syntax:

for (let outerElement of outerIterable) {
    for (let innerElement of innerIterable) {
        // Code to execute
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)