DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Adding Two Hours in DataWeave: Mule 4
  • Immutability in JavaScript — When and Why Should You Use It
  • TypeScript: Useful Features
  • Python F-Strings

Trending

  • How Kubernetes Cluster Sizing Affects Performance and Cost Efficiency in Cloud Deployments
  • Mastering Advanced Traffic Management in Multi-Cloud Kubernetes: Scaling With Multiple Istio Ingress Gateways
  • Mastering Fluent Bit: Installing and Configuring Fluent Bit on Kubernetes (Part 3)
  • The Human Side of Logs: What Unstructured Data Is Trying to Tell You
  1. DZone
  2. Coding
  3. JavaScript
  4. 32 Best JavaScript Snippets

32 Best JavaScript Snippets

I'd like to share some useful JavaScript code snippets I have saved that I think can help make your life as a developer easier.

By 
Rahul . user avatar
Rahul .
·
Mar. 03, 23 · Code Snippet
Likes (3)
Comment
Save
Tweet
Share
5.6K Views

Join the DZone community and get the full member experience.

Join For Free

Hi there, my name is Rahul, and I am 18 years old, learning development and designing sometimes. 

Today, I'd like to share some useful JavaScript code snippets I have saved that I think can help make your life as a developer easier.

Let's get started!

  1. Generate a random number between two values: const randomNumber = Math.random() * (max - min) + min
  2. Check if a number is an integer: const isInteger = (num) => num % 1 === 0

  3. Check if a value is null or undefined: const isNil = (value) => value === null || value === undefined

  4. Check if a value is a truthy value: const isTruthy = (value) => !!value

  5. Check if a value is a falsy value: const isFalsy = (value) => !value

  6. Check if a value is a valid credit card number:

JavaScript
 
const isCreditCard = (cc) => {
  const regex = /(?:4[0-9]{12}(?:[0-9]{3})?|[25][1-7][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})/;
  return regex.test(cc);
}


  1. Check if a value is an object: const isObject = (obj) => obj === Object(obj)
  2. Check if a value is a function: const isFunction = (fn) => typeof fn === 'function'
  3. Remove Duplicated from Array const removeDuplicates = (arr) => [...new Set(arr)];
  4. Check if a value is a promise: const isPromise = (promise) => promise instanceof Promise
  5. Check if a value is a valid email address:
JavaScript
 
    const isEmail = (email) => {
  const regex = /(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))/;
  return regex.test(email);
}


  1. Check if a string ends with a given suffix: const endsWith = (str, suffix) => str.endsWith(suffix)
  2. Check if a string starts with a given prefix: const startsWith = (str, prefix) => str.startsWith(prefix)
  3. Check if a value is a valid URL:
JavaScript
 
const isURL = (url) => {
  const regex = /(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+/;
  return regex.test(url);
}


  1. Check if a value is a valid hexadecimal color code:
JavaScript
 
const isHexColor = (hex) => {
  const regex = /#?([0-9A-Fa-f]{6}|[0-9A-Fa-f]{3})/;
  return regex.test(hex);
}


  1. Check if a value is a valid postal code:
JavaScript
 
const isPostalCode = (postalCode, countryCode) => {
  if (countryCode === 'US') {
    const regex = /[0-9]{5}(?:-[0-9]{4})?/;
    return regex.test(postalCode);
  } else if (countryCode === 'CA') {
    const regex = /[ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ] [0-9][ABCEGHJKLMNPRSTVWXYZ][0-9]/;
    return regex.test(postalCode.toUpperCase());
  } else {
    // Add regex for other country codes as needed
    return false;
  }
}


  1. Check if a value is a DOM element:
JavaScript
 
const isDOMElement = (value) => typeof value === 'object' && value.nodeType === 1 && typeof value.style === 'object' && typeof value.ownerDocument === 'object';


  1. Check if a value is a valid CSS length (e.g. 10px, 1em, 50%):
JavaScript
 
const isCSSLength = (value) => /([-+]?[\d.]+)(%|[a-z]{1,2})/.test(String(value));


  1. Check if a value is a valid date string (e.g. 2022-09-01, September 1, 2022, 9/1/2022):
JavaScript
 
const isDateString = (value) => !isNaN(Date.parse(value));


  1. Check if a value is a number representing a safe integer (those integers that can be accurately represented in JavaScript): const isSafeInteger = (num) => Number.isSafeInteger(num)
  2. Check if a value is a valid Crypto address:
JavaScript
 
//Ethereum
const isEthereumAddress = (address) => {
  const regex = /0x[a-fA-F0-9]{40}/;
  return regex.test(address);
}

//bitcoin
const isBitcoinAddress = (address) => {
  const regex = /[13][a-km-zA-HJ-NP-Z0-9]{25,34}/;
  return regex.test(address);
}

// ripple
const isRippleAddress = (address) => {
  const regex = /r[0-9a-zA-Z]{33}/;
  return regex.test(address);
}


  1. Check if a value is a valid RGB color code:
JavaScript
 
const isRGBColor = (rgb) => {
  const regex = /rgb\(\s*([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\s*,\s*([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\s*,\s*([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\s*\)/;
  return regex.test(rgb);
}


  1. Quickly create an array of characters from a string:
JavaScript
 
const string = "abcdefg";
const array = [...string];


  1. Quickly create an object with all the properties and values of another object but with a different key for each property:
JavaScript
 
const original = {a: 1, b: 2, c: 3};
const mapped = {...original, ...Object.keys(original).reduce((obj, key) => ({...obj, [key.toUpperCase()]: original[key]}), {})};


  1. Quickly create an array of numbers from 1 to 10:
JavaScript
 
const array = [...Array(10).keys()].map(i => i + 1);


  1. Quickly shuffle an array:
JavaScript
 
const shuffle = (array) => array.sort(() => Math.random() - 0.5);


  1. Convert an array-like object (such as a NodeList) to an array:
JavaScript
 
const toArray = (arrayLike) => Array.prototype.slice.call(arrayLike);


  1. Sort Arrays:
JavaScript
 
//Ascending
const sortAscending = (array) => array.sort((a, b) => a - b);

//Descending
const sortDescending = (array) => array.sort((a, b) => b - a);


  1. Debounce a function:
JavaScript
 
const debounce = (fn, time) => {
  let timeout;
  return function(...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => fn.apply(this, args), time);
  };
};


  1. Open a new tab with a given URL:
JavaScript
 
const openTab = (url) => {
  window.open(url, "_blank");
};


  1. Get the difference between two dates:
JavaScript
 
const dateDiff = (date1, date2) => Math.abs(new Date(date1) - new Date(date2));


  1. Generate a random string of a given length:
JavaScript
 
const randomString = (length) => {
  let result = "";
  const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
};


  1. Get value of cookie:
JavaScript
 
const getCookie = (name) => {
  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);
  if (parts.length === 2) return parts.pop().split(";").shift();
};


Thank you for Reading. It is important to note that simply copying and pasting code without understanding how it works can lead to problems down the line. 

It is always a good idea to test the code and ensure that it functions properly in the context of your project.

Also, don't be afraid to customize the code to fit your needs. As a helpful tip, consider saving a collection of useful code snippets for quick reference in the future.

I am also learning if I am going wrong somewhere, let me know.

Data structure JavaScript Snippet (programming) Strings

Published at DZone with permission of Rahul .. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Adding Two Hours in DataWeave: Mule 4
  • Immutability in JavaScript — When and Why Should You Use It
  • TypeScript: Useful Features
  • Python F-Strings

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!