Random quotes generator

Random quotes generator

In this lesson we will develop a random quotes generator.

We will make sure that clicking on a button, from time to time, generates a new sentence.

Try the example below by clicking on the button:

Random Quotes Generator

Development of the random quotes generator

First let’s develop the simple HTML code needed to create the generator.

We insert a container to contain everything where inside we first insert a title, after a div where we will insert the randomly generated sentence and finally a button to generate the event on click.

Here is the HTML code:





Insert some CSS code to give some graphics to the project.

We then develop the JavaScript code.

First of all, let’s prepare the array that will contain all the phrases by choosing some quotes from famous people.

Then through the addEventListener event we call the function to generate a random element of the array upon clicking on the button.

We can simply use a function that generates a random number between 0 and the length of the array minus 1. Then we locate the sentence in the array using this number as an index.

Here is the complete code:



myQuotes = [
    'A volte sono le persone che nessuno immagina che possano fare certe cose quelle che fanno cose che nessuno può immaginare.',
    'La fantasia è più importante del sapere, perché il sapere è limitato.',
    'Chi dice che è impossibile non dovrebbe disturbare chi ce la sta facendo.',
    'C'è una forza motrice più forte del vapore, dell’elettricità e dell’energia atomica: la volontà.',
    'La misura dell’intelligenza è data dalla capacità di cambiare quando è necessario.',
    'La logica ti porta da A a B, l’immaginazione ti porta ovunque.',
    'Gli occhi sono lo specchio dell’anima… cela i tuoi se non vuoi che ne scopra i segreti.',
    'Imparerai a tue spese che nel lungo tragitto della vita incontrerai tante maschere e pochi volti.',
    'Ma guardi signora è facilissimo, le insegno io ad esser pazza. Basta gridare la verità in faccia a tutti, loro non ci crederanno e ti prenderanno per pazza.'
];

const buttonQuote = document.getElementById('new-quote');

buttonQuote.addEventListener('click',generate);

function generate(){
    randomQuote = randomNumber(myQuotes);

    const quote =  document.getElementById('quote');
    quote.innerHTML = myQuotes[randomQuote];
}

function randomNumber(array) {
    const num = Math.round(Math.random() * (array.length - 1));
    return num;
}

Conclusions

In this lesson we have developed a simple random quotes generator, choosing some famous quotes including Pirandello, Turing and Albert Einstein.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

JavaScript projects

JavaScript projects

In this article we will develop some simple JavaScript projects, such as displaying a counter that is incremented in various ways.

JavaScript projects – counter

In this first project we will build a counter using only Vanilla JavaScript.

Try clicking on the buttons below to increase or decrease the counter variable which starts from the initial value 0.

JavaScript Counter

0

How can we develop the code?

First here is the simple html code needed for our project.





We have inserted the button minus which has the function of decreasing the variable number and the button plus which instead has the function of increasing it.

To identify each element we used an id, in order to then be able to use the getElementById method in JavaScript.

We then add some simple CSS code of your choice. For example, I entered this:



.container {
    background-color: #2c45a3;
    text-align: center;
    padding: 20px;
    color: white;
}

h3 {
  font-size: 30px;  
}

button {
  font-size: 30px;
  background-color: #fc7180;
  color: #2c45a3;
  border: none;
  border-radius: 10px;
  padding: 10px 20px;
  cursor: pointer;
}

#number {
  font-size: 40px;
  padding: 0 50px;
}

And here is the JavaScript code that uses the addEventListener method to intercept the mouse click on the two plus and minus buttons.

What we will do by clicking the mouse on each button is simply to increase or decrease the value of the variable and write it in the element that has id number through the innerHTML property.



const number = document.getElementById('number');
const buttonPlus = document.getElementById('plus');
const buttonMinus = document.getElementById('minus');

buttonPlus.addEventListener('click', add);
buttonMinus.addEventListener('click', subtract);

let value = 0;

