Data Structure and Algorithm
Fundamental

πŸ“˜ JavaScript DSA Series - Fundamentals

πŸ“¦ Variables & Constants

  • Variable: A variable is like a container that stores a value. This value can change (or vary) as the program runs.

    let name = "Alice";
  • Constant: A constant is similar to a variable, but once assigned a value, it cannot be changed.

    const PI = 3.14;
  • const Keyword: Declares a constant whose value can't be reassigned.


🌳 Data Types in JavaScript

JavaScript variables can hold different types of data. These types are categorized into Primitive and Non-Primitive (Reference types).

🧩 Data Types Tree Structure

Data Types
β”œβ”€β”€ Primitive
β”‚   β”œβ”€β”€ Number
β”‚   β”œβ”€β”€ String
β”‚   β”œβ”€β”€ Boolean
β”‚   β”œβ”€β”€ Null
β”‚   β”œβ”€β”€ Undefined
β”‚   β”œβ”€β”€ Symbol
β”‚   └── BigInt
└── Non-Primitive (Reference)
    β”œβ”€β”€ Linear
    β”‚   β”œβ”€β”€ Array
    β”‚   └── Linked List (user-defined)
    └── Non-Linear
        β”œβ”€β”€ Tree (user-defined)
        └── Graph (user-defined)

πŸ”Ή Primitive Data Types

TypeDescriptionExample
NumberRepresents integers and floating-point numberslet age = 25;
StringRepresents textual datalet name = "Alice";
BooleanRepresents true or falselet isLoggedIn = true;
NullRepresents intentional empty valuelet data = null;
UndefinedDeclared variable but not assigned valuelet x; console.log(x);
SymbolUnique identifier (mostly for object keys)const id = Symbol("id");
BigIntLarge integers beyond safe number rangelet big = 123456789012345678901234567890n;

πŸ”Έ Non-Primitive (Reference) Data Types

πŸ”Ή Linear Data Structures

1. Array

  • Stores elements in contiguous memory locations.
  • Elements can be accessed via index.
  • Best for random access.
  • Dynamic in size in JS.
let arr = [10, 20, 30];
console.log(arr[1]); // 20

2. Linked List

  • Consists of nodes, where each node contains data and a reference (pointer) to the next node.
  • Does not store data in contiguous memory.
  • Useful for dynamic insertions and deletions.
// Example representation
let node = {
  data: 10,
  next: {
    data: 20,
    next: null
  }
};

πŸ”Ή Non-Linear Data Structures

1. Tree

  • A hierarchical structure where each node can have multiple children.
  • Common types: Binary Tree, Binary Search Tree (BST).
  • Useful in representing the DOM, folder structures, etc.

2. Graph

  • A set of nodes (vertices) connected by edges.
  • Can be directed/undirected, cyclic/acyclic.
  • Used in routing algorithms, social networks, etc.

⚠️ Note: Tree and Graph are implemented manually in JS using objects/classes.

Operators vs Operands in JavaScript

In JavaScript, operators and operands are fundamental building blocks for performing operations. Understanding them is crucial for writing effective code.

What is an Operator?

An operator is a symbol that performs an operation on one or more operands.

let result = 10 + 5;
// Here, '+' is the operator (performs addition)

What is an Operand?

An operand is the value or variable on which the operator acts.

let result = 10 + 5;
// Here, '10' and '5' are operands

πŸ“š Types of Operators

1️⃣ By Number of Operands

πŸ”Έ Unary Operators

  • Work on a single operand
  • Examples: -x, ++x, !x
let x = 5;
let y = -x;  // Unary minus
let z = !x;  // Logical NOT

πŸ”Έ Binary Operators

  • Work on two operands
  • Most common type
let sum = a + b;  // Addition operator
let product = x * y;  // Multiplication operator

πŸ”Έ Ternary Operator

  • Works on three operands
  • Used as a shorthand for if-else
let result = (age >= 18) ? "Adult" : "Minor";

