Learn JavaScript concepts by building a random quote generator

Search for a command to run...

let index=Math.floor(Math.random()*quotes.length;
<!--This will give a random quote-->
quotes[index];
Here you have a ) forgotten. Otherwise super post. Thanks for that!
Maybe not for beginners, but a useful library is Lodash. There is shuffle to sort an array too randomly. That way you can save the math() story.
But to bring JavaScript closer, your post is great!
Fixed it. Thanks for the feedback Kevin Pliester. Yeah. The motive was to use only pure JavaScript.
2022 was a year full of learnings for me. It was about solving problems, lots of iterations, making solid fundamentals, and growing up as a person. Even though it feels like this year went really fast and I have a very vague memory of it, this is my ...

Finally, the wait is over. Last year I built and launched Tabwave, a mindful productivity chrome extension that replaces your browser's new tab. It has been my passion project for a long time. And now it has become even more mindful and beautiful. Af...

The modern web has evolved over the years with new tools and technologies. We are introduced to new approaches to rendering websites and apps. With the rise of frameworks like NextJs and Remix, SSR has gained a lot of popularity in the last few years...

If you are following me for a while you know I love building side projects. And every time I decided to build one, I didn't know how it will turn out in the end. But one thing is for sure, it all started with a half-baked idea. half baked idea? what...

Did you know you can create GraphQL APIs within minutes without writing a single line of code? Well, I didn't. Thanks to the Hasura X Hashnode hackathon. Now I know and so you will. Hi there, In this blog post I will talk about why and how I built a ...

Learning JavaScript is fun. But What's the point if you are not building stuff with it. So in this article, we will learn javascript basic concepts and create a random quote generator of our own.
I assume you have a basic knowledge of HTML and CSS as the main objective of this article is to learn javascript. Else you can check these tutorials on HTML and CSS. I will try to explain everything in detail and by the time you finish this lesson, you will have an understanding of concepts like strings, arrays, functions, event listeners, template literals in JavaScript. So let's begin.
Lets first create three different files in our folder as
The first step is to create a UI. Here is our index.html file look like
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<link rel="shortcut icon" href="icons/favicon.png">
<title>Random quote</title>
</head>
<body>
<div class="content">
<div class="card">
<h2>Random quote</h2>
<p>Do you want a random quote ?</p>
<!--button to display random quote-->
<button class="btn">Generate</button>
</div>
<div id="quote">
<!--Quote will be displayed here.-->
</div>
</div>
</body>
<script src="script.js"></script>
</html>

