🚀 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
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.
Recommended by LinkedIn
let today = new Date();
console.log(today.toDateString());
💡 Key Differences Between Primitives and Reference Types:
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)
TypeScript (Static Typing)
💡 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"];
🔹 Iterating & Transforming
let numbers = [1, 2, 3, 4, 5];
🔹 Searching & Checking
let names = ["Alice", "Bob", "Charlie"];
🔹 Manipulation & Sorting
let letters = ["b", "a", "c"];
2️⃣ String Methods in JavaScript
Strings are sequences of characters and can be manipulated with various methods.
let text = " JavaScript is awesome! ";
🔹 Basic Operations
🔹 Extracting Substrings
🔹 Replacing & Splitting
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
4️⃣ Function Methods in JavaScript
Functions are objects in JavaScript and have methods.
function greet(name) {
console.log(`Hello, ${name}!`);
}
🔹 Function Methods
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
🔹 Modifying Dates
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
🔹 RegExp Methods
let regex = /\d+/g; // Matches numbers globally
let result = regex.test("abc123"); // true
console.log(result);