In this post, we learn to generate random names using javascript. Here we have the first and last names array. Using the getRandomInt() method we select one name from each array and concatenate them into a full name.
getRandomInt method used to get a random integer between two values.
Html Code
<input id="clickMe" type="button" value="Generate Random Name" onclick="generateName();" />
<h2 id="random_name"></h2>
Javascript
function capFirst(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function generateName(){
var first_name = ["abandoned","able","absolute","adorable"];
var last_name = ["people","history","way","art","world"];
var name = capFirst(first_name[getRandomInt(0, first_name.length + 1)]) + ' ' + capFirst(last_name[getRandomInt(0, last_name.length + 1)]);
document.getElementById("random_name").innerHTML = name;
}
Full code
<!DOCTYPE html>
<html lang="en">
<head>
<title>Random Name Generator Javascript</title>
</head>
<body style="background-color: lightcyan;">
<input id="clickMe" type="button" value="Generate Random Name" onclick="generateName();" />
<h2 id="random_name"></h2>
<script>
function capFirst(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function generateName(){
var first_name = ["abandoned","able","absolute","adorable"];
var last_name = ["people","history","way","art","world"];
var name = capFirst(first_name[getRandomInt(0, first_name.length + 1)]) + ' ' + capFirst(last_name[getRandomInt(0, last_name.length + 1)]);
document.getElementById("random_name").innerHTML = name;
}
</script>
</body>
</html>
I hope It will help you.

Brijpal Sharma is a web developer with a passion for writing tech tutorials. Learn JavaScript and other web development technology.