JavaScript examples / cookbook
Practical, runnable JavaScript snippets: JSON handling, iterating arrays and objects, regex and more. Click any example to open it in the interactive JavaScript playground and run it in your browser.
let example = {
intField: 1,
strField: "hello",
boolField: false
};
console.log("default javascript representation");
console.log(example);
// to json
let exampleJson = JSON.stringify(example, null, 2);
console.log("json:");
console.log(exampleJson);
// load json
let parsedObj = JSON.parse(exampleJson);
if (parsedObj['intField'] !== example['intField']) {
throw new Error("Assertion failed");
}
exampleJson;Example converting to and from JSON string using Javascript
Open in JavaScript playgroundconst fruits = ["apple", "banana", "cherry", "date", "elderberry"];
// 1. Using a for loop
console.log("Using a for loop:");
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
console.log("Using a for...of loop:");
// 2. Using a for...of loop
for (const fruit of fruits) {
console.log(fruit);
}
console.log("Using forEach method:");
// 3. Using forEach method
fruits.forEach(function(fruit) {
console.log(fruit);
});
console.log("Using map method (typically for transforming array):");
// 4. Using map method (typically for transforming array, but we'll use it for iteration here)
fruits.map(fruit => {
console.log(fruit);
return fruit; // Map requires a return, though in this case we're not saving the result
});
console.log("Using for...in loop (not recommended for arrays, but possible):");
// 5. Using for...in loop (not recommended for arrays due to possibility of iterating over non-index properties)
for (const index in fruits) {
console.log(fruits[index]);
}
fruits;Example iterating over array using Javascript
Open in JavaScript playground// Example JavaScript code to demonstrate how to use regex to validate email addresses
// Function to validate email address using regex
function validateEmail(email) {
// Define the regular expression for validating an email
// The regex pattern explained:
// ^ asserts position at start of the string
// [a-zA-Z0-9._%+-]+ matches one or more of the allowed characters before the @
// @ matches the literal @ symbol
// [a-zA-Z0-9.-]+ matches one or more of the allowed characters for the domain part
// . matches the literal dot symbol
// [a-zA-Z]{2,} matches two or more alphabetic characters for the top-level domain
// $ asserts position at the end of the string
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/;
// Test the email against the regex pattern
const isValid = emailRegex.test(email);
// Log the regex pattern used for validation
console.log("Regex Pattern: ", emailRegex);
// Log the email being tested and whether it is valid
console.log("Testing Email: ", email);
console.log("Is Valid: ", isValid);
return isValid;
}
// Example email inputs to test the validation function
const testEmails = [
"test@example.com", // Valid email
"user.name@domain.co", // Valid email
"invalid-email@", // Invalid email (missing domain part)
"@example.com", // Invalid email (missing local part)
"user@domain@domain.com", // Invalid email (multiple @ symbols)
"user@domain.c", // Invalid email (top-level domain too short)
];
// Loop through each test email and validate it
testEmails.forEach(email => {
console.log("\n---\n");
validateEmail(email);
});Example validating email using regex in Javascript
Open in JavaScript playground// Example JavaScript code to demonstrate different ways to iterate over an object's key-value pairs
// Define an object with some key-value pairs
const person = {
name: "Alice",
age: 30,
occupation: "Engineer"
};
// Using for...in loop to iterate over the object's keys
console.log("Using for...in loop:");
for (const key in person) {
if (person.hasOwnProperty(key)) { // Check if the property is directly on the object
console.log(`Key: ${key}, Value: ${person[key]}`);
}
}
// Using Object.keys() method to get an array of keys and forEach to iterate
console.log("\nUsing Object.keys() and forEach:");
Object.keys(person).forEach(key => {
console.log(`Key: ${key}, Value: ${person[key]}`);
});
// Using Object.values() method to get an array of values and forEach to iterate
console.log("\nUsing Object.values() and forEach:");
Object.values(person).forEach(value => {
console.log(`Value: ${value}`);
});
// Using Object.entries() method to get an array of [key, value] pairs and forEach to iterate
console.log("\nUsing Object.entries() and forEach:");
Object.entries(person).forEach(([key, value]) => {
console.log(`Key: ${key}, Value: ${value}`);
});
// Using for...of loop with Object.entries() to iterate over [key, value] pairs
console.log("\nUsing for...of loop with Object.entries():");
for (const [key, value] of Object.entries(person)) {
console.log(`Key: ${key}, Value: ${value}`);
}
// Using for...of loop with Object.keys() to iterate over keys and access values
console.log("\nUsing for...of loop with Object.keys():");
for (const key of Object.keys(person)) {
console.log(`Key: ${key}, Value: ${person[key]}`);
}
// Using for...of loop with Object.values() to iterate over values
console.log("\nUsing for...of loop with Object.values():");
for (const value of Object.values(person)) {
console.log(`Value: ${value}`);
}Example iterating over object using Javascript
Open in JavaScript playground