function add() {
  value++;
  number.innerHTML = value;
}

function subtract() {
  value--;
  number.innerHTML = value;
}

JavaScript projects – counter with different increment values

In this second example we increment the counter with different values: 1, 5, 10 or 100.

Then click on the various buttons to see the increase of the starting variable.

JavaScript Counter

0

In this second example we used the onclick event directly on the button in the HTML code.





You can see that we passed a second parameter depending on the value we want to increase.

Here is the JavaScript code:



const number = document.getElementById('number');

let value = 0;

function add(n) {
  value = value + n;
  number.innerHTML = value;
}

Conclusion

In this article we have developed a simple counter. We will then continue in the next articles to develop many interesting JavaScript projects.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

JavaScript isNaN

JavaScript isNaN

JavaScript isNaN function determines whether the value passed as an argument is not a number.

The syntax is therefore the following: isNaN(value).

The function returns a Boolean value that is true if the argument passed is not a number, otherwise it returns false.

JavaScript isNaN – examples

In all the examples presented under the isNaN function gives true:



isNaN('13years');
isNaN('thirteen');
isNaN('13:50');
isNaN('13-01-20');
isNaN('13 01 20');
isNaN('true');

Instead in these other cases it has false value:



isNaN('13.50');
isNaN('13');
isNaN('');

As we can see therefore even if I pass the empty string it gives false as a result, as if it were a number.

Furthermore, even if we pass a number as a string, it always returns false, as in the example below:



var num = '13';
console.log(isNaN(num));

In the browser console we will display false, because the variable num is interpreted as a number.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

Fibonacci JavaScript

Fibonacci JavaScript

In this lesson we will implement a Fibonacci sequence algorithm in JavaScript.

First of all, remember that the Fibonacci sequence is a sequence of positive integers in which each number, starting with the third, is the sum of the previous two and the first two are 1, 1.

So, for example if I want to see the first 10 terms of the Fibonacci sequence I have: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55.

Fibonacci JavaScript – algorithm

Ask in input, through a prompt, how many numbers to calculate and display them one under the other.

To develop this algorithm, first of all we think about the variables that we will need. Surely you need to use two variables to store the first two terms. So, for example, first = 1 and then second = 1.

Then we will need a third variable to store the sum of the first term with the second. So third = first + second.

Well, after having defined this reasoning, we need to repeat some operations.

At the beginning we have this situation: first = 1, second = 1 and third = 1 + 1 = 2.

Then you need to move the value from second to first and the value from third to second, in order to add them together. So: first = 1, second = 2 and third = 3.

Going on with this procedure we will have first = 2, second = 3 and third = 5.

Ultimately we must therefore repeat (iterate some instructions).

Fibonacci JavaScript – algorithm development

Here is a possible solution of the algorithm in JavaScript.

We ask through a prompt how many numbers of the Fibonacci sequence to display. Then we declare the necessary variables and make the assignments.

With a for loop then we repeat the following instructions: c = a + b and then a = b and b = c, i.e. we exchange a with b and b with c.

Here is the complete code of Fibonacci algorithm in JavaScript:



n = prompt('How many numbers do yout want to see?: ');
var a = 1;
var b = 1;
var c;

