Basic math operations on different data types in JavaScript
Tags: beginners, javascript, codenewbie, webdev
Published: 2021-02-20 14:42:16

JavaScript supports all basic arithmetic operations. In this tutorial, you'll learn how the regular `+`, `-`, `*`, and `/` perform on different data types.

<!--more-->

## Addition

You can use the binary operator `+` to add two numbers in JS. It’s called binary because it needs exactly two operands (numbers in our case) to perform the desired action.

```javascript
const sum = 2 + 2;       // 4
```

So, the result is exactly what you would expect here, but things change when we start using other data types. For example, if one of the operands is a string, then the other one will also be considered a string. Those two strings will be concatenated or "glued" together.

```javascript
const numberPlusString = 2 + '2';            // 22
const booleanPlusString = true + 'Story';    // trueStory
const stringPlusString = 'just' + 'Strings'; // justStrings
```

You can also place a regular object, an array, or a function on any side of the `+` operator. In this case, they will be first converted to a string and then the addition will be done.

```javascript
const f = () => {return 0};
const obj = {type: 'regular'};
const arr = [1, 2, 3];

console.log('Hello!' + f); // Hello!() => {return 0}
console.log(true + obj);   // true[object Object]
console.log(1 + arr);      // 11,2,3
```

Notice that most objects will be converted to strings as `[object Object]`. If you want to do something different, then you should implement a custom `toString()` function.

```javascript
const obj = {
  type: 'regular', 
  toString: function () {
  	return JSON.stringify(this);
	},
};

console.log(1 + obj);  // 1{"type":"regular"}
```

Interesting things happen when either both operands are boolean or one of them is a boolean and another one is a number. In this case `true` will always be converted to `1` and `false` will become `0`.

```javascript
const truePlusTrue = true + true;   // 2
const truePlusFalse = true + false; // 1
const booleanPlusNumber = true + 5; // 6
```

## Subtraction, multiplication, and division

Even though the rules for addition might seem quite complex, other basic operations follow common sense logic. With numbers, everything is as expected.

```javascript
const subtractionResult = 10 - 2;    // 8
const multiplicationResult = 2 * 2;  // 4
const divisionResult = 10 / 2;       // 5
```

Booleans are still converted to either `0` or `1` when on the other side is a boolean or a number.

```javascript
console.log(true / true);            // 1
console.log(5 * false);              // 0
console.log(true - false);           // 1
```

### `Infinity` and `-Infinity`

If you try to divide something by `0` or `false`, then the result is either `Infinity` or `-Infinity`.

```javascript
console.log(5 / 0);              // Infinity
console.log(-5 / false);         // -Infinity
```

### NaN

In most other cases when it’s hard to make sense of the arithmetic expression, the result will be `NaN` or "not-a-number".

```javascript
console.log(false / false);            // NaN
console.log(10 / 'string');            // NaN
console.log(5 * {});                   // NaN
console.log({} - [])                   // NaN
```

### Empty Array

An empty array is converted either to an empty string or into `0` whenever possible.

```javascript
console.log('str1' + [] + 'str2');     // str1str2
console.log(12 * []);                  // 0
console.log(5 - []);                   // 5
console.log(1 / []);                   // Infinity
```

## Unary increment and decrement

Two very useful operators allow you to either increment or decrement the value of the variable by 1. They look like double plus `++` and double minus `--`.

```javascript
let counter = 0;
counter++;
console.log(counter);                 // 1
counter--;
console.log(counter);                 // 0
```

The `++` and `--` operators can be placed on either side of the variable. Both `counter++` and `++counter` expressions are valid. The difference can be represented by these examples:

```javascript
let i = 0;
console.log(i++);                     // 0
console.log(i);                       // 1
```

So, first, we’ve taken the value of `i`, logged it into the screen, and then did the increment, which we see in the second `console.log`.

With `++i` it’s the other way around.

```javascript
let i = 0;
console.log(++i);                     // 1
console.log(i);                       // 1
```

To make sure you got this right, please answer the following question in the comments below.

```javascript
let x = 1;
let y = 2;
let z = 3;

console.log(++x - y-- + z++);         // ?
```

## Conclusion

Thank you for reading the whole article! Now you know how basic arithmetic operations work in JavaScript, their rules, and exceptions.

The `+`, `-`, `*`, `/` behave as expected with numbers, but with strings, objects, arrays, functions, and booleans it changes a lot.

[Learn Full Stack JavaScript](https://js.coderslang.com/sign-in)