Categories
JavaScript Answers

How to create a random token in JavaScript?

Spread the love

Sometimes, we want to create a random token in JavaScript.

In this article, we’ll look at how to create a random token in JavaScript.

How to create a random token in JavaScript?

To create a random token in JavaScript, we can use the Math.random method with the toString method.

For instance, we write:

const rand = () => {
  return Math.random().toString(36).substr(2);
};

const token = () => {
  return rand() + rand();
};

console.log(token());

We create a random number with Math.random.

Then we call toString with 36 to convert the number to a base 36 number string.

And then we call `substr with 2 to remove the initial 0’s.

We then call rand twice and combine the strings together and return it.

Conclusion

To create a random token in JavaScript, we can use the Math.random method with the toString method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *