Web Development Articles
Defining a Javascript Function
How To Define a JavaScript Function
There are a few different ways to declare a function in Javascript applications. I’ve laid out 4 ways below so choose the method that best fits your use case! Function declarations are great for named functions, whereas arrow functions are excellent for callbacks and shorter functions.
Using Function Declaration
/** Function Declaration */
function functionName(parameters) {
// code to be executed
return value;
}
// Example
function greet(name) {
return "Hello, " + name + "!";
}
console.log(`My name is ${greet("Alice")}`); // "Hello, Alice!"
Using Function Expression
/** Function Expression */
const functionName = function(parameters) {
// code to be executed
return value;
};
// Example
const multiply = function(a, b) {
return a * b;
};
console.log(`5 * 3 = ${multiply(5, 3)}`); // 15
Using Arrow Functions (ES6)
/** Arrow Function (ES6) */
const functionName = (parameters) => {
// code to be executed
return value;
};
// Examples with different syntax
const square = (x) => {
return x * x;
};
console.log(`Square of 4: ${square(4)}`); // 16
// Implicit return (for single expressions)
const squareRoot = x => x ** 0.5;
console.log(`Square Root of 8: ${squareRoot(8)}`);
// Multiple parameters
const add = (a, b) => a + b;
console.log(`2 + 3 = ${add(2, 3)}`); // 5
// No parameters
const title = () => "Math";
console.log(`The page title is "${pageTitle()}"`);
Using the Function Constructor
/** 4. Function Constructor (less common) */
const functionName = new Function("parameters", "function body");
// Example
const divide = new Function("a", "b", "return a / b;");
console.log(divide(10, 2)); // 5
How to Backup and Restore with pg_dump and mysqldump
This tutorial guides you through backing up MySQL and PostgreSQL databases from the command line. While their native tools—mysqldump and pg_dump—share a similar purpose, their command syntax differs. We will cover the essential commands for both systems, highlighting their key similarities and differences.
Backup MySQL / MariaDB Database
Export every table’s schema and existing records to an SQL executable script.
mysqldump -u username -p database_name > database.sql
This will export the specified table’s schema and records to an executable script.
mysqldump -u username -p database_name table_name > db_table.sql
This will export the specified table’s data only(no schema).
mysqldump -u username -p --no-create-info database_name table_name > table_data.sql
This will export the specified table’s schema only(no data).
mysqldump -u username -p --no-data database_name table_name > table_schema.sql
Restore MySQL / MariaDB Database
mysql -u username -p database_name < database.sql
Backup PostgreSQL Database
Export every table’s schema and existing records to an SQL executable script.
pg_dump -U username database_name > database.sql
This will export both the specified table’s schema and data to an executable script.
pg_dump -U username -t table_name database_name > table.sql
Only data (no schema):
pg_dump -U username -a -t table_name database_name > table_data.sql
Only schema (no data):
pg_dump -U username -s -t table_name database_name > table_schema.sql
Restore PostgreSQL Database
psql -U username -d database_name -f database.sql
Laravel Webpack.mix Asset Compilation AND Performance Optimization
Getting Started with webpack.mix
This is an essential must know for Laravel developers. This tutorial will go through the basics of webpack.mix and preparing live CSS stylesheets and Javascript includes.
Locate webpack.mix.js and the /resources and /public directories. I will define a few ways to specify the files from resources compiled to the live public directory. Check out these 2 examples… they should cover necessary usage for 99% of projects.
Example: Combine multiple files into a single file.
In this example I’ll define a simple way to combine multiple custom javascript files into a single file. Let’s take 4 custom stylesheets and 4 javascript files. We will combine all specified stylesheets from /resources/css into a single stylesheet named /public/css/custom-all.css. Also let’s combine the specified javascript files from /resources/js into a single javascript file named /public/js/custom-all.js
All files that can be edited directly are located in the resources directory. All compiled files will be placed in the public directory where the code can be accessed live.
mix.js('resources/js/app.js', 'public/js')
.vue()
.sass('resources/sass/app.scss', 'public/css');
// Combine all custom JS into one file
mix.scripts([
'resources/js/custom/main.js',
'resources/js/custom/helpers.js',
'resources/js/custom/components/*.js'
], 'public/js/custom-all.js');
// Combine all custom CSS into one file
mix.styles([
'resources/css/custom/main.css',
'resources/css/custom/components/buttons.css',
'resources/css/custom/pages/*.css'
], 'public/css/custom-all.css');
Let’s see how to use things in a blade template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Your Laravel Application</title>
<!-- Compiled CSS -->
<link href="{{ mix('css/app.css') }}" rel="stylesheet">
<link href="{{ mix('css/custom-all.css') }}" rel="stylesheet">
</head>
<body>
<div id="app">
<!-- Your application content -->
</div>
<!-- Compiled JavaScript -->
<script src="{{ mix('js/app.js') }}"></script>
<script src="{{ mix('js/custom-all.js') }}"></script>
</body>
</html>
Example: Prepare several files.
This example is very similar to the example above. The only difference is in this example we are generating individual files in the public directory for each file specified from the resources directory.
// Webpack-compiled JS and CSS
mix.js('resources/js/app.js', 'public/js')
.vue({ version: 2 })
.sass('resources/sass/app.scss', 'public/css') // Or .css() if not using Sass
.css('resources/css/app.css', 'public/css');
// Custom JS files (separate from Webpack bundle)
mix.js('resources/js/custom/main.js', 'public/js/custom.js')
.js('resources/js/custom/helpers.js', 'public/js/helpers.js');
// Custom CSS files (separate from Webpack bundle)
mix.css('resources/css/custom/main.css', 'public/css/custom.css')
.css('resources/css/custom/components/buttons.css', 'public/css/components/buttons.css');
Notice in webpack.mix.js the definitions for mix.js and mix.css methods. Each of the javascript files and stylesheets from the resources directory has a corresponding file in the public directory.
Now let’s look at how to use this in a blade template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Your Laravel Application</title>
<!-- Compiled CSS -->
<link href="{{ mix('css/app.css') }}" rel="stylesheet">
<link href="{{ mix('css/custom.css') }}" rel="stylesheet">
<link href="{{ mix('css/components/buttons.css') }}" rel="stylesheet">
</head>
<body>
<div id="app">
<!-- Your application content -->
</div>
<!-- Compiled JavaScript -->
<script src="{{ mix('js/app.js') }}"></script>
<script src="{{ mix('js/custom.js') }}"></script>
<script src="{{ mix('js/helpers.js') }}"></script>
</body>
</html>
To generate the public CSS and JS files:
npm install
npm run dev
JavaScript Self-Invoked Functions (IIFEs)
What is a self-invoked function? (IIFE)
A self-invoked function, also called an Immediately Invoked Function Expression (IIFE) is a Javascript function expression that is invoked immediately after its declaration. A self-invoked function can be a valuable tool for creating isolated scopes and managing variable privacy in javascript applications.
Key aspects of IIFEs:
- IIFEs execute immediately when defined
- Allows creation of private scopes without polluting global namespace
- Return values can be assigned to variables
- Parameters can be passed to IIFEs
Basic syntax:
(function() {
// code here
})();
// OR arrow functions (ES6+)
(() => {
// code here
})();
Why are IIFEs Necessary?
Immediate Execution with Parameters
// Immediately logs provided data
(function(date, location) {
console.log(`Date: ${date.toDateString()}`);
console.log(`Location: ${location}`);
})(new Date(), 'Seattle');
// Immediately logs:
// Date: Thu Oct 16 2025
// Location: Seattle
Avoiding Global Namespace Pollution
// if multiple scripts use the same variable names
// they won't conflict
(function() {
const restaurant = "Dairy Queen";
console.log(user); // "Dairy Queen"
})();
(function() {
const restaurant = "Burger King";
console.log(user); // "Burger King"
})();
Data Privacy/Encapsulation
// Problem: counter value is vulnerable.
var counter = 0;
function increment() {
return ++counter;
}
// FIX: keeps variables private. counterModule isn't directly accessible
const counterModule = (function() {
let count = 0;
return {
increment: function() {
return ++count;
},
decrement: function() {
return --count;
},
getCount: function() {
return count;
}
};
})();
counterModule.count = 100; // WONT WORK!!
// count is not accessible directly
console.log(counterModule.getCount()); // 0
counterModule.increment();
console.log(counterModule.getCount()); // 1
// OUPTUT: 0 1
Module Pattern Implementation
const User = (function() {
let memory = 0;
function add(a, b) {
return a + b;
}
function store(value) {
memory = value;
}
function recall() {
return memory;
}
// Only expose public methods
return {
add: add,
store: store,
recall: recall
};
})();
console.log(Calculator.add(5, 3)); // 8
Calculator.store(10);
console.log(Calculator.recall()); // 10
// memory is private and inaccessible
Format Date and Time in JavaScript with Date Object
This tutorial The JavaScript Date library is a built-in object that represents a single moment in time. It provides methods for creating, parsing, formatting, and manipulating dates and times. Dates are stored as the number of milliseconds since the Unix epoch (January 1, 1970, 00:00:00 UTC).
In this tutorial I will cover how to format date only, time only, and both date and time using these 3 methods from built-in object Date. A method to format a date. A method to format a time. And a method to format both date and time.
const date = new Date('2025-10-23 11:06:48');
date.toLocaleDateString('en-US');
date.toLocaleTimeString('en-US');
date.toLocaleString('en-US');
Also, I have included 2 handy references at the end of this tutorial. A reference for options and values available to define the format. Also, a reference that lists all available methods on the Javascript built-in Date object.
Date toLocaleDateString()
The toLocaleDateString() method formats the date only. Below the value of the date will be initiated as datetime (yyyy-mm-dd hh:mm:ss):
const date = new Date('2025-10-23 11:06:48');
Even though the Date object is initiated with a date and time string, only the date part of the string will be extracted. The default date.toLocaleDateString('en-US') returns the date formatted as mm/dd/yyyy. Also use other formatting options available. The options are referenced below.
const date = new Date('2025-10-23 11:06:48');
// Date only
date.toLocaleDateString('en-US');
// "10/23/2025"
date.toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric'
});
// "October 23, 2025"
Date toLocaleTimeString()
Target and format the time portion of the string using toLocaleTimeString(). Now time is extracted from the initial value set below…
const date = new Date('2025-10-23 11:06:48');
The toLocaleTimeString() method can be used with or without options. The default time is in 12 hour format (hh:mm:ss AM/PM). Options are listed below:
// Time only
date.toLocaleTimeString('en-US');
// "11:06:48 AM"
date.toLocaleTimeString('en-US', {
hour: '2-digit',
minute: '2-digit',
hour12: true
});
// "11:06 AM"
Date toLocaleString()
To format both the date and time use toLocaleString(). This method also accepts options to provide formatting instructions. Refer to the list below.
// Combined date and time
date.toLocaleString('en-US');
// "10/23/2025, 11:06:48 AM"
date.toLocaleString('en-US').replace(/,/g, '');
// "10/23/2025 11:06:48 AM"
Below are all the possible format options that can be passed to toLocaleString() for the en-US locale.
Option Reference Table toLocaleString()
|
Parameter |
Possible Values |
Description |
Example Output |
|
DATE COMPONENTS |
|||
|
year |
'numeric' |
Full year |
2025 |
|
'2-digit' |
Two-digit year |
25 |
|
|
month |
'numeric' |
Month number |
10 |
|
'2-digit' |
Two-digit month |
10 |
|
|
'long' |
Full month name |
October |
|
|
'short' |
Abbreviated month |
Oct |
|
|
'narrow' |
Single character |
O |
|
|
day |
'numeric' |
Day of month |
23 |
|
'2-digit' |
Two-digit day |
23 |
|
|
weekday |
'long' |
Full weekday name |
Thursday |
|
'short' |
Abbreviated weekday |
Thu |
|
|
'narrow' |
Single character |
T |
|
|
TIME COMPONENTS |
|||
|
hour |
'numeric' |
Hour |
11 |
|
'2-digit' |
Two-digit hour |
11 |
|
|
minute |
'numeric' |
Minute |
6 |
|
'2-digit' |
Two-digit minute |
06 |
|
|
second |
'numeric' |
Second |
48 |
|
'2-digit' |
Two-digit second |
48 |
|
|
fractionalSecondDigits |
1, 2, 3 |
Milliseconds digits |
48.123 |
|
TIME SETTINGS |
|||
|
hour12 |
true |
12-hour clock |
11:06 AM |
|
false |
24-hour clock |
11:06 |
|
|
timeZone |
'America/New_York' |
Specific timezone |
Adjusts time |
|
'UTC' |
UTC timezone |
||
|
'Europe/London' |
Other timezones |
||
|
timeZoneName |
'short' |
Abbreviated timezone |
EDT |
|
'long' |
Full timezone name |
Eastern Daylight Time |
|
|
'shortOffset' |
Short offset |
GMT-4 |
|
|
'longOffset' |
Long offset |
GMT-04:00 |
|
|
'shortGeneric' |
Generic short |
ET |
|
|
'longGeneric' |
Generic long |
Eastern Time |
|
|
OTHER OPTIONS |
|||
|
era |
'long' |
Full era name |
Anno Domini |
|
'short' |
Abbreviated era |
AD |
|
|
'narrow' |
Single character |
A |
|
|
dayPeriod |
'narrow' |
AM/PM format |
AM |
|
'short' |
AM/PM format |
AM |
|
|
'long' |
AM/PM format |
AM |
|
|
calendar |
'gregory' |
Gregorian calendar |
Default |
|
numberingSystem |
'latn' |
Latin digits |
0123456789 |
|
PRESET STYLES |
|||
|
dateStyle |
'full' |
Complete date |
Thursday, October 23, 2025 |
|
'long' |
Long format |
October 23, 2025 |
|
|
'medium' |
Medium format |
Oct 23, 2025 |
|
|
'short' |
Short format |
10/23/2025 |
|
|
timeStyle |
'full' |
Complete time |
11:06:48 AM Eastern Daylight Time |
|
'long' |
Long format |
11:06:48 AM EDT |
|
|
'medium' |
Medium format |
11:06:48 AM |
|
|
'short' |
Short format |
11:06 AM |
JavaScript Date Library Function Reference
Constructor Methods
|
Method |
Description |
Example |
|
new Date() |
Current date/time |
new Date() |
|
new Date(milliseconds) |
From milliseconds since epoch |
new Date(1634980000000) |
|
new Date(dateString) |
From ISO string |
new Date("2025-10-23") |
|
new Date(year, month, day, hours, minutes, seconds, ms) |
From components |
new Date(2025, 9, 23) |
Static Methods
|
Method |
Description |
Returns |
|
Date.now() |
Current timestamp in milliseconds |
1634980000000 |
|
Date.parse() |
Parse date string to milliseconds |
1634980000000 |
|
Date.UTC() |
UTC timestamp from components |
1634980000000 |
Getter Methods: Local Time Getters
|
Method |
Description |
Range |
|
getFullYear() |
4-digit year |
1900+ |
|
getMonth() |
Month |
0-11 |
|
getDate() |
Day of month |
1-31 |
|
getDay() |
Day of week |
0-6 |
|
getHours() |
Hours |
0-23 |
|
getMinutes() |
Minutes |
0-59 |
|
getSeconds() |
Seconds |
0-59 |
|
getMilliseconds() |
Milliseconds |
0-999 |
|
getTime() |
Milliseconds since epoch |
0+ |
|
getTimezoneOffset() |
Timezone offset in minutes |
-720 to 720 |
UTC Getters
|
Method |
Description |
Range |
|
getUTCFullYear() |
UTC 4-digit year |
1900+ |
|
getUTCMonth() |
UTC month |
0-11 |
|
getUTCDate() |
UTC day of month |
1-31 |
|
getUTCDay() |
UTC day of week |
0-6 |
|
getUTCHours() |
UTC hours |
0-23 |
|
getUTCMinutes() |
UTC minutes |
0-59 |
|
getUTCSeconds() |
UTC seconds |
0-59 |
|
getUTCMilliseconds() |
UTC milliseconds |
0-999 |
Setter Methods
Local Time Setters
|
Method |
Description |
Parameters |
|
setFullYear() |
Set year |
year[, month, day] |
|
setMonth() |
Set month |
month[, day] |
|
setDate() |
Set day of month |
day |
|
setHours() |
Set hours |
hours[, min, sec, ms] |
|
setMinutes() |
Set minutes |
minutes[, sec, ms] |
|
setSeconds() |
Set seconds |
seconds[, ms] |
|
setMilliseconds() |
Set milliseconds |
ms |
|
setTime() |
Set time via milliseconds |
milliseconds |
UTC Setters
|
Method |
Description |
Parameters |
|
setUTCFullYear() |
Set UTC year |
year[, month, day] |
|
setUTCMonth() |
Set UTC month |
month[, day] |
|
setUTCDate() |
Set UTC day of month |
day |
|
setUTCHours() |
Set UTC hours |
hours[, min, sec, ms] |
|
setUTCMinutes() |
Set UTC minutes |
minutes[, sec, ms] |
|
setUTCSeconds() |
Set UTC seconds |
seconds[, ms] |
|
setUTCMilliseconds() |
Set UTC milliseconds |
ms |
Conversion Methods
|
Method |
Description |
Example Output |
|
toString() |
Full date string |
"Thu Oct 23 2025 11:06:48 GMT-0400 (EDT)" |
|
toDateString() |
Date portion only |
"Thu Oct 23 2025" |
|
toTimeString() |
Time portion only |
"11:06:48 GMT-0400 (EDT)" |
|
toISOString() |
ISO 8601 format |
"2025-10-23T15:06:48.000Z" |
|
toUTCString() |
UTC string |
"Thu, 23 Oct 2025 15:06:48 GMT" |
|
toGMTString() |
GMT string (deprecated) |
"Thu, 23 Oct 2025 15:06:48 GMT" |
|
toJSON() |
JSON string |
"2025-10-23T15:06:48.000Z" |
|
toLocaleString() |
Locale date/time |
"10/23/2025, 11:06:48 AM" |
|
toLocaleDateString() |
Locale date only |
"10/23/2025" |
|
toLocaleTimeString() |
Locale time only |
"11:06:48 AM" |
Value Methods
|
Method |
Description |
Returns |
|
valueOf() |
Primitive value |
Milliseconds (same as getTime()) |
PHP $this, self and parent operators
Sometimes different aspects of object oriented programming can be a little confusing if you can’t picture a use case for them. Three class operators in PHP where usage can be a little confusing at times are $this, self and parent. In this article I will try to break things down and maybe you can see where you can use this in your code. Ok so let’s begin.
1. $this
- Refers to the current object instance.
- You use $this when you want to access properties or methods of the current object.
Example:
class Animal {
public $name;
public function setName($name) {
$this->name = $name; // "this object’s" name
}
public function getName() {
return $this->name; // returns "this object’s" name
}
}
$dog = new Animal();
$dog->setName("Buddy");
echo $dog->getName(); // Output: Buddy
2. self
- Refers to the current class itself, not the instance.
- Used for static methods and static properties.
- Does not depend on an object ($this is not available in static context).
Example:
class MathHelper {
public static $pi = 3.14159;
public static function circleArea($radius) {
return self::$pi * $radius * $radius; // accessing static property with self
}
}
echo MathHelper::circleArea(5); // Output: 78.53975
3. parent
- Refers to the immediate parent class.
- Used when you want to access a method or constructor from the parent class that is overridden in the child.
Example:
class Animal {
public function makeSound() {
return "Some generic animal sound";
}
}
class Dog extends Animal {
public function makeSound() {
// Call parent method, then add more
return parent::makeSound() . " and Woof!";
}
}
$dog = new Dog();
echo $dog->makeSound(); // Output: Some generic animal sound and Woof!
Now to summarize:
- $this refers to an instance of the class. It isn’t available in a static context, therefore cannot be used within a static class function.
- The self:: operator refers to the class-level property. It is used in a static context and refers to the actual class itself.
- The parent:: operator calls the overridden method from the parent class. It’s used in inheritance typically to call an overwritten method on the parent class.
Here is a really good example that should help you concieve these concepts and clear up any confusion.
class Animal {
public $name;
public static $kingdom = "Animalia";
public function __construct($name) {
$this->name = $name; // instance reference
}
public function describe() {
return "I am an animal named {$this->name}.";
}
public static function getKingdom() {
return "Kingdom: " . self::$kingdom; // static reference
}
}
class Dog extends Animal {
public function describe() {
// Use parent to get base description
$base = parent::describe();
// Add Dog-specific description
return $base . " I am also a dog that says Woof!";
}
public function introduce() {
// `$this` calls instance method
return $this->describe();
}
public static function getInfo() {
// `self` calls static property from this class (or parent if not overridden)
return "Dogs belong to " . self::$kingdom;
}
}
// ------------------- USAGE -------------------
// Create an object
$dog = new Dog("Buddy");
// $this -> instance reference
echo $dog->introduce();
// Output: I am an animal named Buddy. I am also a dog that says Woof!
echo "<br>";
// self -> static reference
echo Dog::getInfo();
// Output: Dogs belong to Animalia
echo "<br>";
// parent -> calling parent method inside child
echo $dog->describe();
// Output: I am an animal named Buddy. I am also a dog that says Woof!
echo "<br>";
// static method from parent
echo Animal::getKingdom();
// Output: Kingdom: Animalia
PHP Null-Safe(Null-Conditional) Operator (?->)
Null-Safe(Null-Conditional) Operator (?->)
The null-safe operator (?->), also known as the null-conditional operator, is a feature in several programming languages that allows you to safely access members of an object without explicitly checking for null references. If the object is null, the expression returns null instead of throwing a NullPointerException.
Basic Property Access
class User {
public ?Profile $profile = null;
}
class Profile {
public string $name = "John Doe";
public ?Address $address = null;
public function getName(): string {
return $this->name;
}
}
class Address {
public string $street = "123 Main St";
}
$user = new User();
// Safe property access
$name = $user?->profile?->name; // Returns null instead of error
var_dump($name); // NULL
// With actual data
$user->profile = new Profile();
$name = $user?->profile?->name;
var_dump($name); // string(8) "John Doe"
Method Calls
$user = new User();
// Safe method call
$result = $user?->profile?->getName(); // Returns null
var_dump($result); // NULL
$user->profile = new Profile();
$result = $user?->profile?->getName();
var_dump($result); // string(8) "John Doe"
Array Access with Null-Safe
class DataContainer {
public ?array $items = null;
public function getItems(): ?array {
return $this->items;
}
}
$container = new DataContainer();
// Safe array access
$firstItem = $container?->items[0] ?? 'default';
var_dump($firstItem); // string(7) "default"
$container->items = ['apple', 'banana'];
$firstItem = $container?->items[0] ?? 'default';
var_dump($firstItem); // string(5) "apple"
Chaining Multiple Levels
$user = new User();
$user->profile = new Profile();
$user->profile->address = new Address();
// Deep chaining
$street = $user?->profile?->address?->street;
var_dump($street); // string(11) "123 Main St"
// With null in chain
$user->profile->address = null;
$street = $user?->profile?->address?->street;
var_dump($street); // NULL
Used with Null-Coalescing Operator
$user = null;
// Null-safe + null coalescing
$userName = $user?->profile?->name ?? 'Guest';
var_dump($userName); // string(5) "Guest"
$user = new User();
$userName = $user?->profile?->name ?? 'Guest';
var_dump($userName); // string(5) "Guest"
$user->profile = new Profile();
$userName = $user?->profile?->name ?? 'Guest';
var_dump($userName); // string(8) "John Doe"
Used with Ternary Operator
$user = null;
$displayName = $user?->profile?->name ?: 'Anonymous User';
var_dump($displayName); // string(15) "Anonymous User"
Key Benefits
1. Reduces Boilerplate: Eliminates repetitive null checks
2. Prevents NullPointerExceptions: Safe access to nested properties
3. Cleaner Code: More readable and concise syntax
4. Short-Circuiting: Stops evaluation when null is encountered
5. Method Safety: Safe method calls on potentially null objects
Limitations
1. Read-Only: Cannot be used for assignment
2. Context-Specific: Only works in expressions, not statements
3. Language Support: Syntax varies between languages
4. Debugging: Can make null-related bugs harder to trace
The null-safe operator is particularly useful in scenarios with deep object graphs, API responses, configuration objects, and any situation where multiple nested objects might be null.