JavaScript is one of the most used programming languages in the world. But how does it work? A focus on arrays and forEach and replace functions. JavaScript is one of the most used programming languages in the world. The main ones for developing web applications are the Olympus of greats such as C, C ++, PHP, Java, and Python. It is increasingly widespread and touches mobile, server, and desktop environments and is the basis of the operation of many sites and online services we use daily. Let’s see how to activate Javascript and what are the main features.
How Javascript Works
JavaScript requires a host program, which loads and executes the script. A typical example is that of the browser. When a web page that contains JavaScript code is visited, it is run by the interpreter contained in the browser. The interfaces that allow the code to relate to a browser are called DOM (Document Object Model). In the web environment, JavaScript is used to write small functions integrated into HTML pages that interact with the browser’s DOM to perform specific actions. An example of JavaScript code inside an HTML page does nothing but display a warning screen containing “Hello World”:
<script type = “text / javascript”>
alert (‘Hello world’);
</script>
To write the message directly on the HTML page:
<script type = “text / javascript”>
document.write (‘Hello world’);
</script>
There is not only the browser, however. Other programs have small scripts written with this language, such as Adobe Acrobat / Adobe Reader in their PDF files or Mozilla Firefox, which uses them for the user interface.
Define An Array In JavaScript
As mathematical matrices with one or more dimensions, arrays allow you to associate multiple values to a single variable name (or identifier), accessible through a numeric index starting from zero. Typically, the values in an array have some affinity (for example, the list of days of the week). The use of collections avoids defining multiple variables and makes it easier to carry out cyclic operations on all values.
An example of an array based on literal representation : var giorniDellaSettimana = [“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”, “Sunday”]; Now we can access the individual elements by referring to the variable name and the index corresponding to the component. If we want to access the first element of the array of the days of the week, we will write: var firstDay = daysOfWeek [0]; The index will scale for the other days:
var thirdDay = daysOfWeek [2];
var seventhDay = daysOf the week [6];
After the assignment, each variable will contain the string corresponding to the index. The elements of an array can be any data that JavaScript expects: var myArray = [123, “string”, true, null]; An element of an array can also be another array: var myArray = [123, “string”, [“a”, “b”, 99]]; In this case, to access element 99, we must first access the third element of the main array and then the third element of the array contained in it: var ninety-nine = myArray [2] [2];
The presence of arrays as elements of other arrays allows us to define multidimensional arrays or arrays. For example, the following is the definition of a 3×3 array of integers: var matrix = [[24, 13, 1], [48, 92, 17], [8, 56, 11]]. To access number 48, we will indicate its coordinates as follows: var forty-eight = matrix [1] [0]; The use of arrays goes well with that of objects, where with curly brackets, you can define a series of properties with a specific value labeled with a name.This is a Javascript object: Student1 = {“name”: “Michele”, “surname”: “Rossi”, “city”: “Rome”}.
Methods And Properties
We can exploit some methods and properties of any object an array is composed of. The most used is a length which indicates the number of elements it contains. Using the array: names = [“Michele”, “Sergio”, “Simona”, “Eva”, “Giorgia”, “Melania”, “Marco”] With names. Length is returned 7. To add elements at the end of the array, we can invoke names. Push (“Alessandro”), and the contents of the structure will become: [“Michele”, “Sergio”, “Simona”, “Eva”, “Giorgia”, “Melania”, “Marco”, “Alessandro”] And the length, consequently, will be equal to 8.
With names.pop (), we do two things: get the last object returned and remove it from the array. Another aspect is the possibility of transforming an array into a string: toString returns a string with all names separated by commas so that we will see ‘Michele, Sergio, Simona, Eva, Giorgia, Melania, Marco’. While nome. join (‘-‘) allows you to specify the separator with which all objects will be appended to each other: ‘Michele – Sergio – Simona – Eva – Giorgia – Melania – Marco’
forEach Loop in JavaScript and PHP
forEach is another method that allows you to apply an action to each element of an array by traversing it in descending order (from 1 to n). It is an iteration, a loop, obtained by associating a callback function that must be executed at each step. var months = [“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December “]; months.forEach (function (item, index) {console.log (‘[‘ + index + ‘]’ + item);}); Thus, the callback function takes as parameters the names of the current element (item in our case) and the current element’s index (optional).
Furthermore, the callback also takes a third parameter where it rewrites the iterating array. In PHP, each is used to cycle through each pair of keys/values of associative arrays without checking their size and will automatically take care of terminating the loop when all elements have been processed. An example that calculates the sum of the elements of an array: $ one-dimensional_array = array (1, 2, 3, 4, 5); $ sum = 0; foreach ($ one-dimensional_array as $ value) {$ sum + = $ value; } Echo “The sum of the elements of the array is: ” $ sum;
The construct after the foreach keyword includes three elements inside the round brackets: the array to be looped; the as keyword; the variable that contains the value of the current index. The code to be executed on each iteration is inside the curly brackets. For a multidimensional array, the syntax is the same with the difference that two variables are used: the variable that identifies the index of the array (in our case, the name of the user) and the variable that recognizes the value of the index ( in our case the age):
$ age_utenti = array (‘Simone’ => 29, ‘Josephine’ => 30, ‘Giuseppe’ => 23, ‘Renato’ => 26);
$ sum_ age = 0;
foreach ($ age_user as $ name => $ age)
{
Echo “The user.” $ name. ” has.” $ age. “years \ n”;
$ sum_ age + = $ age;
}
Echo “The sum of the user ages is:” $ age_sum;
The Replace Method
The replace method in JavaScript is used to simultaneously replace all occurrences of a string. An example is in which we replace JS, valued in the variable str, with the extended definition of our JavaScript language returned by a document. Write: var str = “All uses of JS methods.”; str = str.replace (‘JS’, ‘JavaScript’); document.write (str). This method is also beneficial for replacing uppercase and lowercase letters and managing them easily through a few lines of code. It is case sensitive, i.e., capable of recognizing uppercase and lowercase letters. var str = “GOOD Everyone. GOOD Everyone.”; str = str.replace (/ bravi / ig, ‘Bravi’); document.write (str).
Also Read: Object-Oriented Programming, What It Is And How It Works