Open In App

Coding Challenge for Beginners | Coding Practice Challenges

Here’s a simple coding challenge suitable for beginners. This challenge involves writing a function in a programming language of your choice.

Table of Content



Challenge 1: Print Numbers from 1 to 10




for (let i = 1; i <= 10; i++) {
    console.log(i);
}

Challenge 2: Print Odd Numbers Less Than 100




for (let i = 1; i < 100; i += 2) {
   console.log(i);
}

Challenge 3: Print Multiplication Table with 7




for (let i = 1; i <= 10; i++) {
  console.log(`7 * ${i} = ${7 * i}`);
}

Challenge 4: Print All Multiplication Tables (1 to 10)




for (let i = 1; i <= 10; i++) {
  for (let j = 1; j <= 10; j++) {
    console.log(`${i} * ${j} = ${i * j}`);
  }
}

Challenge 5: Calculate Sum of Numbers from 1 to 10




let sum = 0;
for (let i = 1; i <= 10; i++) {
  sum += i;
}
console.log(sum);

Challenge 6: Calculate 10!




function factorial(n) {
  if (n === 0 || n === 1) return 1;
  return n * factorial(n - 1);
}
  
console.log(factorial(10));

Challenge 7: Sum of Odd Numbers (10 to 30)




let sum = 0;
for (let i = 11; i < 30; i += 2) {
  sum += i;
}
console.log(sum);

Challenge 8: Celsius to Fahrenheit Conversion




function celsiusToFahrenheit(celsius) {
  return (celsius * 9/5) + 32;
}
  
console.log(celsiusToFahrenheit(30));

Challenge 9: Fahrenheit to Celsius Conversion




function fahrenheitToCelsius(fahrenheit) {
  return (fahrenheit - 32) * 5/9;
}
  
console.log(fahrenheitToCelsius(86));

Challenge 10: Sum of Numbers in an Array




let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum);

Challenge 11: Average of Numbers in an Array




let numbers = [1, 2, 3, 4, 5];
let average = numbers.reduce((acc, curr) => acc + curr, 0) / numbers.length;
console.log(average);

Challenge 12: Positive Numbers in an Array (Solution 1)




function positiveNumbers(arr) {
  return arr.filter(num => num > 0);
}
  
console.log(positiveNumbers([-1, 2, -3, 4, -5]));

Challenge 12: Positive Numbers in an Array (Solution 2)




function positiveNumbers(arr) {
  let result = [];
  for (let num of arr) {
    if (num > 0) {
      result.push(num);
    }
  }
  return result;
}
  
console.log(positiveNumbers([-1, 2, -3, 4, -5]));

Challenge 12: Positive Numbers in an Array (Solution 3)




function positiveNumbers(arr) {
  let result = [];
  arr.forEach(num => {
    if (num > 0) {
      result.push(num);
    }
  });
  return result;
}
  
console.log(positiveNumbers([-12, 22, -3, 41, -15]));

Challenge 13: Maximum number in an array




let numbers = [5, 8, 3, 12, 7];
let max = Math.max(...numbers);
console.log(max);

Challenge 14: First 10 Fibonacci numbers without recursion




let fib = [0, 1];
for (let i = 2; i < 10; i++) {
    fib[i] = fib[i - 1] + fib[i - 2];
}
console.log(fib);

Challenge 15: nth Fibonacci number using recursion




function fibonacci(n) {
    if (n <= 1) {
        return n;
    }
    return fibonacci(n - 1) + fibonacci(n - 2);
}
console.log(fibonacci(5));

Challenge 16: Check if a number is prime




function isPrime(num) {
    if (num <= 1) return false;
    for (let i = 2; i <= Math.sqrt(num); i++) {
        if (num % i === 0) return false;
    }
    return true;
}
console.log(isPrime(11));

Challenge 17: Sum of digits of a positive integer




function sumOfDigits(num) {
    let sum = 0;
    while (num > 0) {
        sum += num % 10;
        num = Math.floor(num / 10);
    }
    console.log(sum);
}
sumOfDigits(123);

Challenge 18: First 100 prime numbers




function generatePrimes(count) {
    let primes = [];
    for (let i = 2; primes.length < count; i++) {
        if (isPrime(i)) {
            primes.push(i);
        }
    }
    console.log(primes);
}
generatePrimes(100);

Challenge 19: First “nPrimes” prime numbers greater than “startAt”




function generatePrimes(nPrimes, startAt) {
    let primes = [];
    let num = startAt + 1;
    while (primes.length < nPrimes) {
        if (isPrime(num)) {
            primes.push(num);
        }
        num++;
    }
    console.log(primes);
}
generatePrimes(5, 10);

Challenge 20: Rotate an array to the left 1 position




let arr = [1, 2, 3, 4, 5];
let temp = arr.shift();
arr.push(temp);
console.log(arr);

Challenge 21: Rotate an array to the right 1 position




let arr = [1, 2, 3, 4, 5];
let temp = arr.pop();
arr.unshift(temp);
console.log(arr);

Challenge 22: Reverse an array




let arr = [1, 2, 3, 4, 5];
let reversed = arr.reverse();
console.log(reversed);

Challenge 23: Reverse a string




let str = "Hello, Geeks!";
let reversed = str.split('').reverse().join('');
console.log(reversed);

Challenge 24: Merge two arrays




let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let merged = arr1.concat(arr2);
console.log(merged);

Challenge 25: Elements in the first or second array but not both




let arr1 = [1, 2, 3, 4];
let arr2 = [3, 4, 5, 6];
let result = arr1.filter(num => !arr2.includes(num)).concat(arr2.filter(num => !arr1.includes(num)));
console.log(result);

Challenge 26: Elements in the first array but not in the second




let arr1 = [1, 2, 3, 4];
let arr2 = [3, 4, 5, 6];
let result = arr1.filter(num => !arr2.includes(num));
console.log(result);

Challenge 27: Distinct elements in an array(Solution 1)




function getDistinctElements1(arr) {
    return Array.from(new Set(arr));
}
  
let inputArray = [1, 2, 2, 3, 4, 4, 5];
let distinctArray1 = getDistinctElements1(inputArray);
console.log(distinctArray1);

Challenge 27: Distinct elements in an array(Solution 2)




function getDistinctElements2(arr) {
    return arr.filter((value, index, self) => self.indexOf(value) === index);
}
  
let inputArray = [1, 2, 2, 3, 4, 4, 5];
let distinctArray2 = getDistinctElements2(inputArray);
console.log(distinctArray2);

Challenge 28: Sum of first 100 prime numbers




function sumOfPrimes(count) {
    let primes = [];
    let sum = 0;
    for (let i = 2; primes.length < count; i++) {
        if (isPrime(i)) {
            primes.push(i);
            sum += i;
        }
    }
    console.log(sum);
}
sumOfPrimes(100);

Challenge 29: Distance between the first 100 prime numbers




function primeDistance(count) {
    let primes = [];
    for (let i = 2; primes.length < count; i++) {
        if (isPrime(i)) {
            primes.push(i);
        }
    }
    let distance = [];
    for (let i = 1; i < primes.length; i++) {
        distance.push(primes[i] - primes[i - 1]);
    }
    console.log(distance);
}
primeDistance(100);

Challenge 30: Add two positive numbers of indefinite size as strings(Solution 1)




function addStrings1(num1, num2) {
    let result = BigInt(num1) + BigInt(num2);
    return result.toString();
}
  
  
let sum1 = addStrings1("12345678901234567890", "98765432109876543210");
console.log(sum1);

Challenge 30: Add two positive numbers of indefinite size as strings(Solution 2)




function addStrings2(num1, num2) {
    let maxLength = Math.max(num1.length, num2.length);
    num1 = num1.padStart(maxLength, '0');
    num2 = num2.padStart(maxLength, '0');
  
    let carry = 0;
    let result = '';
  
    for (let i = maxLength - 1; i >= 0; i--) {
        let digitSum = parseInt(num1[i]) + parseInt(num2[i]) + carry;
        carry = Math.floor(digitSum / 10);
        result = (digitSum % 10).toString() + result;
    }
  
    if (carry > 0) {
        result = carry.toString() + result;
    }
  
    return result;
}
  
let sum2 = addStrings2("12345678901234567890", "98765432109876543210");
console.log(sum2);

Challenge 31: Number of words in a text(Solution 1)




function countWords1(text) {
    return text.split(/\s+/).filter(word => word !== '').length;
}
  
let inputText = "This is a sample text.";
let wordCount1 = countWords1(inputText);
console.log(wordCount1);

Challenge 31: Number of words in a text(Solution 2)




function countWords2(text) {
    return text.split(/\s+/).filter(word => word !== '').length;
}
  
let inputText = "This is a sample text.";
let wordCount2 = countWords2(inputText);
console.log(wordCount2);

Challenge 32: Capitalize the first letter of each word in a text




function capitalizeFirstLetter(text) {
    return text.replace(/\b\w/g, char => char.toUpperCase());
}
  
let capitalizedText = capitalizeFirstLetter(inputText);
console.log(capitalizedText);

Challenge 33: Sum of numbers in a comma-delimited string




function sumNumbersInString(str) {
    let numbers = str.split(',').map(Number);
    return numbers.reduce((sum, num) => sum + num, 0);
}
  
let sumOfNumbers = sumNumbersInString(commaDelimitedString);
console.log(sumOfNumbers);

Challenge 34: Words inside a text




function getWordsArray(text) {
    return text.match(/\b\w+\b/g) || [];
}
  
let wordsArray = getWordsArray(inputText);
console.log(wordsArray);

Challenge 35: Convert CSV text to a bi-dimensional array




function csvToBiDimensionalArray(csvText) {
    return csvText.split('\n').map(row => row.split(','));
}
  
let biDimensionalArray = csvToBiDimensionalArray(csvText);
console.log(biDimensionalArray);

Challenge 36: Convert a string to an array of characters




let str = "Hello, Geeks!";
let charArray = Array.from(str);
console.log(charArray);

Challenge 37: Convert a string to an array of ASCII codes




function stringToAsciiArray(text) {
    return text.split('').map(char => char.charCodeAt(0));
}
  
let asciiArray = stringToAsciiArray(inputString);
console.log(asciiArray);

Challenge 38: Convert an array of ASCII codes to a string




function asciiArrayToString(asciiArray) {
    return String.fromCharCode(...asciiArray);
}
  
let asciiArray = [104, 101, 108, 108, 111];
let resultString = asciiArrayToString(asciiArray);
console.log(resultString);

Challenge 39: Implement the Caesar cipher




function caesarCipher(text, shift) {
    return text.replace(/[a-zA-Z]/g, char => {
        let baseCharCode = char.toLowerCase() === char ? 'a'.charCodeAt(0) : 'A'.charCodeAt(0);
        let charCode = char.charCodeAt(0);
        let shiftedCharCode = ((charCode - baseCharCode + shift) % 26 + 26) % 26 + baseCharCode;
        return String.fromCharCode(shiftedCharCode);
    });
}
  
let inputText = "Hello, World!";
let encryptedText = caesarCipher(inputText, 3);
console.log(encryptedText);

Challenge 40: Bubble sort algorithm




