by Cristina | Jul 25, 2021 | JavaScript
In this lesson we introduce the JavaScript join method which, given an array, returns a string.
This method is similar to the previous toString, discussed in the previous lesson. The difference with the toString method is that the latter can also be used on other variables, while join is used only with arrays.
Also in this case the original array remains unchanged, so we have to store the result in another variable, and then use it where appropriate.
The syntax of the JavaScript join() method is as follows: array.join(separator), where the separator is optional and if not specified, elements will be separated by a comma (,).
Let’s now deal with practical examples to understand how it works.
JavaScript join – example 1
As a first example let’s convert a simple array of numbers into a string, using the join () method.
So let’s assume we have the following array of numbers:
var numbers = [5,4,3,2,6,9,62];
We then use the join method to convert the array and store the result in a variable, such as a string name.
Then we display the result in the browser console.
var str = numbers.join();
console.log(str);
In this way we will get numbers separated by a comma.
JavaScript join – example 2
We propose the same example again but with an array of strings, so we repeat the example above by changing only the array.
For example, if by hypothesis we have the following array:
var objectsSchools = ['pencil', 'eraser', 'sharpener', 'notebook', 'pencil'];
And then we apply the join method to the array of starting strings, displaying the result for simplicity always in the browser console.
var str = objectsSchools.join('-');
console.log(str);
We will display the following result: pencil – eraser – sharpener – notebook – pencil.
Conclusion
In this article we talked about the JavaScript join method, in the next lessons we will cover other methods with numerous other examples.
Some useful links
JavaScript tutorial
JavaScript Calculator
Object in JavaScript
For in loop
Caesar cipher decoder
Slot Machine in JavaScript
by Cristina | Jul 25, 2021 | JavaScript
In this lesson we will talk about the JavaScript slice method useful for selecting elements of an array.
This method returns a new array with the selected elements.
The syntax of slice() is as follows: array.slice(start, end).
The start and end parameters are optional. The beginning is a numerical value that indicates where the selection starts from, while the end is always a numerical value that indicates where the selection ends.
Be careful though. The initial array will not be modified, so to get the selection we can store it in a variable and then use it where needed.
JavaScript slice – first example
Take an array of 7 elements as input and select only the second and fourth.
First we take our array of 7 numbers as input.
var numbers = [5,4,3,2,6,9,62];
Then, using the slice method, we select the required elements or the second and fourth. We store the selection made in a variable, for example a result name.
Finally we display the result in the browser console.
var result = numbers.slice(2,4);
console.log(result);
As we can see by testing it, an array with the selected elements will appear in the console.
JavaScript slice – second example
We select all the elements of an array of strings starting from the second.
Suppose we have this array of strings:
var objectsSchools = ['pencil', 'eraser', 'sharpener', 'notebook', 'pencil'];
Then we use the slice method by specifying only the first parameter.
var result = objectsSchools.slice(2);
console.log(result);
In the console we will see all the elements starting from the second: Array (3) [“sharpener”, “notebook”, “pencil”].
So if we do not specify the second parameter, all the elements are selected up to the end of the array.
If, on the other hand, we do not even specify the first parameter, we will clearly have a copy of the starting array.
Conclusion
In this lesson we have approached the slice method of JavaScript through practical examples.
Some useful links
JavaScript tutorial
JavaScript Calculator
Object in JavaScript
For in loop
Caesar cipher decoder
Slot Machine in JavaScript
by Cristina | Jul 25, 2021 | JavaScript
JavaScript forEach method is used over arrays to iterate and apply a function to each element.
This method was introduced starting with ECMAScript 5 (ES5), along with other features.
The syntax is as follows: array.forEach(function(currentValue, index, array), thisValue).
Where the function is required, therefore mandatory, while thisValue is optional and represents the value to pass to the function as this value. If not specified, undefined is passed as thisValue .
The function specified as an argument to the forEach method has 3 parameters:
- currentValue which is required and represents the current value of the array element;
- index is optional and represents the index of the current element of the array;
- array, optional, represents the array to which the element under consideration belongs.
JavaScript forEach – Difference with the for loop
We loop an array with the for loop and then the foreach.
So, suppose we have an array of numbers and print them using a for loop:
var numbers = [13, 25, 8, 9, 12, 9];
for (let i = 0; i < numbers.length; i++){
console.log(numbers[i])
}
Now we print the same result using forEach this time.
var numbers = [13, 25, 8, 9, 12, 9];
numbers.forEach(function(number){
console.log(number);
});
}
We passed a function with the currentValue which in our case represents the element contained in the array.
What if I also want to print the index with the forEach loop?
Just add the second parameter of the function or the index, which represents the index of each element.
var numbers = [13, 25, 8, 9, 12, 9];
numbers.forEach(function(number, index){
console.log('index ' + index + ' number: ' + number);
});
Finally, we use the last parameter which is the array itself to print it out.
var numbers = [13, 25, 8, 9, 12, 9];
numeri.forEach(function(array){
console.log(array);
});
JavaScript forEach – first example
Let’s now take some examples of the application of the forEach loop.
Having as input an array of numbers, we add separately the elements of even place from those of odd place, using the forEach loop.
So let’s create an array of numbers and check the odd or even position using the modulo operator.
let sumEven = 0, sumOdd = 0;
let numbers = [13, 25, 8, 9, 12, 9];
numbers.forEach(sumEvenOdd);
function sumEvenOdd(element, index) {
if (index % 2 == 0){
sumEven += element;
}
else {
sumOdd += element;
}
document.getElementById("sum-even").innerHTML = sumEven;
document.getElementById("sum-odd").innerHTML = sumOdd;
}
Upon entering the calculation made in the html page.
So for example in two different divs we insert the different calculated sums:
<div id="sum-even"></div>
<div id="sum-odd"></div>
The same algorithm could also be solved with a for loop. Let’s implement it to see the difference in use of the two loops.
let sumEven = 0, sumOdd = 0;
let numbers = [13, 25, 8, 9, 12, 9];
for(let i = 0; i < numbers.length; i++){
if (index % 2 == 0){
sumEven += numbers[i];
}
else {
sumOdd += numbers[i];
}
document.getElementById("sum-even").innerHTML = sumEven;
document.getElementById("sum-odd").innerHTML = sumOdd;
}
JavaScript forEach – second example
In this second example we will also use the third parameter, which is the array to which the element refers.
Given an array of numbers, for each element add a random number.
So let’s create a function where we add a random number to each element.
Here is the complete algorithm:
let numbers = [65, 44, 12, 4];
numbers.forEach(addRandom)
function addRandom(element, index, array) {
array[index] = element + Math.floor(Math.random()*9);
}
document.getElementById("random").innerHTML = numbers;
In the html we then write the div where to display the result:
<div id="random"></div>
Conclusion
In this lesson we have studied the JavaScript forEach method through practical examples.
Some useful links
JavaScript tutorial
JavaScript Calculator
Object in JavaScript
For in loop
Caesar cipher decoder
Slot Machine in JavaScript
by Cristina | Jul 25, 2021 | JavaScript
The JavaScript splice method adds and removes elements to an array starting from a specified location.
The syntax is as follows: array.splice(index, q, element1,…, elementN).
Where index represents the index from which to start and can be a negative value, which indicates that it starts from the end of the array.
The quantity q represents the quantity of items to be deleted, and if it is set to 0, or an unspecified value, no items are deleted. Otherwise, as many elements as specified are deleted.
Finally element1 … elementN are the elements to be included in the array.
The index parameter is required, while q and elements are optional parameters.
JavaScript splice – first example
Remove 3 elements from a 7-element array, starting at position 1, using the splice() method.
Let’s start with the following array of 7 numbers:
var numbers = [5,4,3,2,6,9,62];
Now to delete the elements starting from position 1, we use the splice () method and then we display the result, for convenience, in the browser console.
numbers.splice(1,3);
console.log(numbers);
So we used the splice method using the optional q parameter.
JavaScript splice – second example
Add 2 elements to an array of 7 numbers, starting from position 3 and eliminating only the third.
So, always starting from this array of numbers:
var numbers = [5,4,3,2,6,9,62];
Then, we apply the splice method to insert two values, for example 15 and 20 and delete the third, in our case the number 3.
After we always display the result in the browser console.
Here is the sample code:
numbers.splice(2,1,15,20);
console.log(numbers);
Conclusion
In this lesson we have seen how to use the splice method of JavaScript, in the next lesson we will see how to deal with other methods through numerous examples.
Some useful links
JavaScript tutorial
JavaScript Calculator
Object in JavaScript
For in loop
Caesar cipher decoder
Slot Machine in JavaScript
by Cristina | Jul 25, 2021 | JavaScript
In this lesson we study JavaScript reverse method, which is useful for reversing the elements of an array.
The syntax is as follows: array.reverse().
So let’s take some examples to understand how it works.
JavaScript reverse – first example
Reverse the order of an array of strings taken as input, using the reverse() method.
So let’s take our array as input, for example an array made up of school objects like the following:
var objectsSchool = ['eraser', 'notebook', 'pencil'];
Then we simply use the reverse method on the given array, following its syntax and view the result in the browser console.
Here is the example code for using the reverse() method of JavaScript:
objectsSchool.reverse();
console.log(objectsSchool);
In this way, in the console we will see the contents of the starting array in reverse order.
JavaScript reverse – second example
Sort an array of numbers and then reverse it using the reverse() method.
So this time we take an array of numbers as input, as shown in the example below:
var numerbs = [5,4,3,2,6,9,62];
We also remember that in order to perform a numerical sorting of an array we must use the syntax array.sort(comparison function), as explained in this lesson: sort javascript.
Then we order it following the specifications indicated in the previous lesson:
numerbs.sort(function(a, b) {
return a - b;
});
Finally we apply the reverse method of JavaScript and display the result, for convenience, in the console of our browser.
numerbs.reverse();
console.log(numerbs);
If we reflect in this case, the same result could be obtained simply by performing a descending ordering of the starting array.
Below I therefore present a possible alternative solution to the proposed algorithm that does not use the reverse method of JavaScript.
var numbers = [5,4,3,2,6,9,62];
numbers.sort(function(a, b) {
return b - a;
});
console.log(numbers);
Conclusion
In this lesson we have simply seen some very simple examples of using the JavaScript reverse method. In the next lessons we will face still other methods, through the study of practical examples.
Some useful links
JavaScript tutorial
JavaScript Calculator
Object in JavaScript
For in loop
Caesar cipher decoder
Slot Machine in JavaScript