🚀 Mastering JavaScript & TypeScript: Operators, Conditions & Loops! and data types  🔥 DSA and Algo series Warming up part 1

🚀 Mastering JavaScript & TypeScript: Operators, Conditions & Loops! and data types 🔥 DSA and Algo series Warming up part 1

Operators, Conditions, and Loops in JavaScript & TypeScript

JavaScript and TypeScript share the same syntax for operators, conditions, and loops, with TypeScript adding type safety.


1. Operators in JavaScript & TypeScript

Operators in JavaScript and TypeScript include:

1.1 Arithmetic Operators

Used for mathematical operations.

let a = 10, b = 5;

console.log(a + b); // 15
console.log(a - b); // 5
console.log(a * b); // 50
console.log(a / b); // 2
console.log(a % b); // 0
console.log(a ** b); // 100000 (Exponentiation)
        

1.2 Comparison Operators

Used for comparing values.

console.log(10 == "10");  // true (loose equality)
console.log(10 === "10"); // false (strict equality)
console.log(10 != 5);     // true
console.log(10 !== "10"); // true
console.log(10 > 5);      // true
console.log(10 < 5);      // false
console.log(10 >= 10);    // true
console.log(10 <= 9);     // false
        

1.3 Logical Operators

Used for combining conditions.

console.log(true && false); // false (AND)
console.log(true || false); // true (OR)
console.log(!true);         // false (NOT)
        

1.4 Assignment Operators

Used for assigning values.

let x = 10;
x += 5;  // x = x + 5
x -= 3;  // x = x - 3
x *= 2;  // x = x * 2
x /= 2;  // x = x / 2
x %= 3;  // x = x % 3
x **= 2; // x = x ** 2
        

1.5 Bitwise Operators

Works on binary numbers.

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

2. Conditional Statements in JavaScript & TypeScript

2.1 if, else if, else Statement

let num = 10;

if (num > 10) {
    console.log("Greater than 10");
} else if (num === 10) {
    console.log("Equal to 10");
} else {
    console.log("Less than 10");
}
        

2.2 switch Statement

Used when multiple conditions are checked against a single value.

let day = "Monday";

switch (day) {
    case "Monday":
        console.log("Start of the week!");
        break;
    case "Friday":
        console.log("Almost weekend!");
        break;
    default:
        console.log("It's just another day!");
}
        

3. Loops in JavaScript & TypeScript

3.1 for Loop

Used when the number of iterations is known.

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

3.2 for...in Loop

Iterates over object properties.

const user = { name: "John", age: 30, country: "USA" };

for (let key in user) {
    console.log(`${key}: ${user[key]}`);
}
        

3.3 for...of Loop

Iterates over iterable objects like arrays and strings.

const numbers = [10, 20, 30];

for (let num of numbers) {
    console.log(num);
}
        

Bonus: while and do...while Loops

while Loop

Executes as long as the condition is true.

let count = 0;
while (count < 3) {
    console.log(`Count: ${count}`);
    count++;
}
        

do...while Loop

Executes at least once before checking the condition.

let num2 = 0;
do {
    console.log(`Number: ${num2}`);
    num2++;
} while (num2 < 3);
        

TypeScript-Specific Features

  • TypeScript allows explicit type annotations.
  • Example:

let x: number = 10;  // Type-safe variable declaration
        

Deep Dive into JavaScript & TypeScript Data Types

Understanding data types is fundamental in programming, as they define the kind of data that variables can hold. JavaScript is a dynamically typed language, meaning variables can change types at runtime. TypeScript, on the other hand, is a statically typed superset of JavaScript, enforcing types at compile-time to reduce errors.


1️⃣ JavaScript Data Types

JavaScript data types are divided into two main categories:

🟢 Primitive Data Types (Immutable, stored in stack memory)

Primitive types hold simple values and are compared by value rather than reference.

1. String

