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”
1 |
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,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
<!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: