Share 30 basic and practical JavaScript code snippets

c2c47c1ea961ade254e20aeb82635b07.jpeg

In today's article, I want to share with you 30 basic and practical JavaScript code snippets that will help you improve your web development capabilities. From debounce and throttling for improved performance, to array manipulation, string manipulation, number validation and more.

Learn how to implement these time-saving techniques and enhance your development workflow. Improve your skills and stay ahead in the ever-evolving world of web development with these indispensable JavaScript code snippets.

01. Debounce the function to limit the number of times it is called.

function debounce(func, delay) {
  let timer;
  return function() {
    clearTimeout(timer);
    timer = setTimeout(func, delay);
  };
}

02. Throttle a function to limit the rate at which it is called.

function throttle(func, limit) {
  let throttled = false;
  return function() {
    if (!throttled) {
      func();
      throttled = true;
      setTimeout(function() {
        throttled = false;
      }, limit);
    }
  };
}

03. Check whether the variable is an array:

function isArray(variable) {
  return Array.isArray(variable);
}

04. Flatten an array of nested arrays:

function flattenArray(array) {
  return array.flat();
}

05. Generate a random number between the minimum and maximum values:

function getRandomNumber(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

06. Check whether the string is a palindrome:

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

07. Capitalize the first letter of the string:

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

08. Check if the number is even:

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

09. Check whether a number is prime:

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

10. Trim spaces from the beginning and end of a string:

function trimWhitespace(str) {
  return str.trim();
}

11. Check if the object is empty:

function isEmptyObject(obj) {
  return Object.keys(obj).length === 0;
}

12. Reverse the string:

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

13. Check if the value is a number:

function isNumber(value) {
  return typeof value === 'number' && !isNaN(value);
}

14. Shuffle array:

function shuffleArray(array) {
  return array.sort(() => Math.random() - 0.5);
}

15. Remove duplicates from an array:

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

16. Get the current date and time:

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

17. Check if a string starts with a specific substring:

function startsWith(str, substring) {
  return str.startsWith(substring);
}

18. Convert the string to lowercase:

function toLowerCase(str) {
  return str.toLowerCase();
}

19. Check if a value is an object:

function isObject(value) {
  return typeof value === 'object' && value !== null;
}

20. Check if a string contains a specific substring:

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

21. Generate a random alphanumeric string of specified length:

function generateRandomAlphanumeric(length) {
  let result = '';
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
}

22. Check whether an element exists in the array:

function isInArray(array, element) {
  return array.includes(element);
}

23. Reverse the order of words in a string:

function reverseWords(str) {
  return str.split(' ').reverse().join(' ');
}

24. Check if a string ends with a specific substring:

function endsWith(str, substring) {
  return str.endsWith(substring);
}

25. Check if a value is a function:

function isFunction(value) {
  return typeof value === 'function';
}

26. Find the maximum value in an array:

function findMaxValue(array) {
  return Math.max(...array);
}

27. Find the minimum value in an array:

function findMinValue(array) {
  return Math.min(...array);
}

28. Convert a string to a character array:

function stringToArray(str) {
  return Array.from(str);
}

29. Check if a string is empty or consists only of spaces:

function isStringEmpty(str) {
  return str.trim().length === 0;
}

30. Check if the value is a Boolean value:

function isBoolean(value) {
  return typeof value === 'boolean';
}

Summarize

The above are the 30 basic and practical JavaScript code snippets that I want to share with you today, I hope it will be helpful to you.

learn more skills

Please click on the public number below

8fccda1e5ec930f55e954d1a00b42a49.gif

Guess you like

Origin blog.csdn.net/Ed7zgeE9X/article/details/131335668
Recommended