And this is how it looks like in the browser. Wait a minute, It doesn't look nice right.
Let's make it appealing by adding our style.css file
body {background-color: #8c1aff;}
.content{
max-width: 600px;
padding:20px;
margin:auto;
justify-content: center;
align-items: center;}
h2 {
background-color: #4a4be7;
color:#ffffff;
padding:10px;
font-family: arial;
text-align: center;
border-radius:5px;
box-shadow: 4px 4px #ee9be4;}
.btn{
height:50px;
width:150px;
font-size: 18px;
color:#ffffff;
background-color: #ee9be4;
box-shadow: 4px 4px #4a4be7;
padding:5px;
border-radius: 5px;}
.card{
padding:15px 30px 15px 30px;
max-width:500px;
max-height:300px;
text-align: center;
background-color: #f2e6ff;
border-radius: 5px;
border-top: #ee9be4 5px;
margin-top: 20px;}
button:focus {outline: none;}
p{
font-family:Segoe UI;
font-size: 20px;}
img{
height:25px;
width:25px;}
And boom ! this looks great now.

Now let's think about how we are going to make it work. We need to figure out a way to display random quotes after clicking a button. And We will go with the simplest way to do it. How? let's see.
Forget coding. let's just think about what we have to do. okay. First, we will need quotes. We will have to store them somewhere and do something such that we can display a random quote after clicking a button. That's it.
A string is a sequence of one or more characters that may consist of letters, numbers, or symbols. Strings in JavaScript are primitive data types which we are going to use to create quotes.
In JavaScript, there are three ways to write strings. They can be written inside single quotes (' '), double quotes (" "), or backticks ( ).
Strings with backticks(``) are called template literals which we will learn later.
'This is a string'
So all our quotes are basically strings like this.
'Stay hungry, stay foolish !'
But there are multiple such strings and we need something to store them. Here comes the concept of Arrays. But what's an array?
An array in JavaScript is a type of global object that is used to store data. Arrays consist of an ordered collection or list containing zero or more data types, and use numbered indices starting from 0 to access specific items.
<!--Creating an array-->
let quotes =[];
Arrays can contain any data type, including numbers, strings, and objects. We will be storing our strings in an array like this.
let quotes=[
'The secret to life is to love who you are.',
'Look for opportunities in every change in your life.',
'Persist while others are quitting.',
'and so on.'
];
The length property of an object which is an instance of type Array sets or returns the number of elements in that array.
quotes.length;
<!--Output-->
4
An item in a JavaScript array is accessed by referring to the index number of the item in square brackets.
quotes[2];
<!--Output : -->
Persist while others are quitting.
But here we will not access like this. We want a random index to display a random quote. Then how do we do that? We will use the math object.
Math is a built-in object that has properties and methods for mathematical constants and functions.

If you type math in console, you will see there are so many built-in methods for Math object. We will be using a few of them.
The Math.random() function returns a floating-point, pseudo-random number in the range 0 to less than 1. See how it returns every time we call it in the console.

But this is not what we want. We want a whole number and not a floating type. For this, the Math object provides another method called Math.floor()
Math.floor() returns a number representing the largest integer less than or equal to the specified number. So if we pass the math.random() as a parameter to math.floor() we will get a whole number. But Math.floor() is always rounding down to the nearest decimal, therefore, every decimal between 0 and 1 will always revert back to 0.

In order to get a random number between 0 to the length of our array, we will multiply the math.random() by quotes.length. Finally the random index we want is
let index=Math.floor(Math.random()*quotes.length);
<!--This will give a random quote-->
quotes[index];
index will always generate a valid array index number for our quotes array. So we figured out how to retrieve a random quote from the quotes array. But we don't want to display just a string. We are going to do it nicely using template literals.
The Template Literal, introduced in ES6, is a new way to create a string. With it comes new features that allow us more control over dynamic strings in our programs.
Template literals are string literals allowing embedded expressions. It can contain placeholders. These are indicated by the dollar sign and curly braces (${expression}).
`string text ${expression} string text`;
With the ability to have multi-line strings and use Template Expressions to add content into our string, this makes it really nice to use for HTML templates in our code. So we will create a HTML template for our quote and store it in a variable. We used the placeholder to pass our quotes in the template.
let quote=`<div class="card">
<img src="icons/favicon.png">
<p>${quotes[index]}</p> <!--random quote string-->
<img src="icons/favicon.png">
</div>
`;
I added images to make it more appealing.
To access an element in dom(Document Object Model), we will use the querySelector() method. The Document method querySelector() returns the first element within the document that matches the specified selector. The syntax is
element = document.querySelector(selectors);
In our HTML file, we have a div element with id="quote". We will access it in the same way as this. And then we will add the HTML template we created earlier to this div element.
Each HTML element has an innerHTML property that defines both the HTML code and the text that occurs between that element's opening and closing tag. By changing an element's innerHTML after some user interaction, we can make much more interactive pages.
let div=document.querySelector('#quote');
div.innerHTML=quote;
The code we wrote till now will work only once. And we want to execute this every time we want to display a quote. We can do this using functions.
A function is a block of code that performs an action or returns a value. Functions are custom code defined by programmers that are reusable, and can, therefore, make your programs more modular and efficient.
Functions are defined, or declared, with the function keyword. Below is the syntax for a function in JavaScript.
function nameOfFunction() {
// Code to be executed
}
We will create the displayQuote function add all this code in the function.
function displayQuote(){
let index=Math.floor(Math.random()*quotes.length);
//display the quote of that index
let div=document.querySelector('#quote');
let quote=`<div class="card">
<img src="icons/favicon.png">
<p>${quotes[index]}</p>
<img src="icons/favicon.png">
</div>
`;
div.innerHTML=quote;
}
We are almost done. Just need to invoke this displayQuote function whenever we click the generate button.
Events are actions that take place in the browser that can be initiated by either the user or the browser itself. Like in our case it's when the user clicks the generate button.
An event listener watches for an event on an element. We will use the addEventListener() method to listen for the event. addEventListener() takes two mandatory parameters .
target.addEventListener(type, listener [, options]);
We have a button element with class="btn". The click event will call the displayQuote function every time we click on the button and display a random quote.
let btn=document.querySelector('.btn');
btn.addEventListener('click', displayQuote);

And we are done. congratulations. We built a random quote generator while learning some JavaScript concepts.
So the quote generator is ready. Also if you wish, you can add some more features of your own like tweeting the quote or something like that.
You can find the complete repository of the code on Github.
Also, you can see it live here.
I hope you had fun while doing this and learned a few things along the way.
Well for me this process of building things helps me a lot while learning.
I keep writing about the things I learned and applied. So you can connect with me on Twitter, Github or Linkedin. Also, subscribe to my newsletter and stay up-to-date with my latest blog posts.
⚡ Happy learning!