2️⃣ By Operation Type

πŸ”Έ Arithmetic Operators

OperatorDescriptionExample
+Addition5 + 3 = 8
-Subtraction5 - 3 = 2
*Multiplication5 * 3 = 15
/Division15 / 3 = 5
%Modulus (Remainder)5 % 2 = 1
**Exponentiation2 ** 3 = 8

πŸ”Έ Comparison Operators

OperatorDescriptionExample
==Equal (loose)5 == "5" β†’ true
===Equal (strict)5 === "5" β†’ false
!=Not equal (loose)5 != "6" β†’ true
!==Not equal (strict)5 !== "5" β†’ true
>Greater than5 > 3 β†’ true
<Less than5 < 3 β†’ false
>=Greater than or equal5 >= 5 β†’ true
<=Less than or equal5 <= 3 β†’ false

πŸ”Έ Logical Operators

OperatorDescriptionExample
&&Logical ANDtrue && false β†’ false
||Logical ORtrue || false β†’ true
!Logical NOT!true β†’ false

πŸ”Έ Assignment Operators

OperatorDescriptionExample
=Simple assignmentx = 5
+=Add and assignx += 3 β†’ x = x + 3
-=Subtract and assignx -= 3 β†’ x = x - 3
*=Multiply and assignx *= 3 β†’ x = x * 3
/=Divide and assignx /= 3 β†’ x = x / 3
%=Modulus and assignx %= 3 β†’ x = x % 3

πŸ”Έ Increment & Decrement

OperatorDescriptionExample
++Increment by 1x++ or ++x
--Decrement by 1x-- or --x
// Prefix vs Postfix
let x = 5;
let y = x++;  // y = 5, x = 6
let z = ++x;  // x = 7, z = 7

πŸ”Έ Bitwise Operators

OperatorDescriptionExample
&Bitwise AND5 & 3 β†’ 1
|Bitwise OR5 | 3 β†’ 7
^Bitwise XOR5 ^ 3 β†’ 6
~Bitwise NOT~5 β†’ -6
<<Left shift5 << 1 β†’ 10
>>Right shift5 >> 1 β†’ 2

πŸŽ“ Best Practices

  1. Operator Precedence

    • Use parentheses to make operations clear
    • Don't rely on default operator precedence
    let result = (a + b) * c;  // Clear intention
  2. Type Coercion

    • Use strict equality (===) over loose equality (==)
    • Be explicit about type conversions
    let num = Number("123");  // Explicit conversion
  3. Short-Circuit Evaluation

    • Use && and || for conditional execution
    const name = user && user.name;  // Safe property access
    const defaultName = userName || "Guest";  // Default value

πŸ“ Examples

Practical Usage

// Combining multiple operators
let score = 85;
let passing = 60;
let excellent = 90;
let result = score >= passing ? (score >= excellent ? "Excellent!" : "Pass") : "Fail";
 
// Short-circuit evaluation
function getUser(id) {
    const user = findUser(id);
    return user && user.isActive && user.name;
}
 
// Chaining assignments
let a, b, c;
a = b = c = 5;  // All variables get value 5

⚠️ Common Pitfalls

  1. Unintended Type Coercion

    // Avoid
    if (5 == "5") { ... }  // true
    // Prefer
    if (5 === "5") { ... }  // false
  2. Post/Pre Increment/Decrement Confusion

    let x = 5;
    console.log(x++);  // Shows 5, then x becomes 6
    console.log(++x);  // x becomes 7, then shows 7
  3. Operator Precedence Issues

    // Unclear
    let result = a + b * c;
    // Clear
    let result = a + (b * c);

πŸ”€ ASCII Table (Common Characters)

CharacterASCII CodeDescription
A-Z65-90Uppercase letters
a-z97-122Lowercase letters
0-948-57Digits
Space32Space character
!33Exclamation mark
"34Double quote
#35Hash
$36Dollar sign
%37Percent
&38Ampersand