Web Development Articles

JavaScript Variable Types (var, const, let)

0 👍
👎 0
 MySQL

There are 3 types of variables commonly used in javascript.  The main difference with the let type it's block scope.  If it's defined inside of a block it can't be accessed outside of the block.   Let's look at each in more detail:

const

Variables defined with const cannot be Redeclared
Variables defined with const cannot be Reassigned
Variables defined with const have Block Scope


// INCORRECT - must be assigned a value when it's declared.
const x;  
x = 1.999;

// INCORRECT - it cannot be reassigned a value
const x = 1.999;

x = 8;  

// IF defined inside of a block it has block scope. Look at example below:
if( somecondition )
{
   const x = 9;
}
// x cannot be access here outside of the "block", curly brackets.
// Below are valid usage of const:
// Example 1:
if( condition )
{
   const x = 8;
   console.log(x);
}

// Example 2:
const x = 8;
if( condition )
{
   console.log(x);
}


Defining a Javascript Function

0 👍
👎 0
 NodeJS
 Javascript

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

 



Format Date and Time in JavaScript with Date Object

0 👍
👎 0
 VueJS
 Javascript

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())

 

Laravel Webpack.mix Asset Compilation AND Performance Optimization

0 👍
👎 0
 Laravel
 VueJS
 Javascript
 Blade

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

 

PHP Access Modifiers (public, private, protected)

0 👍
👎 0
 PHP
 LAMP

In PHP Object-Oriented programming, public, private, and protected are access modifiers (visibility keywords) used to control how properties (variables) and methods (functions) of a class can be accessed.

They are important in Object-Oriented Programming (OOP) because they enforce encapsulation (controlling how data is exposed and used).


Public
Members declared public can be accessed from inside the class, outside of the class and by subclasses (child classes).  If no visibility is specified on a property the default will be public.


class
Car {

    public $brand;

    public function setBrand($brand) {

   $this->brand = $brand; // accessible inside the class

    }

 }

 $car = new Car();

 $car->brand = "Toyota"; // accessible outside the class

echo $car->brand; // Output: Toyota


Private

Members declared private can only be accessed inside of the class that defines them.  They cannot be accessed from outside the class or by subclasses.

 


class Car {

    private $engineNumber;

    public function setEngineNumber($num) {

       $this->engineNumber = $num; // accessible inside the class

    }

 

    public function getEngineNumber() {

       return $this->engineNumber; // allowed via public method

    }

 }

 

 $car = new Car();

 $car->setEngineNumber("ENG123");

 // echo $car->engineNumber; ERROR: Cannot access private property

 echo $car->getEngineNumber(); // Output: ENG123

 

 

Protected

Members declared protected can be accessed inside of the class, in child(sub) classes that inherit from it.  They cannot be accessed directly from outside of the class… only subclasses.

 

class Vehicle {

  protected $type = "Generic Vehicle";

 

   protected function getType() {

       return $this->type;

   }

}

 

class Car extends Vehicle {

  public function showType() {

       return $this->getType(); // accessible in child class

   }

}

 

$car = new Car();

// echo $car->type; ERROR: Cannot access protected property

echo $car->showType(); // Output: Generic Vehicle

 

 

JavaScript Self-Invoked Functions (IIFEs)

0 👍
👎 0
 NodeJS
 Javascript

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

 

 

PostgreSQL many-to-many Relationship

0 👍
👎 0
 PostgreSQL

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;