JavaScript Programming Labs

Master JavaScript through hands-on coding challenges. Write real code, get instant feedback, and build practical web development skills.

Array Methods & String Manipulation - Module 3

Master powerful array methods and string operations used in real-world JavaScript development.

Lab 7: Map, Filter & Reduce
Intermediate
Coding Challenge
Your Task: Master the three most powerful array methods in JavaScript: map(), filter(), and reduce(). These functional programming methods are essential for modern JavaScript development.

Detailed Requirements:

1. Create an array of numbers - Start with const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

2. Use map() to transform each element - The map() method creates a NEW array by calling a function on every element. It does NOT modify the original array. Create a new array with each number doubled.
const doubled = numbers.map(num => num * 2); // Result: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] // map() takes a callback: (element, index, array) => newValue
3. Use filter() to select elements - The filter() method creates a NEW array with elements that pass a test (return true). Filter the numbers to get only even numbers.
const evens = numbers.filter(num => num % 2 === 0); // Result: [2, 4, 6, 8, 10] // filter() keeps elements where callback returns true
4. Use reduce() to calculate a single value - The reduce() method reduces an array to a single value by executing a reducer function. Calculate the sum of all numbers.
const sum = numbers.reduce((acc, num) => acc + num, 0); // Result: 55 // reduce(callback, initialValue) // callback: (accumulator, currentValue, index, array) => newAccumulator
5. Chain multiple methods together - One of the most powerful features is chaining. Filter even numbers, double them, then sum them.
const result = numbers .filter(n => n % 2 === 0) // [2, 4, 6, 8, 10] .map(n => n * 2) // [4, 8, 12, 16, 20] .reduce((a, b) => a + b, 0); // 60
💡 Pro Tips:
map() always returns an array of the SAME length
filter() returns an array of the SAME or SMALLER length
reduce() can return any type (number, string, object, array)
• Always provide an initial value to reduce() to avoid errors with empty arrays
• These methods are non-mutating - they don't change the original array

⚠️ Common Mistakes to Avoid:
• Forgetting to return a value in map/filter callbacks (when using braces)
• Confusing map() with forEach() (forEach returns undefined)
• Not providing initial value to reduce()

Expected Output:
Original: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Doubled: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] Even numbers: [2, 4, 6, 8, 10] Sum: 55 Chained result: 60

Requirements Checklist

Create an array of numbers (1-10)
Use map() to double each number
Use filter() to get even numbers
Use reduce() to calculate the sum
Chain methods together
Print all results with console.log()
Console Output
// Click "Run Code" to execute your JavaScript // Your console.log() output will appear here
Hints & Tips
• Map syntax: array.map(element => transformedElement)
• Filter syntax: array.filter(element => condition)
• Reduce syntax: array.reduce((acc, curr) => acc + curr, initialValue)
• Arrow function shorthand: n => n * 2 (implicit return)
• Chaining: arr.filter(...).map(...).reduce(...)
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below

Lab 8: String Methods
Beginner
Coding Challenge
Your Task: Master essential string manipulation methods in JavaScript. Strings are immutable - all methods return NEW strings without modifying the original.

Detailed Requirements:

1. Create a string variable - Start with a sentence: const message = " Hello, JavaScript World! "; (note the spaces)

2. Use trim() to remove whitespace - Removes whitespace from both ends of a string. Also available: trimStart() and trimEnd().
const trimmed = message.trim(); // "Hello, JavaScript World!" (spaces removed)
3. Use toUpperCase() and toLowerCase() - Convert case of all characters. Useful for case-insensitive comparisons.
const upper = message.toUpperCase(); // " HELLO, JAVASCRIPT WORLD! " const lower = message.toLowerCase(); // " hello, javascript world! "
4. Use includes() to check for substring - Returns true if the string contains the specified substring, false otherwise. Case-sensitive!
message.includes("JavaScript"); // true message.includes("Python"); // false
5. Use split() to convert to array - Splits a string into an array using a delimiter. Very useful for parsing data.
const words = "apple,banana,orange".split(","); // ["apple", "banana", "orange"] "Hello World".split(" "); // ["Hello", "World"] "Hello".split(""); // ["H", "e", "l", "l", "o"]
6. Use replace() to substitute text - Replaces first occurrence. Use replaceAll() or regex with /g flag for all occurrences.
"Hello World".replace("World", "JavaScript"); // "Hello JavaScript" "aaa".replaceAll("a", "b"); // "bbb"
💡 Pro Tips:
• Strings are immutable - methods return new strings, don't modify original
slice(start, end) extracts a section (end not included)
substring(start, end) similar to slice but handles negative indices differently
startsWith() and endsWith() check string boundaries
padStart() and padEnd() add padding to reach desired length

