Darekdari / JavaScript Exercises

JavaScript Exercises and Solutions

13 JavaScript practice exercises with solutions on arrays, strings, objects and recursion. Try each task yourself, open the solution, then edit the code and run it right in your browser. Ideal javascript exercises for beginners and quick js exercises for daily practice.

13 exercisesRun in browserPortfolio readyBeginner friendly
01 / Overview

How to Use These JavaScript Practice Exercises

Every exercise below is a javascript function exercise: you get a task, write a function, and test it with an example. Open a solution with the + button, press Run to see the output, and edit the code to experiment. The tasks cover javascript variables exercises, loops, array methods, string handling and recursion.

A good way to practice

  • Try first. Write your own version before opening the solution.
  • Run often. Test with the example, then with your own inputs.
  • Solve it twice. Write a version with a loop, then with filter(), map() or reduce().
What changed from the original list: four tasks (palindrome, unique values, longest word, unique pairs) were shown with the code of a different task, so they now have correct solutions. The median solution no longer changes the original array, and the most-common-letter solution counts letters only, not digits or underscores.
02 / Arrays and numbers

Exercises 1 to 5: Arrays and Numbers

1. Sum of the squares of the odd numbers

Write a function that takes an array of numbers and returns the sum of the squares of all the odd numbers.

solution.js
function sumOfSquaresOfOdds(arr) {
  return arr.filter(num => num % 2 !== 0).reduce((acc, num) => acc + num ** 2, 0);
}

console.log(sumOfSquaresOfOdds([1, 2, 3, 4, 5])); // 35
2. Strings that appear in both arrays

Write a function that takes two arrays of strings and returns an array with all the strings that appear in both.

solution.js
function commonStrings(arr1, arr2) {
  const set2 = new Set(arr2);
  return [...new Set(arr1)].filter(str => set2.has(str));
}

console.log(commonStrings(['apple', 'banana', 'orange'], ['banana', 'kiwi', 'orange']));
// ['banana', 'orange']
3. Median of an array

Write a function that returns the median value of an array of numbers.

solution.js
function median(arr) {
  const sorted = [...arr].sort((a, b) => a - b); // copy, so arr is not changed
  const mid = Math.floor(sorted.length / 2);
  return sorted.length % 2 !== 0 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
}

console.log(median([1, 3, 2, 5, 4])); // 3
console.log(median([4, 1, 3, 2]));    // 2.5
4. Count the unique values

Write a function that returns the number of unique values in an array of numbers.

solution.js
function countUnique(arr) {
  return new Set(arr).size;
}

console.log(countUnique([1, 2, 2, 3, 3, 3, 4])); // 4
5. Unique pairs that add up to a target

Write a function that returns all unique pairs of numbers from an array that add up to a target value.

solution.js
function pairsWithSum(arr, target) {
  const seen = new Set();
  const pairs = new Set();
  for (const num of arr) {
    const need = target - num;
    if (seen.has(need)) {
      pairs.add([Math.min(num, need), Math.max(num, need)].join(','));
    }
    seen.add(num);
  }
  return [...pairs].map(p => p.split(',').map(Number));
}

console.log(pairsWithSum([1, 2, 3, 4, 5, 6, 3], 6)); // [[2, 4], [1, 5], [3, 3]]
03 / Strings

Exercises 6 to 9: Strings

6. Most common letter

Write a function that returns the most common letter in a string. If several letters tie, return an array of all of them.

solution.js
function mostCommonLetter(str) {
  const count = {};
  for (const ch of str.toLowerCase()) {
    if (/[a-z]/.test(ch)) count[ch] = (count[ch] || 0) + 1;
  }
  const max = Math.max(...Object.values(count));
  const top = Object.keys(count).filter(k => count[k] === max);
  return top.length === 1 ? top[0] : top;
}

console.log(mostCommonLetter('hello world')); // 'l'
console.log(mostCommonLetter('aabb'));        // ['a', 'b']
7. Capitalize each word

Write a function that capitalizes the first letter of each word and lowercases all other letters.

solution.js
function capitalizeWords(str) {
  return str
    .split(' ')
    .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
    .join(' ');
}

console.log(capitalizeWords('the quick bROWN fox')); // 'The Quick Brown Fox'
8. Palindrome check

Write a function that returns true if a string reads the same forwards and backwards, and false otherwise.

solution.js
function isPalindrome(str) {
  const clean = str.toLowerCase().replace(/[^a-z0-9]/g, '');
  for (let i = 0; i < Math.floor(clean.length / 2); i++) {
    if (clean[i] !== clean[clean.length - 1 - i]) return false;
  }
  return true;
}

console.log(isPalindrome('racecar'));                // true
console.log(isPalindrome('A man, a plan, a canal')); // false
console.log(isPalindrome('Was it a car or a cat I saw')); // true
9. Longest word

Write a function that returns the longest word in a string.

