How to generate a GUID in Javascript

JavaScript is a powerful and flexible programming language that is used for web development, in web applications, for game development, and lots more. It allows you to implement dynamic features on web pages that cannot be done with only HTML and CSS1. It is one of the 3 languages all web developers must learn: HTML to define the content of web pages, CSS to specify the layout of web pages, and JavaScript to program the behavior of web pages

Here is a simple JavaScript function that generates a GUID: it generates a string in the format of a GUID using regular expressions and random number generation. You can call this function to generate a new GUID each time:

  1. function generateGUID() {
  2.   let guid = '';
  3.   for (let i = 1; i <= 32; i++) {
  4.     let random = Math.floor(Math.random() * 16).toString(16);
  5.     guid += random;
  6.     if (=== 8 || i === 12 || i === 16 || i === 20) {
  7.       guid += '-';
  8.     }
  9.   }
  10.   return guid;
  11. }
  12. console.log(generateGUID());

Explanation