Arithmetic Operators
Adam Roynon
Posted on November 26, 2019
Arithmetic operators are the easiest for new developers to understand, they relate to basic mathematics operations. There are five main arithmetic operators; addition, subtraction, multiplication, division, and modulus. These operations are used to manipulate the value of number variables, both integer and float data types. You can use these operators with variables or with plain numbers that are not stored within a variable.
Addition and Subtraction
In addition, using the plus symbol '+' adds two numbers together. subtraction, using the hyphen symbol '-' subtracts one number from another.
The below code examples show how these two operations work.
In regards to the below code, variable 'c' evaluates to the value 9 and variable 'd' evaluates to the number 3.
var a = 3;
var b = 6;
var c = a + b;
var d = b - a;
Multiplication and Division
Multiplication and division do the exact same thing as they do in normal mathematics, multiply and divide two numbers or more numbers. To multiply numbers together the asterisk '*' symbol is used, to divide numbers the forward-slash '/' symbol is used. The below code snippets show how these two operators are used.
In regards to the below code, variable 'c' evaluates to the value 12 and the variable 'd' evaluates to the number 3.
var a = 2;
var b = 6;
var c = a * b;
var d = b / a;
Modulus
The modulus operator returns the remainder after a division operation. 13 modulus 3 will return 1, this is because 13 divides by three is 3 is 4 remainder 1. The percentage symbol '%' is used to run a modulus operation on two numbers.
In regards to the below code, variable 'a' evaluates to the number 1.
var a = 13 % 1;
Multiple Operations
Just like in normal mathematics, we can use multiple operations in one equation and brackets to separate parts of the equation, as shown in the code snippet below. The variable 'a' in the below code snippet evaluates to the value 14.
var a = (3 * 4) + (12 / 6);
Addition Concatenation
Some programming languages allow us to use the addition operator to combine, or concatenate, string variables together. Concatenation is when one or more string variables are put onto the end of another string variable.
Within the below code snippet the variable 'c' evaluates the string value "Hello world". Note the use of a space in variable 'a', string concatenation does not add a space between strings for you.
var a = "hello ";
var b = "world";
var c = a + b;
This article was originally posted on my website: https://acroynon.com/
Posted on November 26, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.