Variable operations section: adding them is an important point in learning JavaScript, since the knowledge gained here will be used constantly.

From the previous section you already know something about variables: creating variables, displaying their values ​​on the screen and rules for working with variable names - this material is familiar to you.

Let's start performing operations on variables: addition, subtraction, multiplication and division. Let's start with the numbers.

That is, with variables whose values ​​are numbers.

// Create three variables

var apple = 20 , orange = 30 , total_fruits;

// Enter the sum of two variables into the total_fruits variable

total_fruits = apple + orange

document.write(total_fruits);

// Create three variables again

var apple = 20, price = 17, total_Sum;

// We put the product of two variables into the total_Sum variable

total_Sum = apple * price

document.write(total_Sum);

As you can see, there is nothing complicated in performing addition and multiplication operations on variables that have numerical values. The same is true with subtraction and division.

I would like to draw your attention to the fact that we have now worked with numerical values ​​of variables.

As you know from previous examples, the value of a variable can be not only a number, but also a string, that is, text or a code fragment, etc....

So the addition operation can be applied to string values ​​of variables. In this case, it is not addition in the mathematical sense of the word that occurs, but a combination of the values ​​of variables.

Let's take an example...

// Create four variables

var name = "Ivan", family = "Ivanov", otch = "Ilyich", FIO;

// We put the sum of three variables into the FIO variable, as if we were connecting their values.

// And add the tag

Which will mark a new paragraph

FIO = family + name + otch + "

document.write(FIO);

// Create three variables.

var name = "Peter", family = "Petrov", otch = "Kuzmich";

// We also enter the sum of three variables into the FIO variable. And add spaces between variables

var FIO = family + " " + name + " " + otch;

document.write(FIO);

Ivan Ivanov Ilyich

Petrov Pyotr Kuzmich

In the example above, we combined the string values ​​of three variables using the addition operation.

To prevent the last name, first name and patronymic from being merged: IvanovIvanIlyich, in the first case, spaces were inserted initially - in the value of each variable, and in the second version, spaces were added to the final FIO variable using the same addition operation.

Code fragments are added in the same way as we did in the first case: we added the tag "

" so that the next output of the FIO variable begins with a new paragraph.

Now let's try to connect a variable containing a number with a variable containing text.

var myStreet = "Dimitrova", myHouse = 121;

Listing 1.9 represents HTML code that contains two numbers (1 and 2), an operation sign (+), a form with a “Calculate” button and a text field to display the entered values. It is necessary to implement the operations of adding the corresponding values ​​(Listing 1.10).

