Web Development Articles
Javascript Map, Filter, Reduce methods
Map
The map() method is used for creating a new array from an existing one, applying a function to each one of the elements of the first array.
let numbers = [1, 2, 3, 4, 5];let doubled = numbers.map(num => num * 2);console.log(doubled) // [2, 4, 6, 8, 5]
Filter
The filter() method takes each element in an array and it applies a conditional statement against it. If this conditional returns true, the element gets pushed to the output array. If the condition returns false, the element does not get pushed to the output array.const numbers = [1, 2, 3, 4];
const odds = numbers.filter(num => num % 2 === 1);
console.log(odds); // [1, 3]
Or with an array of Objects you can implement filter() like the following.
const students = [{name: 'eric', age: 12},{name: 'Jenny' age: 11},{name: 'Freddy', age: 9}];const overTen = students.filter(student => student.age > 10); console.log(overTen); // [{name:'Eric', age:12}, {name:'Jenny', age:11}]
Reduce
The reduce() method reduces/calculates a value down to a single value. To get the output value, it runs a reducer function on each element of the array.
const array1 = [1, 2, 3, 4]; // 0 + 1 + 2 + 3 + 4
const initialValue = 10;
const sumWithInitial = array1.reduce(
(accumulator, currentValue) => accumulator + (currentValue * 10),
initialValue);
// Expected output is 110. Ok so the accumulator starts at the value of zero. And then accumulator is accumulator plus currentValue times 10. Add 10(initialValue... we set it to 10) + 10 + 20 + 30 + 40
Javascript Null Coalescing Operator ??
The double question mark ?? in javascript is referred to as the null coalescing operator. It was introduced in JavaScript ES2020. It allows you to check for null or undefined variable. In most cases the order of operation for this operator follows the math and comparison operators. Below are a few examples:
Example 1:let myval = null;console.log(myval ?? 20); // output is 20 because myval is null
Example 2:console.log(myval ?? 20); // output is 20 because myval is undefined
Example 3:let myval = [];console.log(myval ?? [1,2,3]); // output is [] because it isn't null and it's not undefined
If the myval is anything other than null or undefined, the output will be the value of the right-hand side of the equation.
PostgreSQL many-to-many Relationship
In this example we will look at how to work with a many-to-many relationship. So first let’s look at a situation where we can leverage a many-to-many relationship. Imagine we have both Students and Courses. A student can be enrolled in multiple courses and a course can have multiple students. This is called a many-to-many relationship and requires what’s called a pivot table. Although there aren’t any restrictions to the name of a pivot table I will call it “course_student”. The course_student pivot table will have, at minimum, 2 foreign key fields. A reference to courses table and a reference to students table.
CREATE TABLE students (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
phone_number VARCHAR(100) UNIQUE NOT NULL,
);
CREATE TABLE courses (
id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(100) NOT NULL,
description TEXT NOT NULL
);
-- The pivot table has a reference key to each table
CREATE TABLE course_student (
student_id INT,
course_id INT,
PRIMARY KEY (student_id, course_id),
FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE,
FOREIGN KEY (course_id) REFERENCES courses(id) ON DELETE CASCADE
);
Below are a few useful ways to query this schema. Assuming you are familiar with a LEFT JOIN, these queries specifically use LEFT JOIN for connecting the three tables. courses to course_student to students
# Get all courses that student with id = 2 is enrolled
SELECT c.id course_id, c.title, s.id student_id, s.name
FROM students s
LEFT JOIN course_student cs ON s.id = cs.student_id
LEFT JOIN course c ON c.id = cs.course_id
WHERE s.id = 2;
# Get all students enrolled in course with id = 1
SELECT c.id course_id, c.title, s.id student_id, s.name
FROM courses c
LEFT JOIN course_student cs ON c.id = cs.course_id
LEFT JOIN student s ON s.id = cs.student_id
WHERE c.id = 1;
JavaScript Asynchronous Programming with Promise any()
Promise.any() is a powerful JavaScript method introduced in ECMAScript 2021 that allows you to handle multiple promises simultaneously. This method returns a single promise that resolves as soon as any one of the input promises fulfills, making it ideal for scenarios where you want the fastest successful result.
Browser and Node.js Compatibility
Node.js: 15.0.0+ (native support)
Chrome: 85+
Firefox: 79+
Safari: 14+
For optimal compatibility and performance, we recommend using the latest Node.js LTS version.
How Promise.any() Works
Promise.any() takes an iterable of promises and returns a promise that:
- Resolves with the value of the first successfully fulfilled promise
- Rejects only if all input promises are rejected
Key Characteristics:
- Returns the first successful promise (not necessarily the fastest)
- Ignores rejected promises until all promises fail
- Perfect for fallback strategies and redundancy
Practical Examples
Example 1: First Successful Promise Wins
// Create promises with different resolve/reject patterns
const fastPromise = new Promise((resolve, reject) => {
setTimeout(reject, 100, "fast: rejected");
});
const mediumPromise = new Promise((resolve, reject) => {
setTimeout(reject, 99, "medium: rejected");
});
const slowPromise = new Promise((resolve, reject) => {
setTimeout(resolve, 50, "slow: resolved");
});
const veryFastPromise = new Promise((resolve, reject) => {
setTimeout(() => resolve('very fast: resolved'), 205);
});
// Use Promise.any() to get the first successful result
Promise.any([slowPromise, mediumPromise, fastPromise, veryFastPromise])
.then((result) => {
console.log("First successful promise:", result);
// Output: "slow: resolved"
})
.catch(error => {
console.log("All promises failed");
});
Example 2: Handling Complete Failure
// All promises will be rejected
const rejectedFast = new Promise((resolve, reject) => {
setTimeout(reject, 100, "fast: rejected");
});
const rejectedMedium = new Promise((resolve, reject) => {
setTimeout(reject, 99, "medium: rejected");
});
const rejectedSlow = new Promise((resolve, reject) => {
setTimeout(reject, 50, "slow: rejected");
});
const rejectedVeryFast = new Promise((resolve, reject) => {
setTimeout(() => reject('very fast: rejected'), 205);
});
Promise.any([rejectedSlow, rejectedMedium, rejectedFast, rejectedVeryFast])
.then((result) => {
console.log("Success:", result);
})
.catch(error => {
console.log("Total failures:", error.errors.length);
// Iterate through all rejection reasons
error.errors.forEach((rejection, index) => {
console.log(`Failure ${index + 1}:`, rejection);
});
});
// Output:
// Total failures: 4
// Failure 1: slow: rejected
// Failure 2: medium: rejected
// Failure 3: fast: rejected
// Failure 4: very fast: rejected
Error Handling Best Practices
Always include a .catch() block when using Promise.any(). Without proper error handling, you might encounter:
UnhandledPromiseRejection: This error originated either by throwing inside of
an async function without a catch block, or by rejecting a promise which was
not handled with .catch(). The promise rejected with the reason "slow promise
Rejected".
Proper Error Handling Pattern:
Promise.any([promise1, promise2, promise3])
.then(result => {
// Handle successful result
console.log("Success:", result);
})
.catch(error => {
// Handle case where all promises failed
console.log("All promises rejected");
console.log("Rejection reasons:", error.errors);
})
.finally(() => {
// Cleanup code that runs regardless of outcome
console.log("Operation completed");
});
Real-World Use Cases
1. Multiple API Endpoints with Fallback
const primaryAPI = fetch('https://primary-api.com/data');
const backupAPI = fetch('https://backup-api.com/data');
const cacheAPI = fetch('https://cache-api.com/data');
Promise.any([primaryAPI, backupAPI, cacheAPI])
.then(response => response.json())
.then(data => {
console.log("Data from fastest available source:", data);
})
.catch(() => {
console.log("All data sources unavailable");
});
2. Resource Loading with Redundancy
const cdn1 = loadScript('https://cdn1.com/library.js');
const cdn2 = loadScript('https://cdn2.com/library.js');
const cdn3 = loadScript('https://cdn3.com/library.js');
Promise.any([cdn1, cdn2, cdn3])
.then(() => {
console.log("Library loaded successfully");
initializeApp();
})
.catch(() => {
console.error("All CDNs failed - using local fallback");
loadLocalFallback();
});
PHP Object Oriented Class Inheritance
PHP class inheritance is a mechanism that allows one class (called the child class or subclass) to inherit properties and methods from another class (called the parent class or superclass).
This allows you to reuse code, extend existing functionality, and follow the principle of "Don’t Repeat Yourself (DRY)".
Basics of Inheritance
1. The extends keyword is used in PHP to create inheritance.
2. A child class automatically inherits all the public and protected properties and methods of its parent class.
3. The child class can:
A. Use the inherited methods and properties directly.
B. Override methods from the parent class.
C. Add new methods and properties.
Example 1: Basic Inheritance
Here, the Dog class inherits from the Animal class but overrides the speak() method.
// Parent class
class Animal {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function speak() {
echo "$this->name makes a sound.<br>";
}
}
// Child class
class Dog extends Animal {
public function speak() {
echo "$this->name barks! Woof Woof!<br>";
}
}
// Usage
$animal = new Animal("Generic Animal");
$animal->speak(); // Output: Generic Animal makes a sound.
$dog = new Dog("Buddy");
$dog->speak(); // Output: Buddy barks! Woof Woof!
Example 2: Using parent:: to Call Parent Methods
The Car class overrides the start() method but still uses the parent’s method with parent::start().
class Vehicle {
public function start() {
echo "Starting the vehicle...<br>";
}
}
class Car extends Vehicle {
public function start() {
// Call the parent method first
parent::start();
echo "Car engine started!<br>";
}
}
$car = new Car();
$car->start();
// Output:
// Starting the vehicle...
// Car engine started!
Example 3: Multilevel Inheritance
Human inherits from Animal, and Animal inherits from LivingBeing. So, Human has all methods from both parents.
class LivingBeing {
public function breathe() {
echo "Breathing...<br>";
}
}
class Animal extends LivingBeing {
public function eat() {
echo "Eating...<br>";
}
}
class Human extends Animal {
public function speak() {
echo "Speaking...<br>";
}
}
$person = new Human();
$person->breathe(); // From LivingBeing
$person->eat(); // From Animal
$person->speak(); // From Human
PHP Match Expression (match)
PHP Match Expression (match)
The PHP match expression is a powerful feature introduced in PHP 8.0 that provides a more concise and flexible alternative to switch statements.
Basic Match Syntax
$result = match ($value) {
pattern1 => expression1,
pattern2 => expression2,
// ...
default => default_expression,
};
Comparison switch vs match
// switch statement
switch ($statusCode) {
case 200:
$message = 'OK';
break;
case 404:
$message = 'Not Found';
break;
case 500:
$message = 'Server Error';
break;
default:
$message = 'Unknown';
}
// match equivalent
$message = match ($statusCode) {
200 => 'OK',
404 => 'Not Found',
500 => 'Server Error',
default => 'Unknown',
};
Various Usage Examples:
// multiple conditions
$result = match ($httpCode) {
200, 201, 202 => 'Success',
400, 401, 403 => 'Client Error',
500, 501, 502 => 'Server Error',
default => 'Unknown',
};
// Match uses strict comparison (===)
$result = match ($value) {
0 => 'Integer zero',
'0' => 'String zero',
false => 'Boolean false',
default => 'Other',
};
// Complex Expressions
$age = 25;
$category = match (true) {
$age < 13 => 'Child',
$age < 20 => 'Teenager',
$age < 65 => 'Adult',
default => 'Senior',
};
// returning different types
function processValue($value) {
return match ($value) {
'int' => 42,
'string' => 'Hello World',
'array' => [1, 2, 3],
'bool' => true,
default => null,
};
}
// Using with arrays
$user = [
'role' => 'admin',
'status' => 'active'
];
$permissions = match ($user['role']) {
'admin' => ['read', 'write', 'delete'],
'editor' => ['read', 'write'],
'viewer' => ['read'],
default => [],
};
// nested match expressions
$result = match ($type) {
'number' => match ($value) {
$value > 0 => 'Positive',
$value < 0 => 'Negative',
default => 'Zero',
},
'string' => 'String type',
default => 'Unknown type',
};
// Conditional Logic in Patterns
$score = 85;
$grade = match (true) {
$score >= 90 => 'A',
$score >= 80 => 'B',
$score >= 70 => 'C',
$score >= 60 => 'D',
default => 'F',
};
Advantages Over Switch
- Returns a value - Can be assigned directly to variables
- No fall-through - Prevents accidental bugs
- Strict comparisons - More predictable behavior
- More concise - Less boilerplate code
- Better error handling - Throws UnhandledMatchError for unhandled cases
Important Notes
- Match expressions must be exhaustive or include a default case
- Throws UnhandledMatchError if no pattern matches and no default is provided
- Each arm must be a single expression (use anonymous functions for complex logic)
- Patterns are evaluated in order, first match wins
The match expression is a significant improvement that makes conditional logic more readable, safer, and more expressive in modern PHP code.
PHP Spaceship Operator (<=>)
PHP Spaceship Operator (<=>)
The PHP Spaceship Operator (<=>) is a comparison operator that provides a three-way comparison between two values. It's also known as the "combined comparison operator."
How it works:
The operator returns -1, 0, or 1 depending on the condition.
-1 => if the left operand is less than the right operand
0 => if both operands are equal
1 => if the left operand is greater than the right operand
Sample Usage:
$a = 1;
$b = 1;
$result = $a <=> $b; // result is 0
$b = 2;
$result = $a <=> $b; // result is -1
$b = 0;
$result = $a <=> $b; // $result is 1
Spaceship Operator vs using if-else:
// using if/else
if ($a < $b) {
return -1;
} elseif ($a > $b) {
return 1;
} else {
return 0;
}
// using spaceship operator
return $a <=> $b;
Benefits:
- Concise: Replaces complex if-else chains
- Readable: Clear intention for comparison
- Consistent: Always returns -1, 0, or 1
- Type-safe: Handles different data types predictably