What can we store in variables

We see the concept of data types for the Javascript language and why it is important to handle them well.

In it we have already talked about variables in several articles. But we still have things to see and specifically we will show in this article that we can store different types of data in a variable.

In a variable we can introduce several types of information. For example, we could enter simple text, integer or real numbers, etc. These different kinds of information are known as data types. Each one has different characteristics and uses.

Let’s see what are the most common Javascript data types.

Numbers

To start we have the numeric type, to store numbers like 9 or 23.6

Chains

The character string type stores a text. Whenever we write a string of characters we must use the quotes (“).

Booleans

We also have the boolean type, which stores information that can be true (true) or not (false).

Finally, it would be relevant to point out here that our variables can contain more complicated things, such as an object, a function, or empty (null) but we will see that later.

Actually our variables are not forced to hold a particular data type and therefore we do not specify any data type for a variable when we are declaring it. We can enter any information in a variable of any type, we can even change the content of a variable from one type to another without any problem. Let’s see this with an example.

var city_name = “Valencia” var checked = true city_name = 32 checked = “no”

See also  not found

This lightness when assigning types to variables can be an advantage at first, especially for inexperienced people, but in the long run it can be a source of errors since depending on the type of the variables they will behave in one way or another and If we do not exactly control the type of the variables, we can find ourselves adding a text to a number. Javascript will work just fine, and will return some data, but in some cases it may not be what we were expecting. Thus, although we have freedom with the types, this same freedom makes us be more attentive to possible mismatches that are difficult to detect throughout the programs. Let’s see what would happen if we added letters and numbers.

var adding1 = 23 var adding2 = “33” var sum = adding1 + adding2 document.write(sum)

This script would show us the text 2333 on the page, which does not correspond to the sum of the two numbers, but to their concatenation, one after the other.

We will see in the next article.

Loading Facebook Comments ...
Loading Disqus Comments ...