Elements
2. Language elements:
A. The data
You have previously made a first approximation to the basic elements with which you are going to face when programming. It is time to deepen something else in these elements and we will start by the most elementary: the data. JavaScript handles four types of data: numerical, string, booleans and pointers. The numerical data serve to handle any real number, such as 12, 56.5, -9.
The string data is those used for alphanumeric strings, that is, to represent words, so the following are string data: 'test', 'The key is 4R5T'. Note that this data is waxed in quotes (double or simple, both options are allowed), it is the way to tell JavaScript that is before a character string and not before a name or descriptor of some element of the program. That is, '41' (or "41") is a string data while 41 is number forty-one. And what happens if I want the string to have quotes?, For example, we want to write the next phrase John alias 'machi ' is the boss, in javascript this is a string and should be closed in quotes John alias 'maqui' is the boss, the interpretation of this string would give a mistake as you can check if you write the following instruction in the script window:
logger.warn('John alias 'Maqui' id the boss'); // Error
Why? Well because there are two strings and a name in between: 'John alias', Maqui and 'is the boss'. JavaScript will try to find a variable with the name Maqui. In order to do this correctly, the exhaust character is used: \, which follows this inverted bar is a special character that should be interpreted as a normal character, try this now:
logger.warn('Juan alias \'Maqui\' es el jefe');
Alternatively, we can combine simple and double quotes to get the same result:
logger.warn("Juan alias 'Maqui' es el jefe");
Now it works perfectly. There are more special characters such as tabs, writing line changes, left erase, the inverted bar itself. You can try them with the Logger technique:
logger.warn('This uses an \t tabulation');
logger.warn('This uses a \n line change');
logger.warn('This uses a \r carriage return');
logger.warn('This is the inverted bar \\');
These data are quite common even in everyday life, but there are more types of data as sure you know. For example, if you ask someone, are it five o'clock? There are only two possible answers: Yes or no. This type of data is neither numerical or chain, is Boolean. In programming languages instead of the values true or false are not used. These data are the ones you used when decisions have to be made in the programs, that is, check something and act accordingly: if a fire variable is to deactivate the elevators, for example.
There is a last type of data that is also often used in the scripts for the capture of events, are memory addresses, or pointers, used to assign functions. If the name of a function is saved in a variable that variable is convert in another name for that function.
B. Variables.
We already said that the data, the numerical values can not always be used directly, but usually stored in a named memory position, this is what we call a variable. In other programming languages there are different types of variables depending on the type of data that can save: Variables for strings, for whole numbers, for real numbers, etc. JavaScript is very permissive in this aspect so that a variable can save any type of data and can also be created anywhere in the program. The latter is comfortable but dangerous because it can lead to difficult to debug programs and modify, it is convenient to bring a certain control over the variables you are using in each function and declare them at the beginning of it.
We have said that the variables have names, how are these names? It is worth any combination of letters and digits, but the low script, as long as the first character is not a number and of course not coinciding with a reserved word of language, that is, words with a special meaning for the interpreter as close, open , Write ... It is advisable to use self-explanatory names, it is a way to document your programs. For example, a variable to save a Modbus memory address of a device can be called Dire_ModBus. A last javascript detail difference between cannum and tiny, thus age and age would be two different variables.
Another aspect to keep in mind when using the variables is your scope, that is, what functions have access to them. If a variable is created within a function it will be known within that function, it is about local variables. If several functions are needed to have access to a given variable, it must be created as global variable, this is done with the help of the function GlobalData see section Complete examples
function LightOfficeStatus() {
let light_status;
light_status = devices.read('Office', 'Light');
return light_status;
}
In this example the variable light_status is local to function LightOfficeStatu(). Notes that the variables are created with the keyword Let. Another detail to keep in mind is that at the same time we create the variable we can give it a value, if we do not, the variable will contain the null value.
C. The objects
JavaScript has some predefined objects or intrinsic objects such as: array, boolean, date, function, global, math, nomber, object, regexp, and string. In addition, the programmer can create new objects, with their own methods and properties, adapted to the specific needs of their application.
Create a new object is as simple as you define which your properties will be and your methods, bearing in mind that any object that we define already has inherited the methods and properties of the predefined object object. In the following example we create an object probe that will clarify how to create its own objects:
function probe(Temperature, Humidity, Battery) {
this.temperature = temperature;
this.humidity = humidity;
this.battery = battery;
this.length = 3;
}
let myProbe = new probe(25, 96, 100);
let newProbe = new probe(20, 99, 75);
This object is created with the operator new passing as arguments the declared properties for this object: Temperature, Hummity, Bateria. The keyword this is used to refer to the object itself that we are defining. Even more we can create New properties only for the variable myProbe, but these properties will not affect the object probe itself. For instance:
myProbe.other = 'Object defined by me';
logger.warn(myProbe.other);
It results in Objeto defined by me, but if we were now writing:
logger.warn(newProve.other);
We would get undefined because other is only a property of the variable myProbe not the object newProbe. To expand an object we use prototipe property:
probe.prototype.other = 'Object defined by me';
logger.warn(newProbe.other);
logger.warn(myProbe.other);
Now we have added a property to the object probe and this property is transmitted to the type probe variables (more correctly instances of probe), therefore in Both cases we would obtain the phrase Object defined by me, which is the value given to the New property.
D. The Arrays
Despite its strange name the arrays are nothing more than structures to store values lists. Unlike other languages, in JavaScript the arrays are not a type of variable but were implemented by Netscape as an object, which gives them a huge power. But let's start down.
An array can be seen as a name where we can annotate things, each annotation is identified by its order number in the array (the list), its index, and the total number of spaces to annotate things in the array is its length. If in an array we have written 5 numbers, the first of all will be the index 0 and the last one will have as an index the 4, being 5 length of the array. Simple, right? Let's see how an array is created and as values are assigned in some very simple examples:
week = new Array(7);
myList = new Array(1,5,9);
names= new Array('John', 'Lewis', 'Mery');
empty = new Array();
interesting = new Array(4);
The Week array has been created with length 7, that is, it allows 7 elements. The array. myList has been created with length 3 and value has been given to each element as well as the Array names. Finally, the empty array has been created without length.
week[0] = 'Monday';
week[1] = 'Tuesday';
week[2] = 'Wednesday';
week[3] = 'Thursday' ;
week[4] = 'Friday';
week[5] = 'Saturday';
week[6] = 'Sunday' ;
empty[5] = 'last';
interesting['John'] = 10;
interesting['Pillar'] = 5;
interesting['Antonio'] = 8;
In this last segment of code we have filled the arrays: Week has been filled with the names of the days of the week. Observe the empty array empty, we have given value to the element 5, from now on, this array has length 6 with the first five elements with null value and the sixth (vacuum [5]) with value 'ultimate'. Finally the array called interesting, and it is: Indexes do not have to be numerical.
Each element of an array can be a value of any type: numbers, strings ... or other array, in this last case we will have multidimensional arrays, that is, where each element has several indexes or coordinates to locate them. A mess? We see the simplest case, a two-dimensional array would be an array where each element is in turn another array with which each element will have two indexes one for the first array and another for the second. The two-dimensional array podge imagine it as a table ordered in rows and columns, each element of the array is a cell of that table. An example for a 3-row table and 2 columns:
function matBidim() {
let table = new Array(3);
table[0] = new Array(2);
table[0][0] = 10;
table[0][1] = 5;
table[1] = new Array(2);
table[1][0] = 7;
table[1][1] = 8;
table[2] = new Array(2);
table[2][0] = 9;
table[2][1] = 3;
logger.warn(table[1][1]); /*Visitialize in the Log number 8*/
}
As you see the thing is simple: the array table has three elements and each of them is in turn another array of two elements.
E. The functions
The functions as we said in the introduction, are nothing but blocks of program instructions with name and that can be executed without more than calling them from some part of another function, either directly or through events.
Usually a function is created to execute a very specific action. JavaScript has a series of predefined functions or global functions but the programmer can create their own. To create a function, it is only necessary to indicate it to the interpreter through the keyboat function followed by the name that we want to give to the function and, enrolled in parentheses, the variables that symbolize the values with which the function should work, The arguments. Parenthesis should be written even if there are no arguments. For the function names we follow the same rules as for the variables: charaters, digits and low script, should begin with a low character or script.
As is natural, it is advisable to give the functions a representative name of the operation it performs. Of course we should not give you a name that already exists in JavaScript. Then enclosed between keys, we write the sentences or orders in JavaScript. Optionally, the function can end with the keyword return followed by a value, this value will be the one that returns the function to the program that call it. For instance:
function add(a, b) {
let sum;
sum = a + b;
return sum;
}
Through this example we create the function called add, which uses two arguments and what it does is add these arguments. Finally, it returns the result of the operation, using the keyword return followed by the value you must return. Now in the following program code we use the newly defined function:
let operation;
operation = add(4, 5);
logger.warn(operation);
In this code we call the function with the arguments 4 and 5 and store the result in the variable operation. So far the behavior of JavaScript functions is similar to any other language, but in JavaScript the functions are also objects. Let's see the following example:
let multip = new Function('x', 'y', 'return x * y')
logger.warn(multip(8, 9));
Interesting, now multip is not any variable but an instance of the object function and can be used as the function itself. This feature allows you to directly assign functions to the events and thus simplify your programming.