1

Learning about string and number immutability

If string is 'effectively' an immutable array of characters ['B', 'o', 'b'] then is this true for number data type?

Cannot seem to access the first digit 1 with console.log(immutableNumber[0]); as I did above with the string data type above.

var immutableString = "Bob"; // string 'effectively' an immutable array of characters ['B', 'o', 'b']
immutableString[0] = "Job";
console.log(immutableString[0]); // B
console.log(immutableString); // Bob

var reassignedString = "Bob";
reassignedString = "Job";
console.log(reassignedString); // Job

var immutableNumber = 123456; // is number 'effectively' an immutable array of characters? ['1', '2', '3', '4', '5', '6']
immutableNumber[0] = "7890";
console.log(immutableNumber[0]); // undefined - why not 1? 
console.log(immutableNumber); //123456

var reassignedNumber = "123456";
reassignedNumber = "789101";
console.log(reassignedNumber); // 789101

Can I ask is there a guide for how JS treats the different primitives?

1
  • "then is this true for number data type?" No. Commented Jan 23, 2020 at 15:08

1 Answer 1

3

In JavaScript, Number is a numeric data type in the double-precision 64-bit floating point format (IEEE 754).

The number data type is different and while there are certain methods you can use on a number type you simply can't access the individual digits like you would on a String.

Sign up to request clarification or add additional context in comments.

4 Comments

Can I ask is there a guide for how JS treats the different primitives?
@user1554264 Asking for off-site resources is off-topic on SO.
Ah okay, understood sorry.
@user1554264 It's not like strings are actual arrays, they are array-like in JS and you can do certain things like using the array accessor notation to get a letter out of the string, but they don't have a lot of the features that arrays in JS have. It's not really relevant to look for a guide on how JS treats different primitive types. I would just advise you to get familiar with those types and read as much as you can about them on MDN or something to know what you can do with them. Although if we're talking about comparison between types that's a whole other topic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.