Search code examples
javascriptstringnumbersprimitive

Since number is a primitive type, why is it changing its value when reassigned to another variable?


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


Solution

  • 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.