function bubbleSort(arr) {
    let n = arr.length;
    for (let i = 0; i < n-1; i++) {
        for (let j = 0; j < n-i-1; j++) {
            if (arr[j] > arr[j+1]) {
                // swap arr[j] and arr[j+1]
                let temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }
    return arr;
}
  
let numbers = [64, 34, 25, 12, 22, 11, 90];
console.log(bubbleSort(numbers));

Challenge 41: Distance between two points defined by their coordinates




function calculateDistance(x1, y1, x2, y2) {
    return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}
  
let distance = calculateDistance(1, 2, 4, 6);
console.log(distance);

Challenge 42: Check Circle Intersection




function areCirclesIntersecting(x1, y1, r1, x2, y2, r2) {
    let distance = calculateDistance(x1, y1, x2, y2);
    return distance < (r1 + r2);
}
  
let intersecting = areCirclesIntersecting(0, 0, 5, 8, 0, 5);
console.log(intersecting);

Challenge 43: Extract Column from 2D Array




function extractColumn(matrix, col) {
    return matrix.map(row => row[col]);
}
  
let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
let column = extractColumn(matrix, 1);
console.log(column);

Challenge 44: Convert Binary String to Number




function binaryStringToNumber(binaryString) {
    return parseInt(binaryString, 2);
}
  
let binaryNumber = binaryStringToNumber("1101");
console.log(binaryNumber);

Challenge 45: Sum of Numbers in Jagged Array




function sumJaggedArray(arr) {
    return arr.flat(Infinity).reduce((sum, num) => sum + num, 0);
}
  
let jaggedArray = [1, [2, [3, 4], 5], 6];
console.log(sumJaggedArray(jaggedArray));

Challenge 46: Find Maximum Number in Jagged Array(Solution 1)




function findMaxInJaggedArray(arr) {
    return Math.max(...arr.flat(Infinity));
}
  
let jaggedArray = [1, [2, [3, 4], 5], 6];
console.log(findMaxInJaggedArray(jaggedArray));

Challenge 46: Find Maximum Number in Jagged Array(Solution 2)




function deepCopyJaggedArray(arr) {
    return JSON.parse(JSON.stringify(arr));
}
  
let jaggedArray = [1, [2, [3, 4], 5], 6];
let copiedArray = deepCopyJaggedArray(jaggedArray);
console.log(copiedArray);

Challenge 47: Deep Copy Jagged Array




function deepCopyJaggedArray(arr) {
    return JSON.parse(JSON.stringify(arr));
}
  
let jaggedArray = [1, [2, [3, 4], 5], 6];
let copiedArray = deepCopyJaggedArray(jaggedArray);
console.log(copiedArray);

Challenge 48: Longest Word(s) in a String




function longestWords(str) {
    let words = str.split(/\s+/);
    let maxLength = Math.max(...words.map(word => word.length));
    return words.filter(word => word.length === maxLength);
}
  
let sentence = "The quick brown fox jumps over the lazy dog";
console.log(longestWords(sentence));

Challenge 49: Shuffle Array of Strings




function shuffleArray(arr) {
    return arr.sort(() => Math.random() - 0.5);
}
  
let stringsArray = ["apple", "banana", "orange", "grape"];
console.log(shuffleArray(stringsArray));

Challenge 50: Generate Unique Random Numbers




function generateUniqueRandomNumbers(n) {
    let numbers = Array.from({length: n}, (_, index) => index + 1);
    return shuffleArray(numbers);
}
  
let uniqueRandomNumbers = generateUniqueRandomNumbers(5);
console.log(uniqueRandomNumbers);

Challenge 51: Frequency of Characters in a String




function characterFrequency(str) {
    let frequency = {};
    for (let char of str) {
        frequency[char] = (frequency[char] || 0) + 1;
    }
    return Object.entries(frequency).map(([character, occurrences]) => ({ character, occurrences }));
}
  
let inputString = "programming";
console.log(characterFrequency(inputString));

Challenge 52: Calculate Fibonacci(500)




function calculateFibonacci(n) {
    let a = BigInt(0);
    let b = BigInt(1);
  
    for (let i = 2; i <= n; i++) {
        [a, b] = [b, a + b];
    }
  
    return b.toString();
}
  
let result = calculateFibonacci(500);
console.log(result);

Challenge 53: Calculate 70! with High Precision




function calculateFactorial(n) {
    let result = BigInt(1);
  
    for (let i = 2; i <= n; i++) {
        result *= BigInt(i);
    }
  
    return result.toString();
}
  
let factorial70 = calculateFactorial(70);
console.log(factorial70);

In conclusion, these JavaScript coding challenges are a practical approach for beginners to strengthen their programming skills. These challenges are diverse, encompassing the elements of basic ideas and complicated algorithms that prepare hands-on practice in JavaScript. The simple yet effective solutions act as great references for beginners, making them more confident in solving problems. The process of engaging with these challenges becomes an efficient solution for the newcomers so that their journey to becoming professional JavaScript developers is realized.




Article Tags :