mdn / content

The content behind MDN Web Docs
https://developer.mozilla.org
Other
9.2k stars 22.48k forks source link

Explain autoboxing of JS primitives #15744

Closed dblachut-adb closed 2 years ago

dblachut-adb commented 2 years ago

MDN URL

https://developer.mozilla.org/en-US/docs/Glossary/Primitive

What specific section or headline is this issue about?

Description in first apostrophe.

What information was incorrect, unhelpful, or incomplete?

has no methods.

What did you expect to see?

but can have methods.

Do you have any supporting links, references, or citations?

x = 2.1
typeof x // "number"
x.toFixed() // "2"

Do you have anything more you want to share?

I was surprised to discover that the primitive values can have methods and the only thing that differs them from "objects" is the immutability and disability to add new methods to them.

It seems that this article on MDN have an issue, on the other hand the description in other article seems OK: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#primitive_values

Some of the primitives have disability to call the methods directly and must be assigned to some variable. E.g.

"test".toUpperCase()
2.0.toExponential()

works, but the following does not:

2.toExponential() // Uncaught SyntaxError: identifier starts immediately after numeric literal

MDN metadata

Page report details * Folder: `en-us/glossary/primitive` * MDN URL: https://developer.mozilla.org/en-US/docs/Glossary/Primitive * GitHub URL: https://github.com/mdn/content/blob/main/files/en-us/glossary/primitive/index.md * Last commit: https://github.com/mdn/content/commit/d2a9f2e26a8139d4bb270d7dc3cddd8b848719fe * Document last modified: 2022-02-18T09:06:52.000Z
Elchi3 commented 2 years ago

Thanks for your issue! I think the MDN pages should explain better what "autoboxing" is.

https://dev.to/benjaminmock/do-you-know-what-autoboxing-in-js-is-enl

dblachut-adb commented 2 years ago

Oh, thanks for posting that, so I guess I was wrong with my assumption and the autoboxing kicks off in such situations!

dblachut-adb commented 2 years ago

Looks like primitives can't have methods after all, I think I will close the issue. JS may get really confusing sometimes... :smiley:

Elchi3 commented 2 years ago

It can get confusing and we should update the docs to talk about autoboxing. Reopening this :)

hamishwillee commented 2 years ago

@Elchi3 You learn something new every day :-). Decided to fix this one for that reason #15806

Elchi3 commented 2 years ago

@hamishwillee thank you so much! Well done!