Daavee18
Daavee18

Reputation: 74

Why does Array.length- - not subtract 1?

When I run: var a = ["a", "b", "c"] console.log(a.length--) it prints 3, but when I run: var a = ["a", "b", "c"] console.log(a.length-1) it prints 2. Why? Isn't decrementing the same as subtracting 1? Thanks in advance.

Upvotes: 0

Views: 435

Answers (4)

Dominik Januvka
Dominik Januvka

Reputation: 39

Actually, decrement operator will not decrement returning value of length, it will mutate (pop) array (and then return length value of mutated array)

the position of (--) operator says when the computing will be made, it means:

  • when in front: array will .pop() -erase last value- and then return length of array
  • when at end: it returns length of array and then array will .pop() - erase last value

see example

var c = [1,2,3,4,5]; 
console.log(c.length--); // will return length od array (5), then pop()
console.log(c);
// now reversed
console.log(--c.length);  // will pop(),then return length od array (3)
console.log(c);

Upvotes: 0

traktor
traktor

Reputation: 19301

It does subtract one from the length but the code posted doesn't attempt to observe the result: an array of length 2.

var a = ["a", "b", "c"];
console.log(a.length--)
console.log(a);

Upvotes: 1

Nati Reitblat
Nati Reitblat

Reputation: 35

In Java script you have 2 different shortcuts to subtract an int by one. The first is the one you use here: val-- and the second is --val. If you use any of them alone meaning you have a line that contains only val-- and thats it they do the same thing(subtract by one) but if you use them with something else(for example console.log) they have different effects. If you use val-- the program will log the val first and then subtract by one. But if you use the --val it will first subtract by one and then log the new value.

Code that showcases this:

Var a = 3;
Var b = 3;

Console.log(a--);
//will print 3
Console.log(--b);
//will print 2

Console.log(a);
//prints 2
Console.log(b)
//prints 2

In other words what val-- does is it subtracts by one starting from the next line

Upvotes: 0

Alexandre Elshobokshy
Alexandre Elshobokshy

Reputation: 10922

The decrement operator (--) decrements (subtracts one from) its operand and returns a value.

If used postfix, with operator after operand (for example, x--), the decrement operator decrements and returns the value before decrementing.

If used prefix, with operator before operand (for example, --x), the decrement operator decrements and returns the value after decrementing.

let x = 3;
const y = x--;

console.log(`x:${x}, y:${y}`);
// expected output: "x:2, y:3"

let a = 3;
const b = --a;

console.log(`a:${a}, b:${b}`);
// expected output: "a:2, b:2"

Upvotes: 1

Related Questions