1. Write a function that takes two parameters and returns their sum.
function addNumbers(a, b) {
return a + b;
}const result = addNumbers(5, 10);
console.log(result);
2. Create a function that calculates the average of an array of numbers.
function calculateAverage(numbers) {
if (numbers.length === 0) {
return 0; // Return 0 if the array is empty
}
const sum = numbers.reduce((accumulator, currentValue) => accumulator +
currentValue, 0);
return sum / numbers.length;
}const numbers = [10, 20, 30, 40, 50];
const average = calculateAverage(numbers);
console.log(average);
3. Write a function that checks if a given number is even or odd.
function isEven(num) {
if (num % 2 === 0) {
return "Even";
} else {
return "Odd";
}
}console.log(isEven(4));
console.log(isEven(7));
console.log(isEven(10));
console.log(isEven(11));
4. Create a function that reverses a string.
function reverseString(str) {
let reversedStr = '';
for (let i = str.length - 1; i >= 0; i--) {
reversedStr += str[i];
}
return reversedStr;
}console.log(reverseString("hello"));
console.log(reverseString("JavaScript"));
console.log(reverseString("12345"));
5. Write a function that finds the maximum value in an array of numbers.
function findMaxValue(numbers) {
if (numbers.length === 0) {
return null;
}
let maxValue = numbers[0];
for (let i = 1; i < numbers.length; i++) {
if (numbers[i] > maxValue) {
maxValue = numbers[i];
}
}
return maxValue;
}console.log(findMaxValue([10, 5, 8, 12, 7]));
console.log(findMaxValue([-3, -1, -5, -2]));
console.log(findMaxValue([]));
6. Create a function that converts Celsius to Fahrenheit.
function celsiusToFahrenheit(celsius) {
return (celsius * 9/5) + 32;
}console.log(celsiusToFahrenheit(0));
console.log(celsiusToFahrenheit(10));
console.log(celsiusToFahrenheit(20));
console.log(celsiusToFahrenheit(30));
7. Write a function that generates a random number between a given minimum and maximum.
function getRandomNumber(min, max) {
if (min > max) {
[min, max] = [max, min];
}
return Math.floor(Math.random() * (max - min + 1)) + min;
}console.log(getRandomNumber(1, 10));
console.log(getRandomNumber(0, 100));
console.log(getRandomNumber(-5, 5));
console.log(getRandomNumber(10, 5));
8. Create a function that checks if a string is a palindrome.
function isPalindrome(str) {
str = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
let reversedStr = str.split('').reverse().join('');
return str === reversedStr;
}console.log(isPalindrome("A man, a plan, a canal: Panama"));
console.log(isPalindrome("race car"));
console.log(isPalindrome("Hello, world!"));
console.log(isPalindrome("Was it a car or a cat I saw?"));
9. Write a function that capitalizes the first letter of each word in a sentence.
function capitalizeWords(sentence) {
const words = sentence.split(' ');
const capitalizedWords = words.map(word => {
return word.charAt(0).toUpperCase() + word.slice(1);
});
return capitalizedWords.join(' ');
}console.log(capitalizeWords("the quick brown fox jumps over the lazy dog"));
console.log(capitalizeWords("hello, world!"));
console.log(capitalizeWords("JAVASCRIPT is awesome"));
10. Create a function that returns the factorial of a given number.
function factorial(n) {
if (n === 0) {
return 1;
}
return n * factorial(n - 1);
}console.log(factorial(0));
console.log(factorial(5));
11. Write a function that counts the number of occurrences of a specific element in an array.
function countOccurrences(arr, element) {
let count = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] === element) {
count++;
}
}
return count;
}const myArray = [1, 2, 3, 2, 4, 2, 5, 2];
console.log(countOccurrences(myArray, 2));
console.log(countOccurrences(myArray, 3));
console.log(countOccurrences(myArray, 6));
12. Create a function that checks if a given year is a leap year.
function isLeapYear(year) {
if (year % 4 === 0) {
if (year % 100 === 0) {
if (year % 400 === 0) {
return true;
} else {
return false;
}
} else {
return true;
}
} else {
return false;
}
}console.log(isLeapYear(2000));
console.log(isLeapYear(2024));
console.log(isLeapYear(2100));
console.log(isLeapYear(2400));
console.log(isLeapYear(2023));
13. Write a function that merges two arrays and returns the sorted result.
function mergeSortedArrays(arr1, arr2) {
return (arr1.concat(arr2)).sort((a, b) => a - b);
}console.log(mergeSortedArrays([1, 3, 5], [2, 4, 6]));
console.log(mergeSortedArrays([1, 2, 3], [4, 5, 6]));
14. Create a function that converts a number to its Roman numeral representation.
function convertToRoman(num) {
const romanSymbols = [
['M', 1000],
['CM', 900],
['D', 500],
['CD', 400],
['C', 100],
['XC', 90],
['L', 50],
['XL', 40],
['X', 10],
['IX', 9],
['V', 5],
['IV', 4],
['I', 1],
];
let result = '';
for (const [symbol, value] of romanSymbols) {
while (num >= value) {
result += symbol;
num -= value;
}
}
return result;
}console.log(convertToRoman(3));
console.log(convertToRoman(4));
console.log(convertToRoman(9));
console.log(convertToRoman(58));
console.log(convertToRoman(1994));
15. Write a function that finds the second smallest element in an array of numbers.
function findSecondSmallest(arr) {
let smallest = Infinity;
let secondSmallest = Infinity;
for (const num of arr) {
if (num < smallest) {
secondSmallest = smallest;
smallest = num;
} else if (num < secondSmallest && num !== smallest) {
secondSmallest = num;
}
}
return secondSmallest;
}console.log(findSecondSmallest([5, 2, 3, 1, 4]));
console.log(findSecondSmallest([1, 1, 1, 1, 1]));
16. Create a function that calculates the area of a circle given its radius.
function calculateCircleArea(radius) {
const area = Math.PI * Math.pow(radius, 2);
return area;
}console.log(calculateCircleArea(5));
console.log(calculateCircleArea(-5));
17. Write a function that truncates a string if it exceeds a specified length and appends "..." to the end.
function truncateString(str, maxLength) {
if (str.length > maxLength) {
return str.slice(0, maxLength) + '...';
} else {
return str;
}
}console.log(truncateString('Hello, world!', 10));
console.log(truncateString('JavaScript is awesome!', 15));
console.log(truncateString('Short string', 20));
18. Create a function that checks if a given string contains only digits.
function containsOnlyDigits(str) {
const regex = /^\d+$/;
return regex.test(str);
}console.log(containsOnlyDigits('12345'));
console.log(containsOnlyDigits('0'));
console.log(containsOnlyDigits('123.45'));
19. Write a function that removes all falsy values (false, null, 0, "", undefined, and NaN) from an array.
function removeNullish(arr) {
return arr.filter(item => item !== false && item !== null && item !== 0
&& item !== '' && item !== undefined && !isNaN(item));
}console.log(removeNullish([1, 0, 2, '', 3, null, undefined, NaN]));
console.log(removeNullish([false, true, 42]));
20. Create a function that generates a new array with unique values from a given array.
function getUniqueValues(arr) {
const uniqueSet = new Set(arr);
return Array.from(uniqueSet);
}console.log(getUniqueValues([1, 2, 3, 2, 4, 1, 5]));
console.log(getUniqueValues(['apple', 'banana', 'cherry', 'banana']));
console.log(getUniqueValues([false, true, false, 0, 1, 0]));