Print Alphabets A to Z & a to z using pure JavaScript!

In this post, we are going to write a pure JavaScript program to print alphabets from A to Z and a to z.

To print Alphabets in JavaScript is pretty simple, for example, the below code will print “A”

console.log(String.fromCharCode(65));

So, the value 65 is A, the same way to print B, we need to pass the value of 66 and so on. Therefore, to print A to Z, all we have to do is to pass the value from 65 to 91. And, for small letters, it will be 97 to 123.

Let’s write a function for that,

function printAlphabets(option){
	
	//set the default value of i & j to print A to Z
	var i = 65;
	var j = 91;

	//if the option is small set the value of i,j to print a to z
	if(option == 'small'){
		i = 97;
		j = 123; 
	}

	//loop through the values from i to j
	for(k = i; k < j; k++){
		//convert the char code to string (Alphabets)
		var str =String.fromCharCode(k);
		//print the result in console
                console.log(str);
	}

}

Now, when you call the function printAlphabets(), you can see A to Z printed on your console. For small letters, you need to call printAlphabets(‘small’)

Let’s write a simple HTML page and print the values, also i will put the demo link at the bottom of this page.

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>Page Title</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<!-- Load Bootstrap library for better UI look & feel -->
	<link rel="stylesheet" type="text/css" media="screen" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" />
	<script>
function printAlphabets(option){
	
	//set the default value of i & j to print A to Z
	var i = 65;
	var j = 91;

	//if the option is small set the value of i,j to print a to z
	if(option == 'small'){
		i = 97;
		j = 123; 
	}

	//clear the result
	document.getElementById("result").innerHTML = '';

	//loop through the values from i to j
	for(k = i; k < j; k++){
		//convert the char code to string (Alphabets)
		var str =String.fromCharCode(k);
		//print the result
		document.getElementById("result").insertAdjacentHTML('beforeend', str+" ");
	}

}
	</script>
</head>
<body>
	<div class="container">
		<br />
		<div class="row">
			<div class="col-md-12">
				<h2>Print Alphabets using Pure JavaScript!</h2>

				<button class="btn btn-success" onclick="printAlphabets()">Print Alphabets (CAPS)</button>
				<button class="btn btn-primary" onclick="printAlphabets('small')">Print Alphabets (Small)</button>
				
				<br><br>
				<b>Result:</b>
				<div id="result"></div>
			</div>
		</div>
	</div>
</body>
</html>

Copy this example and put it in a file then save it as .html and then open in browser to execute the complete code.

You can see the demo here:

demo

Leave a Comment

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

Scroll to Top