Softlogic Systems - Placement and Training Institute in Chennai

Easy way to IT Job

Most Popular JavaScript Code Challenges for Beginners
Share on your Social Media

Most Popular JavaScript Code Challenges for Beginners

Published On: November 23, 2024

JavaScript is frequently utilized when creating websites and web apps. This article discusses JavaScript code challenges and solutions, so let’s explore some real-world applications. Use our JavaScript course syllabus to get started.

JS Code Challenges and Solutions

Here are the most popular JavaScript code challenges and solutions that are useful for beginners to ace their technical rounds or project challenges in top companies. 

Calculate Multiple of 3 or 5 Using JavaScript

Challenge: 3, 5, 6, and 9 result in listing every natural number below 10 that is a multiple of 3 or 5. These multiples add up to 23. Complete the answer so that, below the entered value, it returns the sum of all multiples of three or five.

Note: Only count the number once if it is a multiple of 3 and 5. Additionally, return 0 if a number is negative. 

Solution: Here is the code solution for the above challenge. 

const solution = number => 

{

   let sum = 0;

   for (let i = 3; i < number; i++) {

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

       sum += i;

    }

  }

  return sum;     

};

Valid Palindrome in JavaScript

Challenge: If a phrase reads the same forward and backward after all capital letters have been changed to lowercase letters and all non-alphanumeric characters have been eliminated, it is said to be a palindrome. 

  • Letters and numerals are examples of alphanumeric characters. 
  • If a string s is a palindrome, return true; if not, return false.

Solution: Here is the code solution for a valid palindrome challenge.

const isPalindrome = s => {

   const str = s.toLowerCase().replace(/[^a-z0-9]/g, ”);

   let start = 0;

   let end = str.length – 1;

   while (start < end) {

     if (str[start] !== str[end]) return false;

     start++;

     end–;

   }

  return true;

};

Convert Hours into Seconds using JavaScript

The units of time are hours and seconds. These units are crucial for daily routine organization, activity planning, and schedule management. Here, JavaScript will be used to transform hours into seconds.

Solution 1: Here is the code solution using a pre-defined JS function.

  • This method uses a function called convertHoursToSeconds defined in the code that accepts the hours as an input parameter and converts them to seconds. 
  • The function is then called with an hour value of 4. 
  • To convert it to seconds, enter the formula hours*60*60 inside the function. 
  • Return the outcome at the end. 

function convertHoursToSeconds(hours) 

{

    return hours * 60 * 60;

}

const hours = 4;

const seconds = convertHoursToSeconds(hours);

console.log(“Seconds:”, seconds);

Solution 2: Here is the code solution using Class.

We will construct a class called “TimeConverter” that will manage the conversion of hours to seconds and have a method called “convertToSeconds”. 

  • Use the new keyword to create an object of the TimeConverter class and instantiate it. 
  • The number of hours you wish to convert is passed as an argument when you use the convertToSeconds method on the converter object. 
  • Print the result.

class TimeConverter {

    convertToSeconds(hours) {

        return hours * 60 * 60;

    }

}

const converter = new TimeConverter();

const hours = 4;

const seconds = converter.convertToSeconds(hours);

console.log(“Seconds:”, seconds);

Learn the fundamentals with our top JavaScript tutorial for beginners

Duplicate Encoder

Challenge: Create a function that takes a string and turns it into a new string with each character in the new string being if it appears in the original string more than once. When figuring out whether a character is a duplicate, disregard capitalization.

Code Solution: 

const duplicateEncode = word => {

  const lowerWord = word.toLowerCase();

  let result = ”;

  for (const char of lowerWord) {

    lowerWord.indexOf(char) !== lowerWord.lastIndexOf(char)

      ? (result += ‘)’)

      : (result += ‘(‘);

  }

  return result;

};

Like System in Social Media Using JavaScript

The “like” system is likely familiar to you from Facebook and other social media platforms. Users have the option to “like” posts, images, and other content. The wording that should appear next to such an item is what we wish to produce.

Challenge: Create a function that returns a properly structured output string as indicated below, given an input array that contains the names of people who enjoy an item.

Code Solution: 

const likes = names => {

  const len = names.length;

  let output;

  if (len === 0) {

    output = ‘no one likes this’;

  } else if (len === 1) {

    output = `${names[0]} likes this`;

  } else if (len === 2) {

    output = `${names[0]} and ${names[1]} like this`;

  } else if (len === 3) {

    output = `${names[0]}, ${names[1]} and ${names[2]} like this`;

  } else {

    output = `${names[0]}, ${names[1]} and ${len – 2} others like this`;

  }

  return output;

};

Phone Number Generation Using JavaScript

Ever wonder how phone numbers are getting generated for millions of people today? Let’s understand through this JavaScript program. 

Challenge: Create a function that takes 10 integers (between 0 and 9) as input and outputs a string of those values as a phone number.

Code Solution: 

const createPhoneNumber = numbers => 

{

  // Using substrings

  const str = numbers.join(”);

  return `(${str.substring(0, 3)}) ${str.substring(3, 6)}-${str.substring(6)}`;

  // Alternative solution using RegEx

  // return numbers.join(”).replace(/(\d{3})(\d{3})(\d+)/, ‘($1) $2-$3’);

  // Alternative solution using reduce()

  // return numbers.reduce((acc, cur) => acc.replace(‘x’, cur), ‘(xxx) xxx-xxxx’);

};

Fine-tune your skills with our JavaScript project ideas

Bit Counting in JavaScript

Challenge: Create a function that accepts an integer as input and outputs the amount of bits in the binary version of that number that equal 1. The output is guaranteed to be non-negative. 

For instance, the function should return 5 in this instance, as the binary form of 1234 is 10011010010.

Code Solution:

const countBits = n => {

  return n.toString(2).split(‘0’).join(”).length;

};

FizzBuzz with JavaScript

Challenge: Create an application that outputs the numbers 1 through 100. 

  • But “Fizz” is used in place of the number for multiples of three prints, and “Buzz” is used in place of the number for multiples of five prints. 
  • Prints “FizzBuzz” for values that are multiples of both 3 and 5.

Code Solution:

const fizzBuzz = () => {

  let output;

  for (let num = 1; num <= 100; num++) {

    output = ”;

    if (num % 3 === 0) output += ‘Fizz’;

    if (num % 5 === 0) output += ‘Buzz’;

    console.log(output || num);

  }

};

Counting Duplicates Using JavaScript

Challenge: Count the number of unique, case-insensitive alphanumeric characters that appear more than once in the input string by writing a function.

Code Solution: 

const duplicateCount = text => {

  const lowercaseText = text.toLowerCase();

  let frequency = {};

  let count = 0;

  for (const letter of lowercaseText) {

    frequency[letter] = (frequency[letter] || 0) + 1;

    if (frequency[letter] === 2) count++;

  }

  return count;

};

Persistent Bugger Problem in JavaScript

Challenge: Create a function that, given a positive number num, returns the multiplicative persistence of that number (the number of steps required to multiply each digit by the others) and repeat the process until only one digit remains.

Code Solution: 

const persistence = num => {

  if (num < 10) return 0;

  let product = 1;

  while (num >= 10) {

    product *= num % 10;

    num = Math.floor(num / 10);

  }

  return 1 + persistence(product * num);

};

Fibonacci Series in JavaScript

Named for the mathematician Fibonacci, the Fibonacci number (or Fibonacci sequence) is a series of numbers that looks like this: 1, 2, 3, 5, 8, 13, 0… The first two numbers in the sequence are 0 and 1, and the subsequent number is always the sum of the first two.

Challenge: Create the function fib(), which takes one parameter, steps, and returns a number from the Fibonacci sequence. The position in the Fibonacci number is determined by the parameter steps. For instance, fib(0) yields zero, fib(4) yields three, and fib(15) yields 610.

Code Solution: 

const fib = steps => {

  if (steps < 2) return steps;

  return fib(steps – 2) + fib(steps – 1);

};

Review your skills with our top 20 JavaScript interview questions and answers

Find the Ideal Time to Purchase and Sell Stock

Challenge: An array of prices is provided to you, where prices[i] represents the stock’s price on the ith day. 

  • By selecting a particular day to purchase one stock and a different day later to sell that stock, you can optimize your profit.
  • Give back as much money as you can from this transaction. 
  • Return 0 if you can’t make any money.

Code Solution:

const maxProfit = prices => {

  let min = Number.MAX_SAFE_INTEGER;

  let profit = 0;

  for (let i = 0; i < prices.length; i++) {

    min = Math.min(prices[i], min);

    if (prices[i] – min > profit) {

      profit = prices[i] – min;

    }

  }

  return profit;

};

Conclusion

We hope these popular JavaScript code challenges and solutions will be helpful to gain practical exposure to JavaScript. Accelerate your web development career with our JavaScript training in Chennai.

Share on your Social Media

Just a minute!

If you have any questions that you did not find answers for, our counsellors are here to answer them. You can get all your queries answered before deciding to join SLA and move your career forward.

We are excited to get started with you

Give us your information and we will arange for a free call (at your convenience) with one of our counsellors. You can get all your queries answered before deciding to join SLA and move your career forward.