10 Helpful JavaScript Code Snippets v2
10 Helpful JavaScript Code Snippets v2
Write a function that checks whether two given strings are anagrams in
JavaScript. 2
Write a function that converts a string to title case (i.e., the first letter of
each word capitalized) in JavaScript. 3
Write a function that calculates the factorial of a given number without using
recursion in JavaScript. 4
Write a function that calculates the sum of all even numbers in an array in 5
function toTitleCase(str) {
return str.replace(/\b\w/g, (char) =>
char.toUpperCase());
}
Explanation: The function uses a regular expression (/\b\w/g) to
match the first character of each word in the input string. Then, it
uses the replace() method to replace each of these characters
with its uppercase version using an arrow function.
function secondLargest(arr) {
const sorted = arr.sort((a, b) => b - a);
return sorted[1];
}
Explanation: The function first sorts the input array in descending
order using the sort() method and a comparator function. Then, it
returns the second element of the sorted array (which is the
second largest number).
function isPangram(str) {
const alphabet = "abcdefghijklmnopqrstuvwxyz";
const lowercase = str.toLowerCase();
return alphabet.split("").every((char) =>
lowercase.includes(char));
}
Explanation: The function first defines a string of all letters of the
alphabet. Then, it converts the input string to lowercase. Finally,
it checks if every letter in the alphabet is included in the
lowercase string using the every() method.
function sumEven(arr) {
return arr.filter((num) => num % 2 ===
0).reduce((acc, cur) => acc + cur, 0);
}
Explanation: The function first uses the filter() method on the
input array to filter out all odd numbers (i.e., numbers that have
a remainder of 1 when divided by 2). Then, it uses the reduce()
method to accumulate the sum of all even numbers in the
resulting array.
function isPerfectSquare(num) {
const root = Math.sqrt(num);
return root === Math.floor(root);
}
Explanation: The function uses the Math.sqrt() method to
calculate the square root of the input number. Then, it checks if
the square root is equal to its floor (i.e., if it is an integer).
function fahrenheitToCelsius(fahrenheit) {
return (fahrenheit - 32) * 5 / 9;
}
Explanation: The function uses the formula (F - 32) * 5/9 to
convert a temperature in Fahrenheit to Celsius.