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.
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.
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.
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.
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:
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.