10 JavaScript Coding
Exercises with Explanation
and Code
1. Reverse a String: 1
2. Factorial of a Number: 2
3. Check for Palindrome: 3
4. Find the Longest Word: 4
5. Title Case a Sentence: 5
6. Return Largest Numbers in Arrays: 6
7. Check if a String Contains Another String: 7
8. Count the Number of Occurrences of a Character: 8
9. Filter Numbers from an Array: 9
10. Calculate the Average of an Array: 10
1. Reverse a String:
Description: Write a function to reverse a string.
Code:
function reverseString(str) {
// Using split, reverse, and join methods
return str.split("").reverse().join("");
Learn more about code with Examples and Source Code
Laurence Svekis Courses https://basescripts.com/
1
}
// Example usage
const str = "Hello world!";
const reversedStr = reverseString(str);
console.log(reversedStr); // !dlrow olleH
2. Factorial of a Number:
Description: Write a function to calculate the factorial of a number.
Code:
function factorial(n) {
// Base case
if (n === 0) return 1;
// Recursive case
return n * factorial(n - 1);
Learn more about code with Examples and Source Code
Laurence Svekis Courses https://basescripts.com/
2
// Example usage
const num = 5;
const factorialResult = factorial(num);
console.log(factorialResult); // 120
3. Check for Palindrome:
Description: Write a function to check if a string is a palindrome
(reads the same backwards and forwards).
Code:
function isPalindrome(str) {
// Convert string to lowercase and remove whitespace
str = str.toLowerCase().replace(/\s/g, "");
// Compare string with its reversed version
return str === str.split("").reverse().join("");
// Example usage
const word = "racecar";
Learn more about code with Examples and Source Code
Laurence Svekis Courses https://basescripts.com/
3
const palindromeCheck = isPalindrome(word);
console.log(palindromeCheck); // true
4. Find the Longest Word:
Description: Write a function to find the longest word in a
sentence.
Code:
function longestWord(sentence) {
// Split sentence into words
const words = sentence.split(" ");
// Sort words by length (descending)
words.sort((a, b) => b.length - a.length);
// Return the first word (longest)
return words[0];
// Example usage
const sentence = "The quick brown fox jumps over the lazy dog.";
Learn more about code with Examples and Source Code
Laurence Svekis Courses https://basescripts.com/
4
const longestWordResult = longestWord(sentence);
console.log(longestWordResult); // jumps
5. Title Case a Sentence:
Description: Write a function to convert a sentence to title case.
Code:
function titleCase(sentence) {
// Split sentence into words
const words = sentence.split(" ");
// For each word, capitalize the first letter and lowercase the rest
words.forEach((word, index) => {
words[index] = word.charAt(0).toUpperCase() +
word.slice(1).toLowerCase();
});
// Join words with spaces
return words.join(" ");
Learn more about code with Examples and Source Code
Laurence Svekis Courses https://basescripts.com/
5
// Example usage
const sentence = "hello world!";
const titleCasedSentence = titleCase(sentence);
console.log(titleCasedSentence); // Hello World!
6. Return Largest Numbers in Arrays:
Description: Write a function to return the largest numbers in an
array.
Code:
function largestNumbers(arr) {
// Use Math.max and spread operator
return Math.max(...arr);
// Alternative using loops and conditional statements
// let largest = arr[0];
// for (let i = 1; i < arr.length; i++) {
// if (arr[i] > largest) largest = arr[i];
// }
// return largest;
Learn more about code with Examples and Source Code
Laurence Svekis Courses https://basescripts.com/
6
}
// Example usage
const numbers = [1, 5, 3, 8, 2];
const largestNumber = largestNumbers(numbers);
console.log(largestNumber); // 8
7. Check if a String Contains Another String:
Description: Write a function to check if a string contains another
string.
Code:
function containsString(str1, str2) {
// Use includes method
return str1.includes(str2);
// Alternative using indexOf method
// return str1.indexOf(str2) !== -1;
Learn more about code with Examples and Source Code
Laurence Svekis Courses https://basescripts.com/
7
// Example usage
const string1 = "Hello JavaScript";
const string2 = "JavaScript";
const containsCheck = containsString(string1, string2);
console.log(containsCheck); // true
8. Count the Number of Occurrences of a
Character:
Description: Write a function to count the number of times a
character appears in a string.
Code:
function countChar(str, char) {
// Use split and filter methods
return str.split("").filter((c) => c === char).length;
// Alternative using a loop and counter
// let count = 0;
// for (let i = 0; i < str.length; i++) {
Learn more about code with Examples and Source Code
Laurence Svekis Courses https://basescripts.com/
8
// if (str[i] === char) count++;
// }
// return count;
// Example usage
const str = "apple";
const char = "p";
const charCount = countChar(str, char);
console.log(charCount); // 2
9. Filter Numbers from an Array:
Description: Write a function to filter out all non-numeric values
from an array.
Code:
function filterNumbers(arr) {
// Use filter method and isNaN function
return arr.filter((num) => !isNaN(num));
Learn more about code with Examples and Source Code
Laurence Svekis Courses https://basescripts.com/
9
// Alternative using a loop and conditional statements
// const filteredArray = [];
// for (let i = 0; i < arr.length; i++) {
// if (!isNaN(arr[i])) filteredArray.push(arr[i]);
// }
// return filteredArray;
// Example usage
const mixedArray = ["1", 2, "apple", 3, "banana", 5];
const filteredNumbers = filterNumbers(mixedArray);
console.log(filteredNumbers); // [1, 2, 3, 5]
10. Calculate the Average of an Array:
Description: Write a function to calculate the average of all
elements in an array.
Code:
function average(arr) {
Learn more about code with Examples and Source Code
Laurence Svekis Courses https://basescripts.com/
10
// Use reduce method and length property
return arr.reduce((acc, num) => acc + num, 0) / arr.length;
// Example usage
const numbers = [1, 2, 3, 4, 5];
const averageValue = average(numbers);
console.log(averageValue); // 3
These are just a few examples of simple JavaScript coding
exercises. By practicing these and other similar exercises, you can
improve your understanding of JavaScript syntax, logic, and
problem-solving skills.
Learn more about code with Examples and Source Code
Laurence Svekis Courses https://basescripts.com/
11