solution.js
function longestWord(str) {
  return str
    .split(/\s+/)
    .reduce((longest, word) => (word.length > longest.length ? word : longest), '');
}

console.log(longestWord('The quick brown fox jumped')); // 'jumped'
04 / Objects and classics

Exercises 10 to 13: Objects and Classic Functions

10. Oldest person

Write a function that takes an array of objects with a name and an age, and returns the name of the oldest person.

solution.js
function oldestPerson(people) {
  const oldest = people.reduce((acc, p) => (p.age > acc.age ? p : acc), people[0]);
  return oldest.name;
}

const people = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 20 }
];
console.log(oldestPerson(people)); // 'Bob'
11. Factorial (recursion)

Write a recursive function that returns the factorial of a number.

solution.js
function factorial(num) {
  if (num === 0) return 1;
  return num * factorial(num - 1);
}

console.log(factorial(5)); // 120
12. Greatest common divisor

Write a function that returns the greatest common divisor of two numbers using the Euclidean algorithm.

solution.js
function gcd(a, b) {
  return b === 0 ? a : gcd(b, a % b);
}

console.log(gcd(12, 18)); // 6
13. Remove duplicates

Write a function that removes duplicate values from an array and keeps the original order.

solution.js
function removeDuplicates(arr) {
  return arr.filter((item, index) => arr.indexOf(item) === index);
}

console.log(removeDuplicates([1, 2, 3, 2, 4, 3])); // [1, 2, 3, 4]

Want more javascript exercises and solutions? Browse our JavaScript projects, such as the maze game and the memory card game.

05 / FAQ

Frequently Asked Questions About JavaScript Exercises

What are good JavaScript exercises for beginners?

Start with small function exercises on arrays and strings, such as summing numbers, finding the median, counting unique values and checking palindromes. Each one practices variables, loops, array methods and return values.

How do I practice JavaScript effectively?

Try each task yourself before opening the solution, run your code often, then compare your approach with the solution and rewrite it a second way, for example with a loop and then with reduce().

Why does sort() change my original array?

Array.prototype.sort() sorts in place. Copy the array first with [...arr] if you need to keep the original order, as the median solution does.

How long does it take to learn JavaScript?

Most beginners learn the basics (variables, functions, loops, arrays) in a few weeks of regular practice, and become comfortable building projects after a few months.

06 / Languages

JavaScript FAQ in Turkish, Spanish, German and Arabic

Türkçe: JavaScript projeleri

JavaScript ile neler yapılabilir?

Web siteleri, mobil uygulamalar, oyunlar ve Node.js ile sunucu uygulamaları.

JavaScript öğrenmek ne kadar sürer?

Temel konular birkaç hafta, rahatça proje geliştirmek birkaç ay düzenli pratik gerektirir.

JavaScript hangi program?

Bir programlama dilidir. Tarayıcıda veya Node.js ile çalışır.

JavaScript neden popüler?

Her tarayıcıda çalışır, öğrenmesi kolaydır ve hem ön yüzde hem arka yüzde kullanılır.

Español: proyectos en JavaScript

¿Qué proyectos se pueden hacer con JavaScript?

Calculadoras, juegos, relojes, aplicaciones del clima y mucho más.

¿Qué es un proyecto en JavaScript?

Un programa o página web que combina variables, funciones y arrays para resolver un problema.

¿Cómo empezar un proyecto de JavaScript?

Crea un archivo .js, escribe una función pequeña y ejecútala en el navegador.

¿Qué programas se han hecho con JavaScript?

Sitios web, juegos de navegador, servidores con Node.js y aplicaciones con Electron.

Deutsch: JavaScript lernen

Wird JavaScript noch benötigt?

Ja. JavaScript ist die Standardsprache des Webs und läuft in jedem Browser.

Was kann man alles mit JavaScript machen?

Websites, Web-Apps, Spiele, Server-Anwendungen und kleine Projekte.

Ist JavaScript für Anfänger?

Ja. Man sieht Ergebnisse sofort im Browser.

Wie schwierig ist JavaScript?

Die Grundlagen sind leicht. Fortgeschrittene Themen brauchen mehr Übung.

العربية: مشاريع جافا سكريبت

تبحث عن مشاريع جافا سكريبت للمبتدئين؟ هذه التمارين مثال عملي يمكنك تجربته وتعديله مباشرة. ابحث أيضاً عن مشاريع جافا سكريبت جاهزة pdf أو مشروع جافا سكريبت github للمزيد من الشيفرات.

لست بحاجة إلى جافا سكريبت تحميل أو تحميل جافا سكريبت للاندرويد، فهي تعمل داخل المتصفح مباشرة. أما تفعيل جافا سكريبت على الهاتف فيتم من إعدادات المتصفح. وللتوسع جرّب مشاريع جافا للمبتدئين، مع ملاحظة أن جافا وجافا سكريبت لغتان مختلفتان.

Scroll to Top