document.write(a + '
' + b + '
'); for (var i = 0; i< n-2; i++){ c = a + b; a = b; b = c; document.write(c + '
'); }

We can also add an input check on N using for example the do while loop. We therefore ensure that the user enters a number greater than 2.



do {
  n = prompt('How many numbers do yout want to see?: ');
} while (n <= 2);

Similarly, a solution for checking the input could be found using the while.



n = prompt('How many numbers do yout want to see?: ');

while (n <= 2){
     n = prompt('How many numbers do yout want to see?: ');
}

Conclusion

In this lesson we have simply seen an example on the Fibonacci sequence, in the next lessons we will tackle other examples using loops in JavaScript.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

Nesting for loops

Nesting for loops

In this lesson we talk about nesting for loops in JavaScript, with the for loop.

So we will see how to use a loop inside another loop.

To explain the concept of nested loop let’s try to create a table using html and javascript.

Nesting for loops – table

So let’s suppose we want to create a table of 3 rows and 4 columns where in each cell we will write the value of the row and of the column.

We should therefore obtain a result like the one in the figure below:

javascript tabella

To proceed to the solution of the following problem, first of all we open the table tag to which for convenience we assign a border equal to 1 and a space between the content and the border of the table of 10 pixels.

Then, with a first outer for loop we create the three lines.

So let’s initialize i to 1 and insert the condition i <4. Then we insert the opening tag of the line and below the closing one with two different document.write statements.

Between the opening tag of the line and the closing one we insert another for loop using a variable j initialized to 1. After we set as condition j <5 and we increment j by 1.

Within this second cycle we insert the tag for the cell and insert the value of the row and that of the column. Then we close the column tag.

Nesting for loops – code

Here is the complete code that has two for loops, one external and one internal.



document.write('');
for (var i=1; i<4; i++) {
   document.write('')
      for (var j=1; j<5; j++) {
          document.write('');
      }
      document.write('');
}
document.write('
'); document.write('row: ' + i + ' column: ' + j); document.write('
');

In this way, when the outer loop is executed for the first time it will write the tag of the first line. After that it will run the inner loop exactly 4 times, then it will produce the following code:

<tr>
   <td>Row: 1 column: 1</td>
   <td>Row: 1 column: 2</td>
   <td>Row: 1 column: 3</td>
   <td>Row: 1 column: 4</td>

After finishing the internal loop, the closing tag of the line will be printed. We will therefore have:

<tr>
   <td>Row: 1 column: 1</td>
   <td>Row: 1 column: 2</td>
   <td>Row: 1 column: 3</td>
   <td>Row: 1 column: 4</td>
</tr>

As soon as the first iteration is finished, the variable i increases by 1 and then we will proceed in the same way for the second line.

We will therefore have:

<tr>
    <td>Row: 1 column: 1</td>
    <td>Row: 1 column: 2</td>
    <td>Row: 1 column: 3</td>
    <td>Row: 1 column: 4</td>
</tr>
<tr>
    <td>Row: 2 column: 1</td>
    <td>Row: 2 column: 2</td>
    <td>Row: 2 column: 3</td>
    <td>Row: 2 column: 4</td>
</tr>

Similarly for the third row.

Conclusion

In this lesson, we ran a simple example using nesting for loops in JavaScript.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

JavaScript variables and costants

JavaScript toString

JavaScript toString

JavaScript toString method is used to convert an array to a string. The array to be converted can contain any data, such as numbers, objects, strings, etc. It is usually used to converter numbers in strings.

The syntax of this method is very simple: array.toString().

The toString() method therefore returns a string.

Since the original array remains unchanged, so we store the result in a variable and then use the string obtained where needed.

JavaScript toString method can also be used to convert a number to a string, using this syntax: num.toString(base).

Where the base represents the system in which to translate.

We can also omit the base in order to simply get the decimal number in a string.



var number = 20;
console.log("String: " + number.toString());  

But let’s make an example by specifying the base. Let’s convert a decimal number to binary:



var number = 20;
console.log("Binary : " + number.toString(2)); 

JavaScript toString – first example

Convert an array of numbers to a string using the toString() method.

So suppose we have the following array of numbers:



var numbers = [5,4,3,2,6,9,62];

We then use the toString method to convert the array and store the result in a variable such as a string name.

Finally we display the result in the browser console.



var stringNumbers = numbers.toString();
console.log(stringNumbers);

JavaScript toString – second example

The same could be done with an array of strings, so let’s repeat the example above by changing only the array.

For example, if we therefore have the following array:



var objectsSchools = ['pencil', 'eraser', 'sharpener', 'notebook', 'pencil'];

Then we apply the toString method to the array of starting strings and view the result for simplicity in the console.log.



var str = objectsSchools.toString();
console.log(str);

As in the previous example, once again we see a string in the console of our browser.

Conclusion

In this article we talked about the JavaScript toString method, in the next lesson we will tackle other methods with numerous examples.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

JavaScript shift and unshift

JavaScript shift and unshift

With the shift and unshift methods I remove and add respectively an element at the beginning of each array in JavaScript.

The syntax of these methods is as follows:

array.unshift (element1, element2,…, elementN)

array.shift()

As we can see with the unshift method it is possible to insert more than one element between round brackets, separated by commas.

JavaScript shift and unshift – example 1

Create an array of elements and add an element, inserted through a dialog box, at the head of the array.

So let’s assume we have our array of school items as always:



var objectsSchool = ['eraser', 'notebook', 'pencil'];

Then we ask the user to enter an element:



var objectNew = prompt('Insert a school object');

We therefore decide to insert it at the top of the array with the unshift method:



objectsSchool.unshift(objectNew);
console.log(objectsSchool);

In this case, in the console we will see as the first element the one entered by the user.

Now we delete the same element that the user has chosen to insert.

We will need to use the shift method:



objectsSchool.shift();
console.log(objectsSchool);

In the browser console, the first list will be displayed without the item entered by the user.

JavaScript shift and unshift – example 2

Let’s take an example using the days array that we have already used in the previous examples.

This time, however, we will remove the days at the beginning of the array, so starting from Monday.

Try clicking on the button below to get the effect:

Here is the complete code used to solve this simple algorithm that uses the shift () method to delete elements at the beginning of the array.


var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
function removeDay() {
  days.shift();
  alert ("I took off a day");
  // I print every day
  for (var i = 0; i < days.length; i ++) {
    alert(days[i]);
  }
}

After in the html page I insert the following code:

<input type="submit" value="Remove a day" onClick="removeDay()">

Likewise I use unshift () to add elements to the beginning of the array.

Here is a simple example:



var days = ["Monday"];
days.unshift("Tuesday");

Conclusion

Of course these are just simple examples of the JavaScript shift and unshift methods, useful for getting started with arrays in JavaScript. In the next few lessons we will address other methods.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

JavaScript pop

JavaScript pop

In this lesson we will cover the pop method in JavaScript, which is useful for deleting elements in an array.

In the previous lesson we have dealt with the push method and we have seen how to add elements to our queued array, now we will see how to delete them.

So to remove or add elements to the end of an array in JavaScript you can use the pop () and push () methods.

The syntax of the pop method is as follows:

array.pop();

JavaScript pop – example 1

Create an array that contains elements and delete the last element.

In this first example on the use of the pop () method, I first create an array that contains, for example, school objects, as in the previous example of the push.

Then with the pop method I delete the last element.

So here’s the simple example code:



var objectsSchools = ['eraser', 'notebook', 'pencil'];

objectsSchools.pop();

console.log (school objects);

JavaScript pop – example 2

Let’s take a demonstrative example of the pop () method.

For example, suppose you have the days of the week from Monday to Sunday stored in an array. Every time I click on a button inserted in the html page, I remove one day, the last.

Do the test by clicking on the button below several times, you will notice that each time the last day will be removed:

To make the script I create an array that contains the days of the week, for example

days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"].

After, I define a function called remove and insert the instructions to call the pop () method which deletes the days from the array and warns the user with an alert that the operation was successful. So with a for loop I display all the days left.

Here is the sample JavaScript code that uses the pop method of JavaScript:


var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
function removeElement() {
    days.pop();
    alert ("I remove a day");
    for (var i = 0; i < days.length; i++) {
        alert(days[i]);
    }
}

To invoke this function, I insert the action when clicking on the remove day button.

So in the html page I use the following code:

<input type="submit" value="Remove a day" onclick="removeElement()">

Conclusion

In this lesson we have covered some simple examples that use the JavaScript pop method.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

JavaScript array push

JavaScript array push

In this lesson we will see how to insert data into a JavaScript array push method, useful to insert element in array.

The syntax of this method is as follows: array.push(element).

Where array is the name of our array we want to populate. Element represents what we want to insert in the array.

You can also insert more elements and in this case, therefore, the syntax is as follows:

arrayname.push(element1, element2,…, elementon).

The element or elements will be inserted at the end of the array, that is, from the right.

Let’s now make some simple examples to better understand how this method works.

JavaScript array push – first example

Create an array that can contain everything related to eg school material. Then we ask the user for the name of something he wants to insert into this array and we add it to the initial array.

So suppose we have an initial array that contains 3 elements, such as this:

var schoolObjects = [‘rubber’, ‘notebook’, ‘pencil’];

Then we ask the user to insert an element and storing it in a User object variable. So let’s add this element into our array.
Here, then, is the complete code of the exercise that uses the push instruction in JavaScript:



var schoolObjects = ['eraser', 'notebook', 'pencil'];
var objectNew = prompt('Insert a school object');
schoolObjects.push(new object);
console.log(schoolObjects);

We simply display the final contents of our array in the browser console.

JavaScript array push – second example

Populate an empty array with 10 integers required by the user.

So we will first need to define an empty array and then, with a for loop, we need to ask the user for the numbers and populate the array in this way.

Here is the example code for solving the algorithm:


var numbers = [];
var number;
for (let i = 0; i < 10; i ++) {
  number = parseInt(prompt('Enter a number'));
  numbers.push(number);
}
console.log(numbers);

For convenience, we always display the final array in the console of our browser.

Conclusion

In this lesson we have dealt with simple examples on JavaScript array push method, in the next lessons we will further explore this instruction.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

JavaScript array

JavaScript array

In JavaScript an array is a useful tool for storing multiple data even of different types.

In fact, JavaScript, like other programming languages, allows the creation and management of arrays.

There are various ways to define an array in JavaScript, in this tutorial we will analyze them all and see which is more congenial.

JavaScript array – definition

First, let’s study the methods for defining an empty array.

First method to definition an array

The first method we analyze to define an empty array is the use of the Array () object.

This method follows the following syntax:

var photo = new Array();

So the photo variable is an array defined using the new constructor.

In this way the Array() object is exploited.

Second method to definition an array

You can also not use the new constructor to create an empty array, so you can also just write:

var photo = [];

JavaScript array – data entry

We can put the data into an array with multiple methods.

First method to insert data in array

Following the first method, we can assign the elements directly within the round brackets of the Array () object.

var photo = new Array(“img1.jpg”,”img2.jpg”,…);

Second method to insert data in array

The second method is the most used when we need to initialize an array with predefined elements and allows you to insert each element separated by commas:

var photo = [“img1.jpg”, “img2.jpg”, …];

Alternatively, you can create an empty array and then assign the elements:

var photo = [];

photo[0]=”img1.jpg”;

photo[1]=”img2.jpg”;

JavaScript array – read data

Now let’s see how to read data from an array.

Populate an array with the days of the week and print all elements.

In this lesson we will see how to print the elements without using the for loop and the length property, the subject of the next lessons.

So we put the days of the week in an array named days.

var days = [“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”, “Sunday”];

After considering that the first element has index 0 and the others to follow have an increasing index, we print each element simply in this way:

console.log(days[0]); ....

Here is the complete script:



var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
console.log (days [0]);
console.log (days [1]);
console.log (days [2]);
console.log (days [3]);
console.log (days [4]);
console.log (days [5]);
console.log (days [6]);

Of course, you can use a loop to read the entire array, but we will analyze it in the next lessons.

In this lesson we have studied some very simple examples of arrays in JavaScript, in the next lessons we will study the various methods necessary to perform some operations.

Conclusion

In this lesson we have seen how to create a JavaScript array, how to insert data and how to read it.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript