I have read the question and answer here:
javascript numbers- immutable
But it's not enough clear for me why the number (primitive type) are immutable? Just because they create a new reference but not overwrite the value?
If on each assignemt is created a new reference
var x = 5;
x = 1;
Would we have 100 times a new reference in the following loop?
while (x < 101)
{
x++;
}
Is that efficient? I think I am not seeing correctly.
I'm honestly not quite sure what kind of answer you expect since I don't quite understand what you are confused about. But here we go:
Would we have 100 times a new reference in the following loop?
Variables are just containers for values. At a low level a variable is basically just a label for a memory address or a register. E.g. variable x might point to register R1.
x++ would simply increment the number that is stored in that register by 1. Lets assume our register looked like this:
R1: 5
After incrementing it, which can be a single operation, such as ADD R1 1, we would get
R1: 6
I.e. we simple overwrote the previous value with a new one. And we do that multiple times.
Is that efficient? I think I am not seeing correctly.
Incrementing a number by one is as simple of an operation as it can get.
Sure, you could implement mutable numbers on a higher level, but it certainly wouldn't make things more efficient or simpler.
Mutability doesn't make much sense for "single value" values, because mutating such a value basically means replacing it with a different value "in place".
Mutability makes more sense for values that are composed of other values such as lists and dictionaries, where one part changes and the other stays the same.
Additionally, mutability only seems relevant when a language has reference type data types. With that I mean that multiple variables can hold a reference to the very same value of a data type. Objects are reference-type in JavaScript, which allows you to do this:
var a = {foo: 42};
var b = a;
b.foo = 21;
console.log(a);
If data types are not of a reference-type, called value-type, (which primitive values are in JavaScript), then mutability doesn't matter because it would be indistinguishable from immutability. Consider the following hypothetical scenario with a mutable, value-type number:
var a = MutableNumber(42);
var b = a; // creates a copy of MutableNumber(42) because it's a value type
a.add(1);
console.log(a, b); // would log 43, 42
In this scenario it is not possible for two variables to refer to the same mutable number value, a.add(1) is indistinguishable from assigning a new value to a (i.e. a = a + 1).
I could understand your question , the thing is , inside the while loop , everytime the x will point to the new value , whereas the old value will be made ready for garbage collection , so the memory is mantained still.
Read this for better understanding :
https://developer.mozilla.org/en-US/docs/Glossary/Mutable
So about the mutablity , your understanding is correct , the variable references the new value , the old value isn't changed , hence primitive values are immutable.
Refer: https://developer.mozilla.org/en-US/docs/Glossary/Primitive
Mutation is a change of state while numbers (the primitive type) are pure state objects. Any mutation to such a "object" state is actually a new number. Number itself is like an identifier of a mutation of bits in a cell of computer memory.
Therefore numbers are not mutable. Same as colors or characters.
It is also worth claryfining that a new number will ocupy the same memory cell as the old one for any given variable. Actually replacing the old one. Therefore there is no performance hit of any kind.
i dont understand entirely this,
var a=12;
a=45;
we can infer from ;
1.firstly interpreter allocate a chunk of memory and locate 12 to this area.
actually (a) is label of this memory area.
2.than, interpreter allocate a new memory cell and locate 45 to this area.
lastly (a) is associated with this new memory cell. The memory cell that contain 12 is destroyed by garbage collector.
Primitive values vs. references:
In JavaScript values of type boolean, undefined, null, number, symbol, string are primitive. When you assign them to a variable or pass them as an argument to a function, they always get copied.
In contrast objects have two parts to them: Object (it's data) is stored in one chunk of memory and what you assign to a variable is a reference pointing to that object. Object itself is not copied on assignment.
Because numbers are always copied when you assign them to a variable it is impossible to change a number and see that change through some other variable without actually assigning a new value to that variable.
In contrast when you change a field on an object, all variables pointing to that object will see that change.
Let's see some examples:
var a = 1;
var b = a; //This creates a new copy of value 1
console.log(a, b); // 1 1
a = 2;
console.log(a, b); // 2 1
var obj_a = {attr: 1};
var obj_b = obj_a; //This makes a new reference to the same object.
console.log(obj_a, obj_b); // {'attr': 1} {'attr': 1}
obj_b.attr = 2;
console.log(obj_a, obj_b); // {'attr': 2} {'attr': 2}
Immutable objects: immutable.js
Libraries like immutable.js provide types that combine properties of primitive types and objects: Types from immutable.js behave as ordinary objects as long as you don't change them. When you change a property of an immutable object, a new object is created and the change is only visible through that new object. The benefit is that you save space in memory and you can quickly check equality of objects by just comparing their references. You get a set of types that behave like integers but you can store more complex structures in them.
Related
As I know there are 4 primitives in JS (those that store value directly, rather than reference to another memory location) - String, Number, Boolean, Symbol. I am not counting undefined, null - as they are special data-types, and don't share Object-Constructor via inheritance-chain.)
Now, another property of primitives is that they are Immutable or unchanging. Their values cannot be changed. I conclude that means, for the same variable - the values should not change (ever).
Now, kindly explain to me, in the following cases - how these data-types remain unchanged?
var str = "Good Morning";
var bool = true;
var num = 29;
str = str.replace("M", "Z");
bool = !bool;
num+=5;
console.log(str, bool, num);
For same variable, I have changed all - string, bool, number. Then how these variables (of respective primitive data-types) are Immutable in JS?
You are not mutating the existing primitives. You're simply assigning new primitive values (which are immutable as well) to the existing variable names.
Mutation is not the same thing as variable name reassignment. Mutation looks something like the following:
someObj.someProp = newPropVal;
Reassignment is:
someVarName = newVal;
Primitives don't have own-properties; trying to assign to a property of a primitive doesn't do anything and will throw an error in strict mode, because primitives are immutable.
Here's one way of looking at it (it's a nice visualization, though it's necessarily an accurate reflection of what's actually happening in the bytecode): values reference a location in memory. Variable names point to locations in memory. Say that false corresponds to memory location 1234, and you create an object {} which corresponds to memory location 9999. You can assign false to a variable name and have that variable name point to location 1234 in memory. You can reassign the value that the variable name points to by using location 9999 instead, that points to the object. The object, unlike the primitive, is a potential container for other values (and other memory locations). The primitive cannot act as such a container.
your means to change primitives are only reassigning the variable's reference to the stack
var a = 1;
a = 2;
here a is a reference address to the execute stack. Above reassignment only changes the address in stack, not 1 itself. If 1 is stored in address ****, after the reassignment, 1 is still located at ****, but a now points to 2's address in stack
Values are immutable; variables are not; they hold a reference to their (primitive) values.
So:
Objects are mutable by default
Objects have unique identities and are compared by reference
Variables hold references to objects
Primitives are immutable
Primitives are compared by value, they don’t have individual identities
This is from: Understanding Javascript immutable variable
I am trying to understand what a Javascript immutable variable means. If I can do:
var x = "astring";
x = "str";
console.log(x); //logs str` , then why it is immutable?
The only answer I can think (from the little bit of C I know) is that var x is a pointer to a memory block with the value "astring", and after the 2nd statement it points to another block with the value "str". Is that the case?
And a bonus question: I was confused by the value types of Javascript. Are all variables objects under the hood? Even number and strings?
Values are immutable; variables are not; they hold a reference to their (primitive) values.
The three primitive types string, number and boolean have corresponding types whose instances are objects: String, Number, Boolean.
They are sometimes called wrapper types.
The following values are primitive:
Strings: "hello"
Numbers: 6, 3.14 (all numbers in JavaScript are floating point)
Booleans: true, false
null: usually explicitly assigned
undefined: usually the default (automatically assigned) value
All other values are objects, including wrappers for primitives.
So:
Objects are mutable by default
Objects have unique identities and are compared by reference
Variables hold references to objects
Primitives are immutable
Primitives are compared by value, they don’t have individual identities
You might find The Secret Life of JavaScript Primitives a good explanation.
Also, in ES6 there is a new const keyword, that creates a read-only named constant that cannot change value through assignment or be re-declared while the script is running.
Hope this helps!
First, in C "A string is an array of characters with last elem = '\0' ". They are mutable.
If you declare and initialize a string in C like this:
char str[] = "Foo";
What you are basically doing is reserving 4 bytes ( probably 8bit-byte, don't mind this probably if it hurts you ). The word str serves as a pointer to the first elem of this array. So, if you do like this:
str[0] or *(str) = 'G'
then it will mutate the value at that address instead of creating new array. You can verify it by printing out the address of str. In both cases it will be same.
Now in case of JavaScript string is a primitive type. All operations on string are done by value instead of by reference. So, doing this will produce true.
var str1 = "foo";
var str2 = "foo";
str1 === str2; => true
The initialization of string asks for a buffer to fit "foo" and binds the name str1 to it. What makes them immutable is that you can't change that buffer. So, you can't do this:
str1[0] = 'G'
Executing this command will produce no warning or error in non-strict mode but, it will not change the str1. You can verify it by
console.log(str1) => "foo"
But if you do like this:
str1 = "goo"
what you are actually doing is that you are asking for a new buffer to fit "goo" and bind identifier str1 to it. No change in that old buffer containing "foo".
So, what happens to "foo"?
Java Script has an automatic garbage collector. When it sees some chunk of memory that no longer can be referenced by any identifier or ... then it consider that memory free.
Same happens to number,booleans.
Now, about wrapper objects!
Whenever you try to access a property on string like this:
str1.length;
What JavaScript does it creates a new object using String class and invoke the methods on string. As soon as the function call returns, the object is destroyed.
The below code explains it further:
var str = "nature";
str.does = "nurtures"; //defining a new property;
console.log(str.does) => undefined
because the object has been destroyed.
Try this!
var str = new String("Nature");
str.does = "nurtures";
console.log(str) => ??
this str is really an object...
Conclusion: In C , in a single scope the variable name serves as a pointer. So, int, float, string all are mutable. But in Java Script a primitive type variable name serves as value not as reference
References: C++ primer plus, Java Script The Definitive Guide, C by Stephen Kochan
You are correct. Strings (and numbers) are immutable in java script (and many other languages). The variables are references to them. When you "change the value of a variable" you are changing the string (or whatever) that the variable references, not the value itself.
I think many new programmers believe immutability to mean that primitive values cannot be changed by reassignment.
var str = "testing";
var str = "testing,testing";
console.log(str); // testing, testing
var fruits = ["apple", "banana", "orange"];
fruits[0] = "mango";
console.log(fruits); //["mango", "banana", "orange"]
The values associated with both mutable and immutable types can be changed through reassignment as the above examples with strings and arrays show.
But then, these data types have associated functions(methods) that are used to manipulate the values belonging to each data type. This is where mutability/immutability is seen. Since arrays are mutable, any manipulation by an array method affects the array directly. For example,
var fruits = ["mango","banana", "orange"];
fruits.pop();
console.log(fruits) //["mango", "banana"]
The array.pop() method deleted "orange" from the original fruits array.
But with strings for example,
var name = "Donald Trump";
name.replace("Donald", "President");
console.log(name)//Donald Trump
the original string remains intact!
Immutability disallowed any altering of the original string by the string method. Instead, the method produces a new string if the method operation is assigned to a variable like so:
var name = "Donald Trump";
var newName = name.replace("Donald", "President");
console.log(newName);//President Trump
Let's understand here, first,
let firstString = "Tap";
console.log(firstString); //Output: Tap
firstString[0] = "N";
console.log(firstString) //Output: Tap
This is where we can see the immutable effect!
Immutability in this definition is historic. It's attached to what could be done in OTHER programming languages.
I think that is the first thing to understand. And to programmers who have only used JavaScript the question may seem nonsensical or needlessly pedantic. Describing primitives as immutable is like describing ice cream as not being able to jump. Why would I think it could? It is only in relation to other historic programming languages that the lack of mutability is apparent when dealing with primitive types.
This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 2 years ago.
I have a few questions about setting a variable equal to another variable in JavaScript.
Let's say we create an object, a and set b = a.
var a = {
fname: "Jon",
lname: "Smith",
age: 50
}
var b = a;
I understand that if we change one of a's properties b will also be changed because when we set b = a we don't clone a's data, but rather create a reference to a's data. For example if we set a.fname = "Sarah", the new value of b.fname will be "Sarah".
If we try to "clear" a though by setting a = {}, object b will remain unchanged. I don't understand why manipulating an object in this way produces a different result than in the 1st example.
Also I have a question about the following scenario.
var x = 10;
var z = x;
If we then set x = 20, the value of z remains unchanged. Based on the behavior described in my 1st question, one would think that the new value of z would reflect the new value of x. Could someone please explain what I am missing here?
Thank You!
The really short answer to both your questions is that when you make one variable equal to another, a COPY of what's in the first variable is made and stored in the second variable - there is no linkage between the two variables.
But, read on for more details and why it can seem like there is a link in some cases...
JavaScript, like many languages, divides data into two broad categories: value types and reference types. JavaScript value types are its primitives:
string
number
boolean
null
undefined
symbol
When you assign any of these types to a variable, the actual data is stored in that variable and if you set one variable equal to another, a copy (not a linkage) of the primitive is made and stored in the new variable:
var a = 10; // Store the actual number 10 in the a variable
var b = a; // Store a COPY of the actual number stored in a (10) in the b variable
a = 50; // Change the actual data stored in a to 50 (no change to b here)
console.log("a is: " + a); // 50
console.log("b is: " + b); // 10
When you work with reference types, something a little different happens. Assigning a variable to a reference type means that the variable only holds a reference to the memory location where the object is actually stored, not the actual object itself. So, when you do this:
var a = {foo:"bar"};
a does not actually store the object itself, it only stores the memory location for where the object can be found (i.e. 0x3C41A).
But, as far as setting another variable equal to the first goes, it still works as it did with primitives - - a copy of what's in the first variable is made and given to the second variable.
Here's an example:
// An object is instantiated in memory and a is given the address of it (for example 0x3C41A)
var a = {};
// The contents of a (the memory location of an object) is COPIED into b.
// Now, both a and b hold the same memory location of the object (0x3C41A)
var b = a;
// Regardless of whether a or b is used, the same underlying object
// will be affected:
a.foo = "test";
console.log(b.foo); // "test"
// If one of the variables takes on a new value, it won't change
// what the other variable holds:
a = "something else";
console.log("a is: ", a); // The new string primitive stored in memory
console.log("b is: ", b); // The object stored in memory location (0x3C41A)
So, in your first tests, you've simply got two ways of accessing one object and then you change what a is holding (the memory location of the object) to a different object and therefore now you only have one way left to access the original object, through b.
If we try to "clear" a through by setting a = {}, object b will remain
unchanged. I don't understand why manipulating an object in this way
produces a different result than in the 1st example.
Because now we know that a = {} isn't clearing the object. It's just pointing a at something else.
In your first case:
var a = {
fname: "Jon",
lname: "Smith",
age: 50
}
var b = a;
a = {}
b remains unchanged because this is the sequence of events happening in the background:
You create an object at memory address 0x1234 with the data
fname: "Jon",
lname: "Smith",
age: 50
A pointer to that memory block is stored ina.
Then that pointer is copied to b
At this point there are two references to the same bit of memory. Altering anything in that memory block will affect both the references to it.
a = {} doesn't clear out memory block 0x1234, but creates a new object on another memory location (0x1235) and stores a pointer to that block in a. The memory at 0x1234 remains unchanged because b is still pointing to it.
There is a difference in this sort of memory management between simple variables and objects/pointers. Strings and numbers are of the simple variety and are 'passed by value' as opposed to being 'passed by reference' for objects.
Let me try to explain:
1) In your example a and b are references to one and the same object, while a.fname (or b.fname) is an attribute of that object. So when manipulating the attribute it will be changed in the object, while the references won't be affected, they still point to the same object, the object itself has been changed. a = {} on the other hand will just replace the reference to the object without affecting the object itself or b's reference to It. It's no clearance btw you only just created a new reference to a new empty object.
2) These are not objects, so there is no reference you are directly manipulating the values. That' s because there's a difference between objects and primitives which might get confusing especially in the beginning if you're not used to working with strict types.
What is the difference between a JS:
Object, Property and Variable ?
Sorry I'm new to JavaScript but from the way I'm understanding it is a Variable is a container to store information/data types yes ?
An object is a variable but with several different properties (whereas with a variable you have one property)? name:value pairs
a property is the building blocks of objects? is that what makes an Object an Object? because it is a variable with several name:value pairs? ........
I'm supper confused!!! are all three the same are they like interchangeable?
the only example I can think of is
Human body:
Cells
Tissues
Organs
-organs are made up of tissues
-tissues are made up of cells
-cells are tissues, basically lots of cells make up tissues and lots of tissues make up organs.
So basically organs are also cells but they are made up of a lot of cells?
I'm a bit dumb and slow when it comes to learning can somebody please enlighten me?
Explain the differences between them in very simple basic language like your explaining it to a 10 year old or something please
answers much appreciated,
Thanks :)
ps There may be a part 2 to this question
the way I'm understanding it is a Variable is a container to store information/data types yes ?
Almost. A variable is a container that stores a value. Each value is of a specific data type. Common types are number, string and Boolean.
Example:
var userID = 42;
userID is a variable. It contains the value 42. 42 is a number value, i.e. it is of type number.
A JavaScript object is a value of type object. Objects are not just simple, scalar values, they are "container" values. They can themselves contain multiple different values.
Essentially objects are key-value stores, i.e. they contain one or more keys associated with a value. These key-value pairs are called properties.
Example:
var record = {
name: 'Paul',
age: 42
};
record is a variable. It contains an object as value. The object has two properties, name and age. name holds a string value, age a number value.
When one refers to 'variable' one typically imagine a container with some memory to hold a value.
Objects are variables too but dynamically transform to containers of primitives or more-complex values upon Assignment! Complex values can be objects that hold primitive data types or even other objects such in the example below :
var SNOCounter; //gives undefined ^
SNOCounter = 3;
AccObjVar = {firstName:"John", lastName:"Smith"}; //creates an JS "object" variable with two "properties" that hold 'string' type values
AccountWrapperObj = {SNO:SNOCounter,AccountName:AccObjVar};
The dynamism of object properties is such that although AccountWrapperObj which is a JS Object holds a primitive value and Object as its original value. Replacing the AccountName property with an integer can be done by just assigning it the integer value (the properties have dynamic data types just like variables in Javascript)
AccountWrapperObj.AccountName= 'Albert Einstein'; // changes the type of AccountName from AccObjVar object type to a String
----------Extra Info ---------------
^ I am not quite clear on the memory assignment part at this stage. Link says there needs to be a bare minimum memory here for referencing the variable and actually assigning it a value.
Does declaring a variable in JavaScript with var without assignment consume memory?
A variable is a binding to a value in memory and not an object.
The item in a box analogy isn’t quite right. I think that it’s more along the lines of two tin cans connected by a string, one can being the reference(variable) and the other being the value.
I'm also new to JS, so I'll tell what's helping me here
one thing that's helping me is to think about variables as 'labels', something temporary related to execution (a metaphor from Luciano Ramalho's Fluent Python book...), and not as 'boxes', a metaphor that I've seen in a lot of tutorials
so variables are temporary, and related to execution of some function, or of the whole script (depending of where they're declared... see the difference of var, let and const for more about this)
properties, on the other hand, are related to objects, attached to the obj while it or the property exists; so you cannot create a property that's not related to an obj
let myObj = {}; // 'myObj' is the 'label' of the obj we're creating
myObj.prop = true; // we create 'prop', a property of 'myObj', using the dot notation
almost everything in JS is an obj, and objs are custom types/structures for data; functions are also objects, but they're a 'special' kind of obj, we can create and return objects with them (we can execute functions to create/return objs); so
let foo; // declaring an empty variable; the word let is related to the scope of the variable, you can use var, let or const when declaring variables
foo = function(){ return {}; }; // foo returns an empty obj
myObj = foo(); // we execute foo() so that myObj is again an empty obj
the value of a property can also be an object, so we can also do
myObj.foo = function(...args){ // receives no or more arguments
const createProps = (el, i) => { // declares a variable and defines an arrow function
this[`prop${i+1}`] = el; // uses the index of the argument to create the name of the property, with the argument value
}
args.forEach(createProps); // for each arg, create a property
}
myObj.foo('some', 'new', 'properties'); // execute the function, creating new properties in 'myObj'
above, the function that creates properties for my myObj is part of myObj, as a property...
so objects and properties have to do with data structuring, how I relate the different kinds of data in my code; and functions and variables - these 'temporary labels' - have to do with execution, doin' stuff, creating objs, and so on... both 'portions' workin' together, of course
I am trying to understand what a Javascript immutable variable means. If I can do:
var x = "astring";
x = "str";
console.log(x); //logs str` , then why it is immutable?
The only answer I can think (from the little bit of C I know) is that var x is a pointer to a memory block with the value "astring", and after the 2nd statement it points to another block with the value "str". Is that the case?
And a bonus question: I was confused by the value types of Javascript. Are all variables objects under the hood? Even number and strings?
Values are immutable; variables are not; they hold a reference to their (primitive) values.
The three primitive types string, number and boolean have corresponding types whose instances are objects: String, Number, Boolean.
They are sometimes called wrapper types.
The following values are primitive:
Strings: "hello"
Numbers: 6, 3.14 (all numbers in JavaScript are floating point)
Booleans: true, false
null: usually explicitly assigned
undefined: usually the default (automatically assigned) value
All other values are objects, including wrappers for primitives.
So:
Objects are mutable by default
Objects have unique identities and are compared by reference
Variables hold references to objects
Primitives are immutable
Primitives are compared by value, they don’t have individual identities
You might find The Secret Life of JavaScript Primitives a good explanation.
Also, in ES6 there is a new const keyword, that creates a read-only named constant that cannot change value through assignment or be re-declared while the script is running.
Hope this helps!
First, in C "A string is an array of characters with last elem = '\0' ". They are mutable.
If you declare and initialize a string in C like this:
char str[] = "Foo";
What you are basically doing is reserving 4 bytes ( probably 8bit-byte, don't mind this probably if it hurts you ). The word str serves as a pointer to the first elem of this array. So, if you do like this:
str[0] or *(str) = 'G'
then it will mutate the value at that address instead of creating new array. You can verify it by printing out the address of str. In both cases it will be same.
Now in case of JavaScript string is a primitive type. All operations on string are done by value instead of by reference. So, doing this will produce true.
var str1 = "foo";
var str2 = "foo";
str1 === str2; => true
The initialization of string asks for a buffer to fit "foo" and binds the name str1 to it. What makes them immutable is that you can't change that buffer. So, you can't do this:
str1[0] = 'G'
Executing this command will produce no warning or error in non-strict mode but, it will not change the str1. You can verify it by
console.log(str1) => "foo"
But if you do like this:
str1 = "goo"
what you are actually doing is that you are asking for a new buffer to fit "goo" and bind identifier str1 to it. No change in that old buffer containing "foo".
So, what happens to "foo"?
Java Script has an automatic garbage collector. When it sees some chunk of memory that no longer can be referenced by any identifier or ... then it consider that memory free.
Same happens to number,booleans.
Now, about wrapper objects!
Whenever you try to access a property on string like this:
str1.length;
What JavaScript does it creates a new object using String class and invoke the methods on string. As soon as the function call returns, the object is destroyed.
The below code explains it further:
var str = "nature";
str.does = "nurtures"; //defining a new property;
console.log(str.does) => undefined
because the object has been destroyed.
Try this!
var str = new String("Nature");
str.does = "nurtures";
console.log(str) => ??
this str is really an object...
Conclusion: In C , in a single scope the variable name serves as a pointer. So, int, float, string all are mutable. But in Java Script a primitive type variable name serves as value not as reference
References: C++ primer plus, Java Script The Definitive Guide, C by Stephen Kochan
You are correct. Strings (and numbers) are immutable in java script (and many other languages). The variables are references to them. When you "change the value of a variable" you are changing the string (or whatever) that the variable references, not the value itself.
I think many new programmers believe immutability to mean that primitive values cannot be changed by reassignment.
var str = "testing";
var str = "testing,testing";
console.log(str); // testing, testing
var fruits = ["apple", "banana", "orange"];
fruits[0] = "mango";
console.log(fruits); //["mango", "banana", "orange"]
The values associated with both mutable and immutable types can be changed through reassignment as the above examples with strings and arrays show.
But then, these data types have associated functions(methods) that are used to manipulate the values belonging to each data type. This is where mutability/immutability is seen. Since arrays are mutable, any manipulation by an array method affects the array directly. For example,
var fruits = ["mango","banana", "orange"];
fruits.pop();
console.log(fruits) //["mango", "banana"]
The array.pop() method deleted "orange" from the original fruits array.
But with strings for example,
var name = "Donald Trump";
name.replace("Donald", "President");
console.log(name)//Donald Trump
the original string remains intact!
Immutability disallowed any altering of the original string by the string method. Instead, the method produces a new string if the method operation is assigned to a variable like so:
var name = "Donald Trump";
var newName = name.replace("Donald", "President");
console.log(newName);//President Trump
Let's understand here, first,
let firstString = "Tap";
console.log(firstString); //Output: Tap
firstString[0] = "N";
console.log(firstString) //Output: Tap
This is where we can see the immutable effect!
Immutability in this definition is historic. It's attached to what could be done in OTHER programming languages.
I think that is the first thing to understand. And to programmers who have only used JavaScript the question may seem nonsensical or needlessly pedantic. Describing primitives as immutable is like describing ice cream as not being able to jump. Why would I think it could? It is only in relation to other historic programming languages that the lack of mutability is apparent when dealing with primitive types.