Javascript Articles
JavaScript Promises and Asynchronous Handling Explained
Have you ever made an HTTP API request in JavaScript, only to find the data you need is mysteriously unavailable? You're confident the server-side API works, as you've tested it repeatedly. The issue often lies in JavaScript's asynchronous nature.
JavaScript doesn't pause execution to wait for slow operations, like API calls, to complete. Instead, it triggers the request and immediately moves on to the next line of code. By the time your script tries to use the response data, the request may not have finished.
This is where the Promise object becomes essential. A Promise represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Let's explore how to use them effectively.
First let’s take a look at the most commonly used methods available on a JavaScript Promise object (Promise.then()):
1. Basic Promise Handling with .then()
The .then() method is the primary way to interact with a Promise. You can pass it two functions: one to handle a successful resolution and another to handle a rejection.
let name = "Mary";
const promise = new Promise((resolve, reject) => {
name == "Mary" ? resolve(name) : reject(name);
});
// promise.then(onFulfilled, onRejected)
promise.then(
x => console.log(`Name resolved: ${x}`), // Called if resolved
x => console.log(`Name rejected: ${x}`) // Called if rejected
);
// Expected output: "Name resolved: Mary"
2. Chaining Multiple .then() Methods
Promises are powerful because they can be chained, allowing you to define a sequence of asynchronous steps. Each .then() in the chain receives the result from the previous one.
let name = "Mary";
// Function passed to the Promise constructor
const analyzeName = (resolve, reject) => {
name == "Mary" ? resolve(name) : reject(name);
};
// Handler for a resolved promise
const nameResolved = (x) => {
console.log(`Name resolved: ${x}`);
return x; // Pass the value to the next .then()
};
// Handler for a rejected promise
const nameRejected = (x) => {
console.log(`Name rejected: ${x}`);
return x; // Even on rejection, we can pass the value down the chain
};
// Subsequent steps in the process
const step2 = (x) => {
console.log(`Step 2: Processing ${x}`);
return x;
};
const step3 = (x) => {
console.log(`Final Step: ${x}`);
return x;
};
const namePromise = new Promise(analyzeName);
namePromise
.then(nameResolved, nameRejected) // Handles the initial result
.then(step2) // Receives the value from nameResolved/nameRejected
.then(step3); // Receives the value from step2
// Console Output:
// Name resolved: Mary
// Step 2: Processing Mary
// Final Step: Mary
By using Promises and its .then() method, you gain precise control over the flow of your asynchronous code. This ensures that each step waits for the previous one to complete before executing, which is the fundamental solution to the "missing data" problem in async operations like API calls. For modern, cleaner syntax, consider using async/await, which is built on top of Promises.
Here is a comprehensive example that builds on the previous explanation by adding .catch() and .finally() methods, which are crucial for robust promise handling.
While .then() handles successful outcomes, a complete promise chain needs ways to handle errors and cleanup operations. This is where .catch() and .finally() come in.
- catch() - Handles any rejection that occurs in the chain
- finally() - Executes regardless of success or failure, perfect for cleanup
Below I’ve included a real-world example with HTTP request and a more practical example of its use with proper error handling.
Practical Example: User Data Fetch with Complete Error Handling
// Simulate fetching user data from an API
const fetchUserData = (userId) => {
return new Promise((resolve, reject) => {
console.log(`Fetching data for user ${userId}...`);
// Simulate API call delay
setTimeout(() => {
const users = {
1: { id: 1, name: "Alice", role: "admin" },
2: { id: 2, name: "Bob", role: "user" }
};
const user = users[userId];
if (user) {
resolve(user); // Success case
} else {
reject(new Error(`User ${userId} not found`)); // Error case
}
}, 1000);
});
};
// Processing functions for our chain
const validateUserRole = (user) => {
console.log(`Validating role for: ${user.name}`);
if (user.role !== 'admin') {
throw new Error('Insufficient permissions'); // This will trigger .catch()
}
return user; // Pass to next .then()
};
const logAccess = (user) => {
console.log(`Access granted to ${user.name} (${user.role})`);
return user;
};
// Example 1: Successful chain
console.log('=== SUCCESSFUL REQUEST ===');
fetchUserData(1) // Returns Alice (admin)
.then(validateUserRole)
.then(logAccess)
.then(user => {
console.log(`Final success: ${user.name} is logged in`);
return user;
})
.catch(error => {
console.error('Error:', error.message);
return { error: true, message: error.message }; // Recover from error
})
.finally(() => {
console.log('Request completed - cleaning up resources\n');
});
// After 1 second, this will output:
// Fetching data for user 1...
// Validating role for: Alice
// Access granted to Alice (admin)
// Final success: Alice is logged in
// Request completed - cleaning up resources
Real-Word HTTP Request Example
// Real-world example with fetch API
const loadUserProfile = (userId) => {
console.log(`Starting profile load for user ${userId}`);
fetch(`/api/users/${userId}`)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json(); // Parse JSON response
})
.then(userData => {
console.log('User data received:', userData);
// Continue with data process in .then()
return processUserData(userData);
})
.then(processedData => {
updateUI(processedData);
})
.catch(error => {
console.error('Failed to load profile:', error);
showErrorMessage('Failed to load user profile');
})
.finally(() => {
hideLoadingSpinner(); // Always hide spinner, success or failure
console.log('Profile load operation completed');
});
};
// Mock functions for the example
const processUserData = (data) => {
console.log('Processing user data...');
return { ...data, processed: true };
};
const updateUI = (data) => {
console.log('Updating UI with:', data);
};
const showErrorMessage = (message) => {
console.log('Showing error:', message);
};
const hideLoadingSpinner = () => {
console.log('Loading spinner hidden');
};
// Simulate calling the function
// loadUserProfile(123);
As you can see from the last 2 examples, this pattern ensures your asynchronous code is robust, maintainable, and properly handles both success and failure scenarios.
Below is a comprehensive list of the static methods and instance methods available on a Promise:
Static Methods (Called on Promise class)
Promise.all()
- Returns a single Promise that resolves when all promises in the iterable have resolved
- Rejects immediately if any promise in the iterable rejects
- Results are in the same order as input promises
Promise.allSettled()
- Returns a single Promise that resolves when all promises in the iterable have settled (either fulfilled or rejected)
- Never rejects - always resolves with an array of outcome objects showing each promise's status and value/reason
Promise.any()
- Returns a single Promise that resolves when any promise in the iterable fulfills
- Only rejects if all promises are rejected (with an AggregateError)
Promise.race()
- Returns a single Promise that settles based on the first promise in the iterable to settle (whether fulfilled or rejected)
- Adopts the state and value/reason of the first settling promise
Promise.resolve()
-
Returns a Promise object that is resolved with the given value
-
Creates an immediately fulfilled promise
Promise.reject()
- Returns a Promise object that is rejected with the given reason
- Creates an immediately rejected promise
Instance Methods (Called on Promise instances)
.then()
- Attaches callbacks for when the promise is fulfilled or rejected
- Returns a new promise allowing for method chaining
- Takes two optional arguments: onFulfilled and onRejected handlers
.catch()
- Attaches a callback for when the promise is rejected
- Returns a new promise (sugar syntax for .then(null, onRejected))
.finally()
- Attaches a callback that executes regardless of fulfillment or rejection
- Useful for cleanup operations that should always run
- Returns a new promise that preserves the original settlement state
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();
});
Master JavaScript Asynchronous Programming with Promise.allSettled()
The Promise.allSettled() method is a powerful tool for handling multiple promises in JavaScript. It returns a single Promise that resolves with an array of objects, each representing the outcome of a promise in the input array.
Each outcome object contains a status property, which is either 'fulfilled' or 'rejected'.
- If the status is 'fulfilled', the object will also contain a value property with the resolved value.
- If the status is 'rejected', the object will contain a reason property with the error (typically the value passed to reject).
Key Difference: Promise.allSettled() vs. Promise.all()
Unlike Promise.all(), which immediately rejects if any promise in the iterable is rejected, Promise.allSettled() never short-circuits. It waits for all promises to settle (either fulfill or reject), making it ideal for use cases where you need to know the result of every asynchronous operation, regardless of individual failures. This provides a more robust way for error handling in async/await and promise chains.
When to use Promise.allSettled() in JavaScript?
Use it whenever you need to process the results of multiple independent asynchronous operations and you don't want a single failure to prevent you from handling the others. Common scenarios include making multiple API calls or database queries where individual failures are non-critical.
The following example demonstrates how to use Promise.allSettled() to handle a mix of successful and failed promises.
// Example: Handling multiple API calls or asynchronous tasks
const p1 = new Promise((resolve, reject) => {
setTimeout(resolve, 200, "Data for User 1"); // Simulates a successful API call
});
const p2 = new Promise((resolve, reject) => {
setTimeout(resolve, 200, "Data for User 2"); // Simulates another successful call
});
const p3 = new Promise((resolve, reject) => {
setTimeout(reject, 200, "User 3 not found"); // Simulates a failed API call (e.g., 404)
});
const p4 = new Promise((resolve, reject) => {
setTimeout(reject, 200, "Server error for User 4"); // Simulates a server error (e.g., 500)
});
// Execute all promises and handle results with allSettled
Promise.allSettled([p1, p2, p3, p4])
.then(results => {
console.log("All operations settled:");
results.forEach((result, index) => {
if (result.status === 'fulfilled') {
console.log(`Promise ${index + 1}: Success -`, result.value);
} else {
console.log(`Promise ${index + 1}: Failed -`, result.reason);
}
});
});
// ** CONSOLE OUTPUT **
// All operations settled:
// Promise 1: Success - Data for User 1
// Promise 2: Success - Data for User 2
// Promise 3: Failed - User 3 not found
// Promise 4: Failed - Server error for User 4
Understanding JavaScript Promise.all()
Promise.all() takes an array of promises and returns a single promise that fulfills when all input promises have been fulfilled, or rejects immediately if any of the input promises reject.
Basic Usage:
// resolve promise1
const promise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 200, "King");
});
// resolve promise2
const promise2 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, "Queen");
});
// Notice that all promises supplied must resolve or an error is
// thrown and the promise will be handled in catch()
Promise.all([promise1, promise2]).then(
(fulfilled) => {
console.log(`All fulfilled: ${fulfilled.length}`);
console.log(fulfilled)
}
).catch(e => console.log(e));
// All fulfilled:
// [ 'King', 'Queen' ]
All Promises Must Resolve:
If any Promise in the chain is rejected, a Promise error is returned and will be handled with Promise.catch(). It’s important to get into a habit of providing a Promise.catch() to handle any rejected results.
// All promises are resolved successfully! An array with resolved results
// from each of the fulfilled promises is provided to the chained
// Promise.then(x => console.log(x)) method.
Promise.all([
Promise.resolve("Success 1"),
Promise.resolve("Success 2"),
Promise.resolve("Success 3")
]).then(results => {
console.log(results); // ['Success 1', 'Success 2', 'Success 3']
});
Handling Rejections Gracefully:
// One promise rejects - all others are ignored
const promise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 200, "King");
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(reject, 100, "Queen rejected!");
});
Promise.all([promise1, promise2])
.then((fulfilled) => {
// This will NOT execute
console.log("All fulfilled");
})
.catch(e => {
console.log("Error:", e); // "Error: Queen rejected!"
});
// Output: "Error: Queen rejected!"
Order of Preservation:
A results array is returned ordered in the sequence in which the promise fulfills in the list. All promises are executed in parallel. The first promise to resolve will be the first element of the return array. Notice in this example the first promise in the supplied promises array is actually the last promise in the return array of resolved promises.
// Order of Preservation
// Results maintain the same order as input promises
Promise.all([
new Promise((resolve, reject) => {
setTimeout(resolve, 100, "First");
}),
Promise.resolve("Second"),
Promise.resolve("Third")
])
.then(results => {
console.log(results[0]); // "Second"
console.log(results[1]); // "Third"
console.log(results[2]); // "First"
});
Immediate Rejection:
Notice slowResolve below continues executing but the results are ignored. It’s handled in Promise.catch()
// If any promise rejects, Promise.all immediately rejects
// without waiting for other promises
const fastResolve = new Promise(resolve =>
setTimeout(resolve, 100, "Fast")
);
const slowResolve = new Promise(resolve =>
setTimeout(resolve, 500, "Slow")
);
const fastReject = new Promise((resolve, reject) =>
setTimeout(reject, 50, "Rejected!")
);
Promise.all([fastResolve, slowResolve, fastReject])
.then(results => {
// Never executes
console.log("Success:", results);
})
.catch(error => {
console.log("Caught:", error); // "Caught: Rejected!"
// Both fastResolve and slowResolve continue executing but its result are ignored
});
Always Include Proper Error Handling:
Promise.all([apiCall1(), apiCall2(), apiCall3()])
.then(([result1, result2, result3]) => {
// Process all results
console.log("All API calls succeeded");
})
.catch(error => {
console.error("One or more API calls failed:", error);
// Handle the error appropriately
});
Parallel Processing
It’s perfect for processing multiple API calls in parallel.
const userId = 123;
const api1 = new Promise(resolve => fetch(`/api/users/${userId}`));
const api2 = new Promise(
resolve => fetch(`/api/users/${userId}/posts`)
);
const api3 = new Promise(
resolve => fetch(`/api/users/${userId}/settings`)
);
Promise.all([
api1,
api2,
api2
])
.then(responses => Promise.all(responses.map(r => r.json())))
.then(([user, posts, settings]) => {
console.log("User profile, posts and settings loaded");
// Use all data
})
.catch(error => {
console.error(error);
});
Promise.all() Summary:
1. Promise.all() waits for all promises to resolve or any to reject
2. Order of results matches the input array order
3. Fast failure - rejects immediately on first rejection
4. Always use .catch() to handle potential rejections
5. Perfect for parallel operations that don't depend on each other
If you need different behavior (like waiting for all promises to settle regardless of outcome), checkout Promise.allSettled().
Mastering Promise Chaining with .then() in JavaScript
Have you ever made an HTTP API request in JavaScript, only to find the data you need is mysteriously unavailable? You're confident the server-side API works, as you've tested it repeatedly. The issue often lies in JavaScript's asynchronous nature.
JavaScript doesn't pause execution to wait for slow operations, like API calls, to complete. Instead, it triggers the request and immediately moves on to the next line of code. By the time your script tries to use the response data, the request may not have finished.
This is where the Promise object becomes essential. A Promise represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Let's explore how to use them effectively.
1. Basic Promise Handling with .then()
The .then() method is the primary way to interact with a Promise. You can pass it two functions: one to handle a successful resolution and another to handle a rejection.
var name = "Mary"
const promise = new Promise((resolve, reject) => {
name == "Mary" ? resolve(name) : reject(name)
});
// promise.then(ifResolved, ifRejected)
promise.then(
x => console.log(`name resolved: ${x}`),
x => console.log(`name rejected: ${x}`)
) // expected output "name resolved: Mary"
2. Chaining Multiple .then() Methods
Promises are powerful because they can be chained, allowing you to define a sequence of asynchronous steps. Each .then() in the chain receives the result from the previous one.
var name = "Mary"
// initial method provided to the Promise
const analyzeName = (resolve, reject) => {
name == "Mary" ? resolve(name) : reject(name)
}
// method to handle resolved
const nameResolved = x => {
console.log(`Name resolved: ${x}`)
return x
}
// method to handle rejected
const nameRejected = x => {
console.log(`Name rejected: ${x}`)
return x
}
// Step 2
const step2 = x => {
console.log(`Step 2: ${x}`)
return x
}
// Step 3
const step3 = x => {
console.log(`Final Step: ${x}`)
return x
}
const namePromise = new Promise(analyzeName)
namePromise.then(
x => nameResolved(x), // Expected "Name Resolved: Mary"
x => nameRejected(x) // Expected "Name Rejected Mary"
)
.then(x => step2(x)) // Expected "Step 2: Mary"
.then(x => step3(x)) // Expected "Final Step: Mary"
// Name Resolved: Mary
// Step 2: Mary
// Final Step: Mary
Key Takeaway
By using Promises and their .then() method, you gain precise control over the flow of your asynchronous code. This ensures that each step waits for the previous one to complete before executing, which is the fundamental solution to the "missing data" problem in async operations like API calls. For modern, cleaner syntax, consider using async/await, which is built on top of Promises.
How to use JavaScript Promise catch()
There are a few ways to take advantage of the Promise catch method. The catch() method is run when the Promise is rejected or throws an error. Return value from a Promise is passed forward to the catch() method. Promises can be chained as well. It simply forwards the return value from the chained Promise to the catch method if the Promise is rejected or an error is thrown.
A basic example of using catch() with a Promise reject:
// using Promise.reject
let rejectPromise = new Promise(function(resolve, reject){
reject("promise rejected")
})
function displayCatch(x) {
console.log(x)
}
rejectPromise.catch(x => displayCatch(x))
A basic example of using catch() by throwing an error from the promise:
// throw an error
let promiseError = new Promise(function(resolve, reject){
throw "throw error"
})
function displayCatch(x) {
console.log(x)
}
promiseError.catch(x => displayCatch(x));
Chained promises. Reject or throw error from chained Promise:
let resolvePromise = new Promise(function(resolve, reject) {
setTimeout(resolve, 50, "resolved chained");
})
function resolveDisplay(x) {
console.log(x)
throw "throw error from chained Promise"
}
function displayCatch(x) {
console.log(x)
}
resolvePromise.then(x => resolveDisplay(x)).catch(x => displayCatch(x))
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()) |
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
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
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