简体   繁体   中英

Javascript primitives

Im still new to JS, learning about objects at the moment and a little confused on primitives. on W3schools a javascript primitive is defined as:

"A primitive value is a value that has no properties or methods .

A primitive data type is data that has a primitive value.

JavaScript defines 5 types of primitive data types:

string

number

boolean

null

undefined"

per: W3Schools

but isnt a string an object and has methods such as string.prototype.indexOf() and string.prototype.toUpperCase() those are considered methods right? What am i missing?

it is actually the difference between string and String. string is primitive but String is object.

var str = "string"  //primitive
var str1 = new String("string") //object

when you apply a method to str of String object class, it is automatically converted to the object.

Auto-boxing is the process whereby the JS will convert primitive data types to their corresponding object wrapper classes. For example, string will be converted to String

It maybe because JavaScript automatically wraps those primitive values with an object. According to MDN :

Except for null and undefined, all primitive values have object equivalents that wrap around the primitive values:

  • String for the string primitive.
  • Number for the number primitive.
  • Boolean for the Boolean primitive.
  • Symbol for the Symbol primitive.

In JavaScript there are 5 primitive types: undefined, null, boolean, string and number. Everything else is an object. The primitive types boolean, string and number can be wrapped by their object counterparts. These objects are instances of the Boolean, String and Number constructors respectively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM