14+ Basic Programs Using JavaScript Language
Embark on an exhilarating journey through foundational JavaScript programs! Each program is a stepping stone to mastering coding skills. Feel the thrill as you conquer challenges like removing a class from multiple elements or trimming whitespace from a string. Let your passion drive you through this dynamic language, where every line of code showcases your creativity and determination.
As you tackle each program, enjoy the satisfaction of seeing your ideas come to life—like changing background colors on button click or embedding variables into strings. It’s like riding an emotional rollercoaster through loops, conditionals, and functions. Discover the endless possibilities of JavaScript and let your enthusiasm guide you through the joy of learning and the triumph of overcoming coding obstacles.
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'
Explanation
The reverseString
function takes a string parameter str
. It uses the split('')
method to convert the string into an array of characters, reverse()
to reverse the array, and join('')
to combine the characters back into a string. For example, passing 'hello'
results in '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
Explanation
The factorial
function uses recursion to compute the factorial of num
. If num
is 0 or 1, it returns 1 (base case). Otherwise, it multiplies num
by the factorial of num - 1
. For num = 5
, it calculates 5 * 4 * 3 * 2 * 1 = 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
Explanation
The isPalindrome
function checks if str
is a palindrome by comparing it to its reversed version. It creates reversed
using split('')
, reverse()
, and join('')
. If str
equals reversed
, it returns true
. For 'racecar'
, both are identical, so it returns 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'
Explanation
The findLongestWord
function splits sentence
into an array of words using split(' ')
. It initializes longestWord
as an empty string and iterates through words
. If a word
’s length exceeds longestWord
’s length, it updates longestWord
. For 'The quick brown fox'
, 'quick'
(5 letters) is the longest.
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]
Explanation
The fibonacci
function generates a Fibonacci series for n
terms. It initializes series
with [0, 1]
. For each index i
from 2 to n
, it computes next
as the sum of the previous two numbers (series[i-1] + series[i-2]
) and pushes it to series
. For n = 5
, it returns [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
Explanation
The findMissingNumber
function finds the missing number in nums
. It calculates the expectedSum
of numbers from 0 to n
using the formula (n * (n + 1)) / 2
. The actualSum
is computed using reduce
. The difference (expectedSum - actualSum
) is the missing number. For [0, 1, 3]
, the missing number is 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
Explanation
The countVowels
function counts vowels in str
. It defines vowels
as a string of vowels and initializes count
to 0. It iterates through each char
in str
, incrementing count
if char
is in vowels
. For 'Hello, World!'
, it finds 3 vowels (e
, o
, o
).
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
Explanation
The areAnagrams
function checks if str1
and str2
are anagrams. It converts both strings to arrays, sorts them with sort()
, and joins them back with join('')
to create sorted1
and sorted2
. If they’re equal, the strings are anagrams. For 'listen'
and 'silent'
, both sort to 'eilnst'
, so it returns 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
Explanation
The findMax
function finds the largest number in arr
using Math.max
with the spread operator (...
) to pass array elements as individual arguments. For [3, 5, 1, 9, 2]
, it returns 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]
Explanation
The removeDuplicates
function removes duplicates from arr
by converting it to a Set
, which automatically removes duplicates, and then back to an array using Array.from
. For [1, 2, 2, 3, 4, 4, 5]
, it returns [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) => acc + num, 0);
return sum / arr.length;
}
console.log(calculateMean([1, 2, 3, 4, 5]));
Output:
3
Explanation
The calculateMean
function computes the average of arr
. It uses reduce
to calculate sum
by adding all numbers, starting with an accumulator acc
of 0. The mean is sum
divided by arr.length
. For [1, 2, 3, 4, 5]
, the sum is 15, and the mean is 15 / 5 = 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 => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase());
return titleCaseWords.join(' ');
}
console.log(titleCase('this is a title'));
Output:
'This Is A Title'
Explanation
The titleCase
function capitalizes the first letter of each word in sentence
. It splits sentence
into words
, maps each word
by capitalizing its first letter with charAt(0).toUpperCase()
and lowercasing the rest with slice(1).toLowerCase()
, then joins with join(' ')
. For 'this is a title'
, it returns '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 <= 1) return false;
if (num <= 3) return true;
if (num % 2 === 0 || num % 3 === 0) return false;
for (let i = 5; i * i <= num; i += 6) {
if (num % i === 0 || num % (i + 2) === 0) return false;
}
return true;
}
console.log(isPrime(7));
Output:
true
Explanation
The isPrime
function checks if num
is prime. It returns false
for num <= 1
, true
for num <= 3
, and false
if num
is divisible by 2 or 3. It then checks divisibility by numbers of the form 6k ± 1
up to the square root of num
. For num = 7
, it’s prime, so it returns 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 <= num; i++) {
result *= BigInt(i);
}
return result.toString();
}
console.log(factorial(100));
Output:
'93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000'
Explanation
The factorial
function handles large factorials using BigInt
to avoid overflow. For num = 0
or 1
, it returns '1'
. It initializes result
as BigInt(1)
and multiplies it by BigInt(i)
from 2 to num
. The result is converted to a string with toString()
. For num = 100
, it returns a large factorial number.
15. Check if a Number is Even or Odd
Problem: Write a function that checks if a given number is even or odd.
Example
function isEven(num) {
return num % 2 === 0;
}
console.log(isEven(4)); // true
console.log(isEven(7)); // false
Output:
true
false
Explanation
The isEven
function checks if num
is even by testing if num % 2 === 0
. If true, num
is even; otherwise, it’s odd. For num = 4
, it returns true
; for num = 7
, it returns false
.
16. Sum of Array Elements
Problem: Write a function that calculates the sum of all elements in an array.
Example
function arraySum(arr) {
return arr.reduce((sum, num) => sum + num, 0);
}
console.log(arraySum([1, 2, 3, 4]));
Output:
10
Explanation
The arraySum
function computes the sum of arr
using reduce
, which adds each num
to an accumulator sum
, starting at 0. For [1, 2, 3, 4]
, it calculates 1 + 2 + 3 + 4 = 10
.
17. Reverse an Array
Problem: Write a function that reverses an array without using the built-in reverse()
method.
Example
function reverseArray(arr) {
const reversed = [];
for (let i = arr.length - 1; i >= 0; i--) {
reversed.push(arr[i]);
}
return reversed;
}
console.log(reverseArray([1, 2, 3, 4]));
Output:
[4, 3, 2, 1]
Explanation
The reverseArray
function reverses arr
by creating a new array reversed
. It iterates from the last index of arr
to the first, pushing each element to reversed
. For [1, 2, 3, 4]
, it returns [4, 3, 2, 1]
.
Related Posts:
- How To Remove A Class From Multiple Elements Using JavaScript
- How to Change the Background Color on Button Click in JavaScript
- How To Trim Whitespace From The Start Or End Of String Using Javascript
- Create An Element With Class, ID Or Style Attribute In Javascript
- How to Remove a Character from a String in JavaScript
- How to Remove Empty Strings from an Array In JavaScript
- How to Show and Hide an Element with JavaScript
- How to Get All the Attributes Of A DOM Element with JavaScript
- How To Get Mouse Position Relative to An Element In JavaScript
- How To Add A Variable Inside A String In JavaScript
- How to Append Text To A DIV Using JavaScript
- How to Call a JavaScript Function on Page Load
- How To Sort Alphabetically Html Unordered Elements Using JavaScript
These programs and resources are perfect for honing your JavaScript skills. Practice them, experiment, and keep coding!
Comments
Post a Comment