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