JavaScript Code Snippets 1000+

JavaScript Code Snippets 1000+

1. Reverse a String

function reverseString(s) {
  return s.split('').reverse().join('');
}

// Example usage
console.log(reverseString("Hello, World!"));  // Output: !dlroW ,olleH

Explanation: This function reverses a string s by first converting it to an array of characters with split(''), then reversing the array with reverse(), and finally joining the characters back into a string with join('').


2. Check if a Number is Prime

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

// Example usage
console.log(isPrime(11));  // Output: True

Explanation: Similar to Python, this function iterates from 2 to the square root of n, checking if n is divisible by any of these numbers. If it finds a divisor, it returns false.


3. Count Vowels in a String

function countVowels(s) {
  const vowels = 'aeiouAEIOU';
  return Array.from(s).filter(char => vowels.includes(char)).length;
}

// Example usage
console.log(countVowels("Hello, World!"));  // Output: 3

Explanation: This function counts vowels by filtering characters in the string that are included in the vowels string and returns the length of the resulting array.


4. Flatten a Nested Array

function flattenArray(nestedArray) {
  return nestedArray.flat(Infinity);
}

// Example usage
console.log(flattenArray([[1, 2], [3, 4], [5]]));  // Output: [1, 2, 3, 4, 5]

Explanation: Uses JavaScript’s Array.flat() method with the depth parameter set to Infinity to flatten nested arrays of any depth.


5. Generate Fibonacci Sequence

function fibonacci(n) {
  let a = 0, b = 1, sequence = [];
  for (let i = 0; i < n; i++) {
    sequence.push(a);
    [a, b] = [b, a + b];
  }
  return sequence;
}

// Example usage
console.log(fibonacci(10));  // Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Explanation: This function generates a Fibonacci sequence using destructuring to update values of a and b.


6. Find the Maximum Value in an Array

function findMax(arr) {
  return Math.max(...arr);
}

// Example usage
console.log(findMax([1, 2, 3, 4, 5]));  // Output: 5

Explanation: Utilizes JavaScript’s spread operator ... to pass all elements of the array as arguments to Math.max().


7. Remove Duplicates from an Array

function removeDuplicates(arr) {
  return [...new Set(arr)];
}

// Example usage
console.log(removeDuplicates([1, 2, 2, 3, 4, 4]));  // Output: [1, 2, 3, 4]

Explanation: Converts the array to a Set to remove duplicates and then converts it back to an array.


8. Sort an Object by Value

function sortObjectByValue(obj) {
  return Object.fromEntries(
    Object.entries(obj).sort((a, b) => a[1] - b[1])
  );
}

// Example usage
console.log(sortObjectByValue({a: 3, b: 1, c: 2}));  // Output: {b: 1, c: 2, a: 3}

Explanation: Sorts entries of an object by their values and then converts them back to an object.


9. Check for Palindrome

function isPalindrome(s) {
  return s === s.split('').reverse().join('');
}

// Example usage
console.log(isPalindrome("racecar"));  // Output: True

Explanation: This function checks if a string s is a palindrome by reversing the string and comparing it to the original.


10. Merge Two Objects

function mergeObjects(obj1, obj2) {
  return {...obj1, ...obj2};
}

// Example usage
console.log(mergeObjects({a: 1}, {b: 2}));  // Output: {a: 1, b: 2}

Explanation: This function merges two objects using the spread operator ... to combine their properties.


11. Calculate Factorial

function factorial(n) {
  if (n === 0) return 1;
  return n * factorial(n - 1);
}

// Example usage
console.log(factorial(5));  // Output: 120

Explanation: This recursive function calculates the factorial of a number n.


12. Find the Intersection of Two Arrays

function arrayIntersection(arr1, arr2) {
  return arr1.filter(x => arr2.includes(x));
}

// Example usage
console.log(arrayIntersection([1, 2, 3], [2, 3, 4]));  // Output: [2, 3]

Explanation: This function finds the intersection of two arrays by using the filter() method to keep only elements present in both arrays.


13. Convert Celsius to Fahrenheit