⚠️ Common Mistakes to Avoid:
• Forgetting that includes() is case-sensitive
• Expecting string methods to modify the original string
• Using == instead of === for string comparison

Expected Output:
Original: " Hello, JavaScript World! " Trimmed: "Hello, JavaScript World!" Uppercase: " HELLO, JAVASCRIPT WORLD! " Lowercase: " hello, javascript world! " Includes 'JavaScript': true Words array: ["Hello,", "JavaScript", "World!"] Replaced: "Hello, Python World!"

Requirements Checklist

Create a string variable with spaces
Use trim() to remove whitespace
Use toUpperCase() and toLowerCase()
Use includes() to check for substring
Use split() to convert string to array
Use replace() to substitute text
Console Output
// Click "Run Code" to execute your JavaScript
Hints & Tips
• Trim spaces: str.trim() removes whitespace from both ends
• Case conversion: str.toUpperCase() / str.toLowerCase()
• Check substring: str.includes("text") returns true/false
• Split to array: str.split(" ") splits by space
• Replace text: str.replace("old", "new")
• Get length: str.length (property, not method)
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below

Lab 9: Template Literals & Destructuring
Intermediate
Coding Challenge
Your Task: Master modern ES6+ features: template literals for string interpolation and destructuring for extracting values from arrays and objects.

Detailed Requirements:

1. Create variables for template literal demo - Create name, age, and city variables.

2. Use template literals for string interpolation - Template literals use backticks (`) and allow embedding expressions with ${expression}. Much cleaner than string concatenation!
const name = "Alice"; const age = 25; const greeting = `Hello, my name is ${name} and I am ${age} years old.`; // "Hello, my name is Alice and I am 25 years old." // You can include expressions: const message = `Next year I'll be ${age + 1} years old.`; // Multi-line strings (no \n needed): const multiLine = `Line 1 Line 2 Line 3`;
3. Use array destructuring - Extract values from arrays into distinct variables. Order matters!
const colors = ["red", "green", "blue"]; const [first, second, third] = colors; // first = "red", second = "green", third = "blue" // Skip elements with empty slots: const [primary, , tertiary] = colors; // primary = "red", tertiary = "blue" // Rest operator to collect remaining: const [head, ...tail] = colors; // head = "red", tail = ["green", "blue"]
4. Use object destructuring - Extract properties from objects. Names must match property names (unless renamed).
const person = { name: "Bob", age: 30, city: "NYC" }; const { name, age, city } = person; // name = "Bob", age = 30, city = "NYC" // Rename during destructuring: const { name: personName, age: personAge } = person; // personName = "Bob", personAge = 30 // Default values: const { name, country = "USA" } = person; // country = "USA" (default, since it doesn't exist)
5. Combine destructuring with function parameters - Very common pattern in modern JavaScript!
// Instead of: function greet(person) { return person.name; } function greet({ name, age }) { return `${name} is ${age} years old`; } greet({ name: "Alice", age: 25 }); // "Alice is 25 years old"
💡 Pro Tips:
• Template literals can contain any valid JavaScript expression
• Nested destructuring: const { address: { city } } = person;
• Swap variables: [a, b] = [b, a];
• Destructuring in loops: for (const { name } of people) { }

⚠️ Common Mistakes to Avoid:
• Using regular quotes instead of backticks for template literals
• Forgetting that object destructuring uses property names
• Not providing defaults for potentially undefined properties

Expected Output:
Template: Hello, Alice! You are 25 years old and live in Seattle. Array destructuring: red, green, blue Object destructuring: Bob, 30, NYC Function with destructuring: Charlie is 28 years old

Requirements Checklist

Create variables (name, age, city)
Use template literals with ${} interpolation
Use array destructuring
Use object destructuring
Create a function using destructured parameters
Print all results with console.log()
Console Output
// Click "Run Code" to execute your JavaScript
Hints & Tips
• Template literal: `Hello, ${name}!` (use backticks!)
• Array destructuring: const [a, b, c] = array;
• Object destructuring: const { prop1, prop2 } = object;
• Rename in destructuring: const { name: newName } = obj;
• Function params: ({ name, age }) => `${name}: ${age}`
• Default values: const { x = 10 } = obj;
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below