0
let age = 21;
let newAge = age++;
let newerAge = ++age;
let name = "basic";
let name2 = name.toUpperCase();
let name3 = name + "why";

console.log(age);
console.log(newAge);
console.log(newerAge);
console.log(age);
console.log(name);
console.log(name2);
console.log(name3);
console.log(name);

Here, changes in newAge and newerAge has changed the value of age. But from. my understanding, age(Number) is a primitive type and shouldn't have changes in its value. String, however, works as i expected. Changes in name2 and name3 haven't affected the value of name. Help me understand, Thank you

  • 1
    Does this answer your question? [++someVariable vs. someVariable++ in JavaScript](https://stackoverflow.com/questions/3469885/somevariable-vs-somevariable-in-javascript) – Ivar Dec 04 '20 at 13:22
  • 1
    `age` is not a number; it's a *variable*. It's *value* is a number, and at any time the value can be updated with another number. – Pointy Dec 04 '20 at 13:23
  • `++age / age++` is incrementing the value of `age` and this value is being assigned to `newAge` and `newerAge`...in other words: you ARE changing `age`'s value – Elmer Dantas Dec 04 '20 at 13:26
  • Try this: `const age = 21` in this way you are sure that the change you see is due to a *modification of the value* and not due to a *reassignment*. – GACy20 Dec 04 '20 at 13:27
  • `++age` simply means `age = age+1` or `age += 1`. The equivalent operation with a string, would look like `name = name + "why"` or `name += "why"`. In your string examples, you are reassigning to a new variable. If you try `name += "why"`, the `name` variable is assigned with a NEW string. – adiga Dec 04 '20 at 13:27
  • @adiga Thank you for clarifying. I understand now. thank you very very much. – Arpan Shrestha Dec 04 '20 at 13:46
  • thank you everyone. Appreciate the help. Helped me understand the core concepts even further. – Arpan Shrestha Dec 04 '20 at 13:48
  • Prefix and postifx operators are special in that regard. With any other operator, the operand can be a plain value (e.g. as a literal). But prefix and postfix operands need something that can be assigned to. `5++` is invalid (`"name" + "why"` is not). In the spec: https://www.ecma-international.org/ecma-262/11.0/#sec-postfix-increment-operator – Felix Kling Dec 04 '20 at 13:48

1 Answers1

0

The number 21 is a primitive value, but it doesn't change.

age is a variable and does get a new value assigned by the ++ operator. It's equivalent to writing

let age = 21;
let newAge = age; age = age + 1;
let newerAge = (age = age + 1); // newerAge = (age += 1)

If you don't want to mutate the age variable, don't use the ++ operator but write for example

let age = 21;
let newAge = age + 1;
let newerAge = 1 + age;

To understand what ++ does in details, see also ++someVariable vs. someVariable++ in JavaScript. It's pretty confusing for beginners, so it is recommended not to use it in assignments.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375