Listing 1.9. File 1.html

  • Random phrase
  • Adding numbers


  • 1
  • 2
  • +
  • Calculate
  • The form consists of one text field for displaying values. To organize the symbols “1”, “2”, “+”, tags were used (other tags could be used, for example, or buttons), and a button was used to display the final result. The containers have an onClick event that calls the addition(…) function, passing the corresponding value (1, 2, +) to the JS script as a parameter. A button with id="ok" calls the press_button() function, which has no parameters. This function calculates and outputs the result back to the window.

    Listing 1.10. my_script.js file

  • function addition(value) (
  • document.getElementById("answer").value += value;
  • function press_button() (
  • var answer = 0;
  • var equation = document.getElementById("answer").value;
  • numbers = equation.split("+");
  • for (i in numbers)
  • if (numbers[i] != "") answer += parseInt(numbers[i]);
  • The first function in Listing 1.10 populates the form's text field with the value "1", "2", or "+", depending on which tag was clicked.

    The second function reads the value attribute value from the text field with id="answer" and assigns this value to the equation variable. This is a string that contains n characters. For example, it is possible to write ""1+2+1"" or ""1212+1121+1++2"".

    Since we know in advance that the addition operation is used, the "+" sign is used as a string separator into an array of numbers. The .split("+") function is used for this. The numbers variable contains these values.

    Now you need to go through the array and add up all the elements. For this purpose it is used for loop(i in numbers)(…) . However, there are two important points to consider when adding.

    First, the numbers array contains string values. If you use the “+” operation for string values, the elements will be merged into one string. We want to get the answer to adding numbers. Therefore, it is necessary to convert string values ​​to numeric values. To do this, use the parseInt(numbers[i]) function. An array element with number = i is passed into it.

    Secondly, the user may initially specify the wrong string. For example, ""1212+1121+1++2"". In this case, when using the .split("+") function, not only numbers will be obtained, but also empty values. Empty values ​​should be discarded. To do this, use the if (numbers[i] != "") condition.

    Finally, to calculate the results, the variable var answer was introduced, initially equal to 0. Values ​​are added to it in the loop at each iteration step. This value is then returned back to the text field document.getElementById("answer").value = answer.

    The good thing about function addition(value) and press_button() is that they can be used to add any integer. You can set all the numbers in a range in tags and handle the onClick() event. Or allow input into the text field with id="answer" and disable entering letters.

    The press_button() function (as currently written) is not suitable for handling all number operations. Because the split function splits a string by only one value.

    To implement the processing of other arithmetic operations, you can, for example, add the first two entered numbers, analyzing the sign between them. Those. without waiting for the “Calculate” button to be pressed, process the input values ​​and output an intermediate result (Listing 1.11, 1.12).

    Listing 1.11. File 1.html

  • Random phrase
  • Adding numbers


  • 1
  • 2
  • +
  • Calculate
  • Note that in this case (Listing 1.11) all values ​​are passed to the press_button() function.

    Listing 1.12. my_script.js file

  • var number = "";
  • var answer = 0;
  • function press_button(value) (
  • if (value == "1" || value == "2")
  • number += value;
  • document.getElementById("answer").value = number;
  • else if (value == "+")
  • if (number != "")
  • answer += parseInt(number);
  • number = "";
  • document.getElementById("answer").value = answer;
  • else if (value =="ok") !}
  • if (number =="") answer = document.getElementById("answer").value;
  • else answer += parseInt(number);
  • document.getElementById("answer").value = answer;
  • answer = 0;
  • number = "";
  • The press_button(value) function analyzes the passed value. If the value is a number (1 or 2), then the sequence is entered into the text field.

    If the passed value is a “+” sign, the previously entered number is added to the answer (answer += parseInt(number); ), the entered string is reset to zero: number = "";, the answer is displayed in the text field. These actions only happen if number != "", i.e. if a number was entered before entering the “+” sign.

    If the passed value is the word "ok", a comparison is made again to see if a number was previously entered. If not, then the value of the text field is not changed. If a number has been entered, then the summation occurs and the result is displayed. Since pressing the button does not involve further summation, the answer again takes the value 0.

    Good day to everyone who is reading this article. Today I will tell you in detail about addition in JavaScript. More precisely, we will discuss with you how the addition of prime numbers, string variables and arrays is performed, what is the difference between unary and binary operators, what are the priorities of operations, and also what is meant by increment and decrement.

    Let's get started!

    Let's understand the terms

    At the very beginning of this article, I want you to understand the basic terms in programming languages ​​related to calculations. Perhaps most of you have been operating with them for a long time. And that's great.

    So, it's worth knowing what terms like operand, unary and binary operator mean.

    An operand is the element to which certain operators are applied. So, for example, in the entry “15 - 38” the operator is the minus sign, and the operands are the numbers 15 and 38.

    What is a unary or binary operator? Everything is simple here too. Unary (from the word "uno", meaning "one") applies to only one element. For example, -7. In this case, the minus is a unary operator. And binary (it’s already clear what “two” means) works with two objects. Here we can use “12*701” as an example.

    “I have priorities! That’s why I don’t care about your order!”

    I am sure that everyone knows about the priorities of performing arithmetic operations. However, with the study of programming languages, other types are added to this list. There are 20 levels in total, starting from 0 to 19.

    In the table attached below, I have listed several operators in order of importance.

    If to solve a problem you need to learn about other operators, then go to the full table provided at the link.

    Increment and decrement

    Let's start by prioritizing. The most common operations in JavaScript, as in other programming languages, are those named in the title of the current chapter. They are used to decrease or increase the value of a particular element by one.

    There are two types of both increment and decrement: postfix and prefix. Moreover, the first type has priority 16, and the second - 15.

    The difference lies in the moment at which the number changes. Thus, prefix types increase or decrease the value immediately. Therefore, if the line says:

    then when you run the program, 2 will be displayed. While when using postfix operators after running the code

    1 will be displayed.

    Let's look at an example that is often given in tests or interviews. You need to say what will be displayed on the screen for the first and second outputs.

    1 2 "use strict"; 3 var i = 3; 4 i--; // short and convenient notation for i = i - 1. 5 alert(++i + i++); //i=? 6 alert(i);// i=? 7

    Now let's take a look. The fourth line indicates the decrease of i by one. The changes will take effect when the next line of the program is executed. Therefore, when alert is called, the variable i will be equal to 2.

    A prefix increment immediately increases the value by 1, while a postfix increment takes effect on the next line. As a result, we get the entry “3+3”, which means 6 will be displayed in the dialog box.

    On the next line, the increase worked and therefore displays 4.

    Something new when adding elements

    In JS you can add not only numbers, but also other types of variables: strings, etc. As an example, check out part of the program.

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

    function myFunction() ( var a=3, b=7; var str1="Hi, ", str2="friend!"; var c = a+b; var str = str1+str2; var mix = str1+a; alert(c+"\n"+str+"\n"+mix); //will display: 10 // Hi, friend! // Hi, 3 )

    In the second and third cases of addition, strings are concatenated, i.e. combining them into one. This is where problems arise for novice developers.

    Let's say you pulled out a certain value, which is a string var str1="10"; and at the same time you need to sum it with the number var a=3; . If the operation var mix = str1+ a; , then when outputting alert (mix); “103” will appear on the screen. To avoid this, the text variable must be converted as follows:

    var mix = parseInt (str1, 10)+a;. //answer: 13

    Let's move on to arrays. IN script language There is a function that combines several arrays into one. This is concat.

    var numbers1 = ; var numbers2 = ; // this results in an array; var nums = numbers1.concat(numbers2); alert(nums);

    If you need to sum all the elements of an array, then only loops will save you.

    1 2 3 4 var res=0; for (var i=0; i