Skip to main content

13+ Basic Programs Using Javascript Language

basic-programs-using-javascript

Prepare yourself for an exhilarating adventure through 14 foundational JavaScript programs! Each program serves as a building block towards mastering coding skills. Experience the excitement as you overcome obstacles and reveal the mysteries of this dynamic language. Allow your passion to propel you forward as you navigate the captivating realm of JavaScript. Remember, every line of code you craft demonstrates your ingenuity and resolve.

As you progress through each program, relish in the fulfillment of witnessing your concepts materialize. It's akin to embarking on an emotional rollercoaster as you traverse loops, conditionals, and functions. Unveil the myriad possibilities of JavaScript and allow your passion to guide you through the thrill of learning and the triumph of surmounting coding challenges.


1. Reverse a String:

Problem: Write a function that reverses a given string.

Example

function reverseString(str) {
   return str.split('').reverse().join('');
}
console.log(reverseString('hello'));

Output:

'olleh'


2. Find the Factorial of a Number:

Problem: Write a function to calculate the factorial of a given number.

Example

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

Output:

120


3. Check for Palindrome:

Problem: Write a function that checks if a given string is a palindrome (reads the same forwards and backwards).

Example

function isPalindrome(str) {
    const reversed = str.split('').reverse().join('');
    return str === reversed;
}
console.log(isPalindrome('racecar')); 

Output:

true


4. Find the Longest Word:

Problem: Write a function that finds the longest word in a sentence.

Example

function findLongestWord(sentence) {
    const words = sentence.split(' ');
    let longestWord = '';
    for (const word of words) {
        if (word.length > longestWord.length) {
            longestWord = word;
        }
    }
    return longestWord;
}
console.log(findLongestWord('The quick brown fox')); 

Output:

quick


5. Calculate Fibonacci Series:

Problem: Write a function to generate the Fibonacci series up to a given number of terms.

Example

function fibonacci(n) {
    const series = [0, 1];
    for (let i = 2; i < n; i++) {
        const next = series[i - 1] + series[i - 2];
        series.push(next);
    }
    return series;
}
console.log(fibonacci(5));

Output:

[0, 1, 1, 2, 3]


6. Find the Missing Number:

Problem: Given an array containing n distinct numbers taken from 0 to n, find the missing number.

Example

function findMissingNumber(nums) {
    const n = nums.length;
    const expectedSum = (n * (n + 1)) / 2;
    const actualSum = nums.reduce((sum, num) => sum + num, 0);
    return expectedSum - actualSum;
}
console.log(findMissingNumber([0, 1, 3]));

Output:

2


7. Count the Vowels in a String:

Problem: Write a function that counts the number of vowels in a given string.

Example

function countVowels(str) {
    const vowels = 'aeiouAEIOU';
    let count = 0;
    for (const char of str) {
        if (vowels.includes(char)) {
            count++;
        }
    }
    return count;
}
console.log(countVowels('Hello, World!'));

Output:

3


8. Check for Anagrams:

Problem: Write a function that checks if two strings are anagrams of each other.

Example

function areAnagrams(str1, str2) {
    const sorted1 = str1.split('').sort().join('');
    const sorted2 = str2.split('').sort().join('');
    return sorted1 === sorted2;
}
console.log(areAnagrams('listen', 'silent'));

Output:

true


9. Find the Maximum Number:

Problem: Write a function that finds the maximum number in an array of numbers.

Example

function findMax(arr) {
    return Math.max(...arr);
}
console.log(findMax([3, 5, 1, 9, 2]));

Output:

9


10. Remove Duplicates from an Array:

Problem: Write a function that removes duplicate elements from an array.

Example

function removeDuplicates(arr) {
    return Array.from(new Set(arr));
}
console.log(removeDuplicates([1, 2, 2, 3, 4, 4, 5]));

Output:

[1, 2, 3, 4, 5]


11. Calculate the Mean (Average):

Problem: Write a function that calculates the mean (average) of an array of numbers.

Example

function calculateMean(arr) {
    const sum = arr.reduce((acc, num) = & gt; acc + num, 0);
    return sum / arr.length;
}
console.log(calculateMean([1, 2, 3, 4, 5]));

Output:

3


12. Title Case a Sentence:

Problem: Write a function that converts the first letter of each word in a sentence to uppercase.

Example

function titleCase(sentence) {
    const words = sentence.split(' ');
    const titleCaseWords = words.map(word = & gt; word.charAt(0).toUpperCase() + word.slice(1).toLowerCase());
    return titleCaseWords.join(' ');
}
console.log(titleCase('this is a title'));

Output:

'This Is A Title'


13. Check for Prime Number:

Problem: Write a function that checks if a given number is prime.

Example

function isPrime(num) {
    if (num & lt; = 1) return false;
    if (num & lt; = 3) return true;
    if (num % 2 === 0 || num % 3 === 0) return false;
    for (let i = 5; i * i & lt; = num; i += 6) {
        if (num % i === 0 || num % (i + 2) === 0) return false;
    }
    return true;
}
console.log(isPrime(7));

Output:

true


14. Calculate the Factorial of a Large Number:

Problem: Write a function to calculate the factorial of a large number without causing an overflow.

Example

function factorial(num) {
    if (num === 0 || num === 1) return 1;
    let result = BigInt(1);
    for (let i = 2; i & lt; = num; i++) {
        result *= BigInt(i);
    }
    return result.toString();
}
console.log(factorial(100));

Output:

A very large number!

These additional programming problems and solutions should help you further develop your JavaScript coding skills. Feel free to use them for practice and learning.

Comments