5 fun JavaScript coding exercises

5 JavaScript coding Exercises 1

Reverse a String:
FizzBuzz:
Palindrome Checker:
Random Number Generator:
Capitalize the First Letter of Each Word:

Reverse a String:

Write a function that takes a string as an argument and returns the string in reverse order. For example, if the input string is “hello”, the output should be “olleh”.

function reverseString(str) {

  return str.split(“”).reverse().join(“”);

}

console.log(reverseString(“hello”));

FizzBuzz:

Write a function that takes an integer n as an argument and prints out numbers from 1 to n. For multiples of 3, print “Fizz” instead of the number. For multiples of 5, print “Buzz”. For multiples of both 3 and 5, print “FizzBuzz”.

function fizzBuzz(n) {

  for (let i = 1; i <= n; i++) {

    if (i % 3 === 0 && i % 5 === 0) {

      console.log(“FizzBuzz”);

    } else if (i % 3 === 0) {

      console.log(“Fizz”);

    } else if (i % 5 === 0) {

      console.log(“Buzz”);

    } else {

      console.log(i);

    }

  }

}

fizzBuzz(15);

Palindrome Checker:

Write a function that takes a string as an argument and returns true if the string is a palindrome (reads the same backward as forward), otherwise false.

function isPalindrome(str) {

  const reversedStr = str.split(“”).reverse().join(“”);

  return str === reversedStr;

}

console.log(isPalindrome(“racecar”));

console.log(isPalindrome(“hello”));

Random Number Generator:

Write a function that generates a random number between 0 and a given maximum value (inclusive).

function getRandomNumber(max) {

  return Math.floor(Math.random() * (max + 1));

}

console.log(getRandomNumber(10));

Capitalize the First Letter of Each Word:

Write a function that takes a string as an argument and returns the same string with the first letter of each word capitalized.

function capitalizeWords(str) {

  return str.split(” “).map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(” “);

}

console.log(capitalizeWords(“hello world”));