Operations on Variables
Using variables in the program makes it easy for us to perform various operations on data. Different types of variables support different types of operations. For simplicity, let's consider the type integer. On this type of variable, all mathematical operations are valid.
Let's consider a code example.
1var a = 5;
2var b = 10;
3var result = a + b;
4console.log(result);
5// prints 15 in console
This code block shows that if we have two integer variables, we can add them and get the result. Similarly, other mathematical operations such as subtraction, multiplication, and division are also supported.
Now let's consider if we had a variable of type string. In this case, the operations are defined differently. Here, a +
symbol between two variables will join the two strings together. Consider the following example.
1var prefix = 'un';
2var root = 'clear';
3var word = prefix + root;
4console.log(word);
5// prints the string 'unclear' on console
Here, the two strings are joined together to produce a new string. This operation is called concatenation
. There are several other operations that we can perform on strings, integers, and other types of variables, but we will discuss them in later lessons.
Time for some practice questions!