# JavaScript: Get unique guid of the specified length, or 32 by default

## JavaScript String: Exercise-49 with Solution

Write a JavaScript function to get a guid (an acronym for 'Globally Unique Identifier'?) of the specified length, or 32 by default.
Test Data:
console.log(guid());
console.log(guid(15));
"hRYilcoV7ajokxsYFl1dba41AyE0rUQR"

Sample Solution:

JavaScript Code:

// Define a function named 'guid' that generates a unique identifier.
function guid(len) {
// Initialize an empty array to store characters of the generated identifier.
var buf = [],
// Define a string containing all possible characters for the identifier.
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
// Calculate the length of the character string.
charlen = chars.length,
// Set the desired length of the identifier or default to 32.
length = len || 32;

// Loop 'length' times to generate the identifier.
for (var i = 0; i < length; i++) {
// Generate a random index to pick a character from the character string.
buf[i] = chars.charAt(Math.floor(Math.random() * charlen));
}

// Return the generated identifier by joining the array of characters into a string.
return buf.join('');
}

// Log the result of calling 'guid' with no arguments to generate a default-length identifier.
console.log(guid());
// Log the result of calling 'guid' with an argument of 15 to generate a 15-character identifier.
console.log(guid(15));

Output:

0ZcEJpjnYG4yHqCjtFSf44d4TuJHi1Xh
PrwS8Ev7m3onHtk

Explanation:

The above code defines a function "guid(len)" that generates a random unique identifier (GUID). Here's a breakdown:

• The 'guid' function takes an optional parameter 'len' to specify the length of the generated GUID.
• It initializes an empty array 'buf' to store the characters of the GUID.
• It defines a string 'chars' containing all possible characters that can be used in the GUID.
• It calculates the length of the character string using 'charlen'.
• It sets the length of the GUID to the specified length or defaults to 32 if no length is provided.
• It loops 'length' times and, in each iteration, generates a random character from the 'chars' string and adds it to the 'buf' array.
• Finally, it joins the characters in the 'buf' array to form a string and returns the generated GUID.

Flowchart:

Live Demo:

See the Pen JavaScript Get unique guid of the specified length, or 32 by default-string-ex-49 by w3resource (@w3resource) on CodePen.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