function celsiusToFahrenheit(celsius) {
  return (celsius * 9/5) + 32;
}

// Example usage
console.log(celsiusToFahrenheit(0));  // Output: 32.0

Explanation: This function converts a temperature from Celsius to Fahrenheit using the formula ( F = C \times \frac{9}{5} + 32 ).


14. Count Occurrences of an Element in an Array

function countOccurrences(arr, element) {
  return arr.filter(x => x === element).length;
}

// Example usage
console.log(countOccurrences([1, 2, 2, 3], 2));  // Output: 2

Explanation: This function counts how many times a specific element appears in an array using the filter() method.


15. Generate a Random Password

function generatePassword(length = 8) {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+';
  let password = '';
  for (let i = 0; i < length; i++) {
    password += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return password;
}

// Example usage
console.log(generatePassword(12));  // Outputs a random 12-character password

Explanation: This function generates a random password of a specified length using characters from a defined set.


16. Find the Length of a String

function stringLength(s) {
  return s.length;
}

// Example usage
console.log(stringLength("Hello, World!"));  // Output: 13

Explanation: This function returns the length of a string s.


17. Check if a String Contains Only Digits

function isAllDigits(s) {
  return /^\d+$/.test(s);
}

// Example usage
console.log(isAllDigits("12345"));  // Output: True

Explanation: This function checks if a string s contains only digits using a regular expression.


18. Find the Index of an Element in an Array

function findIndex(arr, element) {
  return arr.indexOf(element);
}

// Example usage
console.log(findIndex([1, 2, 3, 4], 3));  // Output: 2

Explanation: This function returns the index of the first occurrence of element in an array using the indexOf() method.


19. Remove Whitespace from a String

function removeWhitespace(s) {
  return s.replace(/\s/g, "");
}

// Example usage
console.log(removeWhitespace("Hello, World!"));  // Output: Hello,World!

Explanation: This function removes all whitespace from a string s using the replace() method with a regular expression.


20. Create a Simple Countdown Timer

function countdownTimer(seconds) {
  let interval = setInterval(() => {
    console.log(seconds);
    seconds--;
    if (seconds < 0) {
      clearInterval(interval);
      console.log("Time's up!");
    }
  }, 1000);
}

// Example usage
// countdownTimer(5);  // Uncomment to run

Explanation: This function creates a countdown timer that counts down from a specified number of seconds, logging each second and ending with a message when time is up.


21. Simple Calculator

const calculator = {
  '+': (a, b) => a + b,
  '-': (a, b) => a - b,
  '/': (a, b) => a / b,
  '*': (a, b) => a * b,
  '**': (a, b) => Math.pow(a, b)
};

// Example usage
console.log(calculator['-'](10, 1));  // Output: 9

Explanation: This snippet sets up a simple calculator using an object where keys are operators and values are functions performing the corresponding arithmetic operations.


22. Print the String N Times

const n = 5;
const s = "hello";
console.log(s.repeat(n));

Explanation: This code uses the repeat() method to print the string s n times consecutively.


23. Shuffle a List

function shuffleArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}

const foo = [1, 2, 3, 4];
console.log(shuffleArray(foo));  // Output: Randomly shuffled list, e.g., [1, 4, 3, 2]

Explanation: This function randomly shuffles the elements of an array using the Fisher-Yates (Durstenfeld) shuffle algorithm.


24. Set Difference

const x = new Set(["apple", "banana", "cherry"]);
const y = new Set(["google", "microsoft", "apple"]);

const difference = new Set([...x].filter(element => !y.has(element)));
console.log(difference);  // Output: Set {'banana', 'cherry'}

Explanation: This snippet finds the difference between two sets by filtering elements of the first set that are not in the second set.


25. Capitalize First Letters of Words

const s = "hello world";
console.log(s.split(' ').map(word => word[0].toUpperCase() + word.substring(1)).join(' '));  // Output: Hello World

Explanation: This code splits the string into words, capitalizes the first letter of each word, and joins them back together.


26. Swap Values

function swap(a, b) {
  return [b, a];
}

const [a, b] = swap(1, 2);
console.log(a, b);  // Output: 2 1

Explanation: This function swaps two values and returns them in a new order.


27. Get Default Value for Missing Keys

const d = {'a': 1, 'b': 2};
console.log(d['c'] || 3);  // Output: 3

Explanation: This code fetches the value for key 'c' from the dictionary d, or returns 3 if the key is not found.


28. Find the Minimum Value in a List

function findMin(arr) {
  return Math.min(...arr);
}

// Example usage
console.log(findMin([5, 3, 8, 1, 4]));  // Output: 1

Explanation: This function returns the minimum value from an array using JavaScript’s Math.min() function along with the spread operator to pass array elements as arguments.


29. Generate a List of Squares

function generateSquares(n) {
  return Array.from({length: n}, (_, index) => index ** 2);
}

// Example usage
console.log(generateSquares(5));  // Output: [0, 1, 4, 9, 16]

Explanation: This function generates an array of squares from 0 to n-1 using Array.from() with a mapping function.


30. Check if a String is an Anagram

function isAnagram(s1, s2) {
  const normalize = str => str.toLowerCase().split('').sort().join('');
  return normalize(s1) === normalize(s2);
}

// Example usage
console.log(isAnagram("listen", "silent"));  // Output: True

Explanation: This function checks if two strings are anagrams by normalizing both strings (sorting characters) and comparing them.


31. Convert a List to a Set

function listToSet(list) {
  return new Set(list);
}

// Example usage
console.log(listToSet([1, 2, 2, 3, 4]));  // Output: Set {1, 2, 3, 4}

Explanation: This function converts a list to a set, automatically removing any duplicate values.


32. Get the Current Date and Time

function currentDateTime() {
  return new Date();
}

// Example usage
console.log(currentDateTime());  // Output: Current date and time

Explanation: This function returns the current date and time using JavaScript’s Date object.


33. Find the Length of a List

function listLength(list) {
  return list.length;
}

// Example usage
console.log(listLength([1, 2, 3, 4, 5]));  // Output: 5

Explanation: This function returns the number of elements in a list using the .length property.


34. Remove an Element from a List

function removeElement(list, element) {
  const index = list.indexOf(element);
  if (index > -1) {
    list.splice(index, 1);
  }
  return list;
}

// Example usage
console.log(removeElement([1, 2, 3, 4], 3));  // Output: [1, 2, 4]

Explanation: This function removes the first occurrence of element from the list using indexOf() and splice().


35. Check if a Number is Even

function isEven(n) {
  return n % 2 === 0;
}

// Example usage
console.log(isEven(4));  // Output: True

Explanation: This function checks if a number n is even by evaluating the remainder when divided by 2.


36. Convert a List of Strings to Uppercase

function toUppercase(list) {
  return list.map(s => s.toUpperCase());
}

// Example usage
console.log(toUppercase(["hello", "world"]));  // Output: ['HELLO', 'WORLD']

Explanation: This function converts each string in the list to uppercase using the map() method and toUpperCase().


37. Check if a String Contains a Substring

function containsSubstring(s, substring) {
  return s.includes(substring);
}

// Example usage
console.log(containsSubstring("Hello, World!", "World"));  // Output: True

Explanation: This function checks if a string s contains a specified substring using the includes() method.


38. Calculate the Sum of a List

function sumOfList(list) {
  return list.reduce((acc, val) => acc + val, 0);
}

// Example usage
console.log(sumOfList([1, 2, 3, 4]));  // Output: 10

Explanation: This function calculates the sum of all elements in a list using the reduce() method.


39. Create a Dictionary from Two Lists

function listsToDict(keys, values) {
  return Object.fromEntries(keys.map((key, i) => [key, values[i]]));
}

// Example usage
console.log(listsToDict(['a', 'b', 'c'], [1, 2, 3]));  // Output: {'a': 1, 'b': 2, 'c': 3}

Explanation: This function creates a dictionary by mapping keys to corresponding values using map() and Object.fromEntries().


40. Check if a Year is a Leap Year

function isLeapYear(year) {
  return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}

// Example usage
console.log(isLeapYear(2024));  // Output: True

Explanation: This function checks if a given year is a leap year based on the rules of the Gregorian calendar.


41. Find the GCD of Two Numbers

function gcd(a, b) {
  while (b !== 0) {
    let temp = b;
    b = a % b;
    a = temp;
  }
  return a;
}

// Example usage
console.log(gcd(12, 15));  // Output: 3

Explanation: This function calculates the greatest common divisor (GCD) of two numbers using the Euclidean algorithm. It repeatedly swaps a and b with b and a % b until b becomes zero, at which point a is the GCD.


42. Create a List of Even Numbers

function evenNumbers(n) {
  return Array.from({ length: n }, (_, index) => index).filter(x => x % 2 === 0);
}

// Example usage
console.log(evenNumbers(10));  // Output: [0, 2, 4, 6, 8]

Explanation: This function generates a list of even numbers from 0 to n-1 by first creating an array of all integers up to n-1 and then filtering for even numbers.


43. Replace a Substring in a String

function replaceSubstring(s, old, newStr) {
  return s.replace(new RegExp(old, 'g'), newStr);
}

// Example usage
console.log(replaceSubstring("Hello, World!", "World", "Python"));  // Output: Hello, Python!

Explanation: This function replaces all occurrences of a substring old with newStr in a string s using the replace() method and a regular expression.


44. Capitalize the First Letter of a String

function capitalizeFirstLetter(s) {
  return s.charAt(0).toUpperCase() + s.slice(1);
}

// Example usage
console.log(capitalizeFirstLetter("hello"));  // Output: Hello

Explanation: This function capitalizes the first letter of the string s by taking the first character, converting it to uppercase, and then appending the rest of the string.


45. Merge Two Lists

function mergeLists(list1, list2) {
  return [...list1, ...list2];
}

// Example usage
console.log(mergeLists([1, 2], [3, 4]));  // Output: [1, 2, 3, 4]

Explanation: This function merges two lists into one by concatenating them using the spread operator ....


46. Check if a String is Numeric

function isNumeric(s) {
  return !isNaN(parseFloat(s)) && isFinite(s);
}

// Example usage
console.log(isNumeric("12345"));  // Output: True

Explanation: This function checks if a string s is numeric by verifying it can be parsed as a float and is a finite number.


47. Find the Product of a List

function productOfList(list) {
  return list.reduce((acc, val) => acc * val, 1);
}

// Example usage
console.log(productOfList([1, 2, 3, 4]));  // Output: 24

Explanation: This function calculates the product of all elements in a list using the reduce() method, multiplying each element together.


48. Count Words in a String

function countWords(s) {
  return s.split(/\s+/).filter(Boolean).length;
}

// Example usage
console.log(countWords("Hello, World!"));  // Output: 2

Explanation: This function counts the number of words in a string by splitting the string by whitespace and filtering out any empty strings, then returning the length of the resulting array.


49. Flatten a List of Lists Using Recursion

function flatten(list) {
  return list.reduce((acc, val) => Array.isArray(val) ? acc.concat(flatten(val)) : acc.concat(val), []);
}

// Example usage
console.log(flatten([[1, 2], [3, [4, 5]], 6]));  // Output: [1, 2, 3, 4, 5, 6]

Explanation: This recursive function flattens a list of potentially nested lists by checking if each item is an array and recursively flattening it, or concatenating it directly if not.


50. Create a Simple GUI with Tkinter

While JavaScript doesn’t natively support GUI creation like Python’s Tkinter, you can create simple GUIs for the web using HTML and JavaScript. Here’s a basic example using HTML buttons and JavaScript event listeners:

<!DOCTYPE html>
<html>
<head>
<title>Simple GUI</title>
</head>
<body>
<button id="myButton">Click Me</button>
<script>
document.getElementById("myButton").addEventListener("click", function() {
  alert("Button clicked!");
});
</script>
</body>
</html>

Explanation: This HTML document includes a button that, when clicked, triggers a JavaScript alert saying "Button clicked!".