17 JavaScript Function Exercises with solution

1. Write a JavaScript function to print the “Hello World” message

Function `displayMessage()` prints “Hello World” string using console.log() function.

function displayMessage() {
  console.log("Hello World");
}

displayMessage(); //"Hello World"

2. Write a function that returns the square of a number

Function `findSquare()` returns the square of the input number which is passed as an argument in the function call.

function findSquare(num) {
  return num*num;
}

console.log(findSquare(2)) //4
console.log(findSquare(9)) //81
console.log(findSquare(15)) //225

3. Write a function to convert Celsius to Fahrenheit

Function `calFahrenheit()` returns the converted Celsius value to Fahrenheit value based on the formula `(Celsius × 9/5) + 32 = Fahrenheit`

function calFahrenheit(cel) {
  return (cel*9/5)+32; //Conversion formula
}

console.log(calFahrenheit(0)) //32
console.log(calFahrenheit(20)) //68
console.log(calFahrenheit(40)) //104

4. Write a function to find the area of a given Rectangle

Function `rectangleArea()` returns the rectangle area provided the width and height as the argument.

function rectangleArea(a,b) {
  return `The area of rectangle is ${a*b}`;
}

console.log(rectangleArea(10,20)) //The area of rectangle is 200
console.log(rectangleArea(30,30)) //The area of rectangle is 900

5. Write a function to find the area and perimeter of a Circle

Function `circleValues()` returns the perimeter and area of the circle provided the radius as an argument for the function call.

function circleValues(rad) {
  return `Perimeter: ${2*Math.PI*rad}, Area: ${Math.PI*rad*rad}`;
}

console.log(circleValues(10)) //"Perimeter: 62.83, Area: 314.15"
console.log(circleValues(15)) //"Perimeter: 94.24, Area: 706.85"
console.log(circleValues(25)) //"Perimeter: 157.07, Area: 1963.49"

6. Write a function to reverse a number

Function `reverseNum()` returns the reversed number for the given argument number value. 

function reverseNum(num) {
  var reverse = 0;
  while(num != 0)
  {
    reverse = reverse * 10;
    reverse = reverse + num%10;
    num = Math.trunc(num/10); // Remove decimal places
  }
  return reverse;
}

console.log(reverseNum(123)) //321
console.log(reverseNum(5872)) //2785

7. Count number of Vowels in String

Function `countVowel()` returns the number of vowels in input string. Learn more about JavaScript String methods from javatpoint.com/javascript-string.

function countVowel(str) {
  var count = 0;
  str=str.toLowerCase();
  for(var i=0;i<str.length;i++){
    if(str.charAt(i)=="a"||str.charAt(i)=="e"||str.charAt(i)=="i"||
       str.charAt(i)=="o"||str.charAt(i)=="u"){
       count++; //Increment vowel count
    }
  }
  return count;
}

console.log(countVowel("Hello")) //2
console.log(countVowel("Umbrella")) //3

8. Flatten array of arrays using JavaScript reduce

Function `flattenArr()` flattens a 2D array by combining each sub array into 1D array by using JavaScript reduce.

function flattenArr(arr) {
  return arr.reduce((result, array) => result.concat(array));
}

console.log(flattenArr([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
// [1, 2, 3, 4, 5, 6, 7, 8, 9]

9. Write a function to check if an input string is a palindrome

Function `checkPalindrome()` return a boolean value based on whether the input string is palindrome or not.

function checkPalindrome(str) {
  for(var i=0;i<str.length;i++){
    if(str.charAt(i)!=str.charAt(str.length-i-1)){ // Comparison fail
      return false;
    }
  }
  return true;
}

console.log(findPalindrome("bannana")) //false
console.log(findPalindrome("racecar")) //true
console.log(findPalindrome("madam")) //true

10. Write a function to calculate simple interest based on the principle amount

Function `simpleInt()` returns a final amount based on the simple interest formula provided principal amount, rate of interest per year, and time on a yearly basis.

function simpleInt(principle, rate, time) {
  var finalAmt=principle + principle*time*rate;
  return finalAmt; 
}

console.log(simpleInt(20000,5,2)) //220000
console.log(simpleInt(150000,25,1)) //3900000

11. Write a function to calculate compound interest based on the principle amount

Function `compoundInt()` returns a final amount based on the compound interest formula provided principal amount, rate of interest per year, time on a yearly basis, and n as the number of times that interest is compounded per unit time.

function compoundInt(principle, rate, time, n) {
  var interest = principle * (Math.pow((1 + (rate / n)), (n * time)));
  return principle + interest;
}

console.log(compoundInt(20000,5,2,2)) //3021250
console.log(compoundInt(150000,25,1,2)) //27487500

12. Write a function to generate a random number

Function `genRandom()` return a generated random integer number between the provided start and end range.

function genRandom(start, end) {
  return Math.floor(Math.random() * end) + start
}

console.log(genRandom(1,10)) // random int between 1 to 10
console.log(genRandom(80,90)) // random int between 80 to 90

13. Write a function to find Factorial of a number

Function `getFactorial()` return the factorial of a number using the formula `n*(n-1)*(n-2)*…` .

function getFactorial(num) {
  if(num==1){
    return 1; // Termination condition
  }
  if(num==0 || num<0){
    return 0; // Termination condition
  }
  return num*getFactorial(num-1);
}

console.log(getFactorial(5)) // 120
console.log(getFactorial(12)) // 479001600

14. Write a function to add unlimited numbers

Function `addNumber()` return the sum of all the number passed as arguments of the function.

function addNumber(...args) {
  return args.reduce((total,num) => total+num); //Add numbers
}

console.log(addNumber(2,4,5)) // 11
console.log(addNumber(10,45,34,130)) // 219

15. Write a function to combine unlimited arrays

Function `addArrays()` return the concatenated array by combining all the arrays passed as an argument of the function.

function addArrays(...args) {
  return args.reduce((total,arr)=>total.concat(arr));
}

console.log(addArrays([2,3,4],[6,4,9],[34,6,4])) 
// [2, 3, 4, 6, 4, 9, 34, 6, 4]

16. Write a function to find the count of a letter in a string

Function `letterCount()` return the count of letter in a given string.

function letterCount(str, c) {
  var count=0;
  str=str.toLowerCase(); //Case insensitive
  for(var i=0;i<str.length;i++){
     if(str.charAt(i)==c){ 
       count++; //Increment count
     }
  }
  return count;
}

console.log(letterCount("Connect",'c')) // 2
console.log(letterCount("first person",'s')) // 2

17. Write a function to check if a number is Prime

Function `checkPrime()` return Boolean value based on whether the number is Prime or not.

function checkPrime(num, div=2) {
  // Base case
  if (num <= 2){
    return (num == 2) ? true : false;
  }

  // No Divisor case
  if (div * div > num){
    return true;
  }
    
  // Number is not prime if divisible
  if (num % div == 0){
    return false;
  }   
  // Recursive call with next divisor
  return checkPrime(num, div+1);
}

console.log(checkPrime(27)) // false
console.log(checkPrime(19)) // true

JavaScript beginner exercises