A string represents a sequence of characters enclosed in single ('), double ("), or backticks (`).

let name = "John";
let greeting = `Hello, ${name}`; // Template literal
        

Strings are immutable, meaning their values cannot be changed after creation.

2. Number

JavaScript has only one number type for both integers and floating-point values.

let age = 25;
let price = 99.99;
        

There is no separate integer type like in some other languages.

3. Boolean

A boolean has two possible values: true or false.

let isLoggedIn = true;
let hasAccess = false;
        

Booleans are commonly used in conditional statements.

4. Null

null represents an intentional absence of value.

let emptyValue = null;
        

💡 Gotcha: typeof null returns "object" due to a historical JavaScript bug.

5. Undefined

undefined means a variable has been declared but not assigned a value.

let notAssigned;
console.log(notAssigned); // undefined
        

💡 A variable explicitly assigned null is different from undefined.

6. BigInt

For numbers beyond Number.MAX_SAFE_INTEGER, BigInt is used by appending n to a number.

let bigNumber = 9007199254740991n;
        

7. Symbol

A Symbol represents a unique and immutable value, often used as object property keys.

const uniqueKey = Symbol("id");
console.log(uniqueKey); // Symbol(id)
        

🟣 Reference Data Types (Stored in heap memory, compared by reference)

Reference types store memory addresses, so two objects with the same properties are not equal when compared.

1. Object

An object is a collection of key-value pairs.

let user = { name: "Alice", age: 30 };
        

Objects allow nesting and dynamic property assignment.

2. Array

An array is a special type of object used for ordered lists.

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

Arrays can hold mixed data types and can be manipulated with various methods.

3. Function

A function is an object that can be invoked.

function greet() {
  return "Hello!";
}
console.log(greet()); // "Hello!"
        

4. Date

A Date object represents a date and time.

let today = new Date();
console.log(today.toDateString());
        

💡 Key Differences Between Primitives and Reference Types:

  • Primitive types store values directly in memory.
  • Reference types store memory addresses and are mutable.


2️⃣ TypeScript Data Types (Beyond JavaScript)

TypeScript enhances JavaScript by introducing static typing, which helps prevent errors at compile-time.

🟢 Basic TypeScript Types

TypeScript introduces explicit type annotations.

let username: string = "John";
let age: number = 30;
let isAdmin: boolean = false;
        

💡 Unlike JavaScript, TypeScript will not allow type mismatches.

🟣 Special TypeScript Types

1. Any

The any type allows a variable to hold any value, bypassing type checking.

let data: any = "hello";
data = 42; // No error
        

💡 Avoid using any unless absolutely necessary.

2. Unknown

The unknown type is safer than any, requiring explicit type checks.

let input: unknown;
if (typeof input === "string") {
  console.log(input.toUpperCase());
}
        

3. Void

Used for functions that do not return a value.

function logMessage(): void {
  console.log("This function returns nothing");
}
        

4. Never

Represents a function that never returns (e.g., an infinite loop or an error throw).

function throwError(): never {
  throw new Error("Something went wrong");
}
        

5. Tuple

A tuple is a fixed-length array with specific types at each position.

let person: [string, number] = ["Alice", 30];
        

6. Enum

An enum defines a set of named constants.

enum Role {
  Admin,
  User,
  Guest
}
let userRole: Role = Role.Admin;
        

3️⃣ JavaScript vs TypeScript Data Type Handling

JavaScript (Dynamic Typing)

  • Variables can hold any type of value at runtime.
  • Type errors occur only when executing the code.

TypeScript (Static Typing)

  • Variables must be assigned specific types at compile-time.
  • Prevents type-related bugs before execution.

💡 TypeScript helps catch mistakes like:

let username: string = "Alice";
username = 42; // ❌ Type error: number is not assignable to string
        

🔍 Key Takeaways

1️⃣ JavaScript has 7 primitive types and multiple reference types. 2️⃣ TypeScript enforces type safety, reducing runtime errors. 3️⃣ Primitive values are immutable and compared by value, while reference types store memory addresses and are compared by reference. 4️⃣ TypeScript’s special types (unknown, void, never, tuple, enum) offer extra safety and structure to JavaScript.

🔥 JavaScript Methods: Arrays, Strings, Objects, Functions, Dates & Regular Expressions

JavaScript provides built-in methods to manipulate arrays, strings, objects, functions, dates, and regular expressions, making coding more efficient. Let's dive deep into these essential methods! 🚀


1️⃣ Array Methods in JavaScript

Arrays store ordered lists of values and come with powerful built-in methods.

🔹 Adding & Removing Elements

let fruits = ["apple", "banana", "cherry"];
        

  • .push(value): Adds to the end ➝ fruits.push("grape");
  • .pop(): Removes last element ➝ fruits.pop();
  • .unshift(value): Adds to the beginning ➝ fruits.unshift("mango");
  • .shift(): Removes first element ➝ fruits.shift();

🔹 Iterating & Transforming

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

  • .map(callback): Transforms each element ➝ numbers.map(n => n * 2);
  • .filter(callback): Filters elements ➝ numbers.filter(n => n > 2);
  • .reduce(callback, initial): Reduces to a single value ➝ numbers.reduce((sum, n) => sum + n, 0);
  • .forEach(callback): Iterates over elements ➝ numbers.forEach(n => console.log(n));

🔹 Searching & Checking

let names = ["Alice", "Bob", "Charlie"];
        

  • .includes(value): Checks existence ➝ names.includes("Bob"); // true
  • .indexOf(value): Finds index ➝ names.indexOf("Charlie"); // 2
  • .find(callback): Returns first match ➝ names.find(name => name.startsWith("A"));
  • .some(callback): Checks if any match ➝ names.some(name => name.length > 3);
  • .every(callback): Checks if all match ➝ names.every(name => name.length > 3);

🔹 Manipulation & Sorting

let letters = ["b", "a", "c"];
        

  • .sort(): Sorts in place ➝ letters.sort(); // ["a", "b", "c"]
  • .reverse(): Reverses array ➝ letters.reverse();
  • .concat(array): Merges arrays ➝ letters.concat(["d", "e"]);
  • .join(separator): Converts to string ➝ letters.join("-"); // "b-a-c"
  • .slice(start, end): Extracts part of an array ➝ letters.slice(1, 3);
  • .splice(start, deleteCount, ...items): Modifies array ➝ letters.splice(1, 1, "z");


2️⃣ String Methods in JavaScript

Strings are sequences of characters and can be manipulated with various methods.

let text = "  JavaScript is awesome!  ";
        

🔹 Basic Operations

  • .length: Get length ➝ text.length;
  • .charAt(index): Get character ➝ text.charAt(3);
  • .indexOf(value): Find first index ➝ text.indexOf("is");
  • .lastIndexOf(value): Find last index ➝ text.lastIndexOf("a");
  • .toUpperCase() / .toLowerCase(): Change case ➝ text.toUpperCase();
  • .trim(): Remove spaces ➝ text.trim();
  • .repeat(n): Repeat string ➝ text.repeat(3);
  • .padStart(length, value) / .padEnd(length, value): Add padding ➝ "5".padStart(3, "0"); // "005"

🔹 Extracting Substrings

  • .slice(start, end): Extract part ➝ text.slice(2, 10);
  • .substring(start, end): Similar to slice
  • .substr(start, length): Get portion ➝ text.substr(2, 5);

🔹 Replacing & Splitting

  • .replace(old, new): Replace ➝ text.replace("awesome", "powerful");
  • .replaceAll(old, new): Replace all occurrences
  • .split(separator): Convert to array ➝ text.split(" ");


3️⃣ Object Methods in JavaScript

Objects store key-value pairs and have various methods.

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

🔹 Object Property Management

  • Object.keys(obj): Get keys ➝ Object.keys(person);
  • Object.values(obj): Get values ➝ Object.values(person);
  • Object.entries(obj): Get key-value pairs ➝ Object.entries(person);
  • Object.assign(target, source): Merge objects ➝ Object.assign({}, person, { age: 30 });
  • Object.freeze(obj): Prevent modification
  • Object.seal(obj): Allow modification but not new properties


4️⃣ Function Methods in JavaScript

Functions are objects in JavaScript and have methods.

function greet(name) {
  console.log(`Hello, ${name}!`);
}
        

🔹 Function Methods

  • .call(thisArg, ...args): Call function with a specific this
  • .apply(thisArg, [args]): Same as .call(), but takes an array
  • .bind(thisArg, ...args): Returns a new function with bound this

let person = { name: "Bob" };
function sayHello() {
  console.log(this.name);
}
let boundHello = sayHello.bind(person);
boundHello(); // "Bob"
        

5️⃣ Date Methods in JavaScript

JavaScript's Date object helps handle dates and times.

let now = new Date();
        

🔹 Creating & Formatting Dates

  • new Date(): Get current date/time
  • getFullYear(): Get year
  • getMonth(): Get month (0-based)
  • getDate(): Get day of the month
  • getDay(): Get day of the week (0 = Sunday)
  • toISOString(): Convert to ISO format
  • toLocaleDateString(): Localized date

🔹 Modifying Dates

  • setFullYear(year), setMonth(month), setDate(day)
  • getTime(): Get timestamp


6️⃣ Regular Expression Methods in JavaScript

Regular expressions (RegExp) allow pattern matching.

let pattern = /hello/i; // Case-insensitive match
let text = "Hello, world!";
        

🔹 String Methods with RegExp

  • .match(regex): Find matches
  • .search(regex): Get first match index
  • .replace(regex, newStr): Replace pattern
  • .split(regex): Split using pattern

🔹 RegExp Methods

let regex = /\d+/g; // Matches numbers globally
let result = regex.test("abc123"); // true
console.log(result);
        

  • .test(str): Check match (returns true/false)
  • .exec(str): Find match details




To view or add a comment, sign in

More articles by Hari Mohan Prajapat

Insights from the community

Others also viewed

Explore topics