In JavaScript, a primitive is data that is not an object, and has no methods or props, such as:
- null
- undefined
- number
- string
- bigint
- boolean
There is a fundamental difference between primitive values and objects. Well first primitives are immutable: there is no way to change a primitive value. This is obvious for numbers and booleans. It is not so obvious for strings, however.
Since strings are like arrays of characters, you might expect to be able to alter the character at any specified index. In fact, JavaScript does not allow this, and all string methods that appear to return a modified string are, in fact, returning a new string value. For example:
let str = "hello world"
str.toUpperCase() // "HELLO WORLD"
str // "hello world" - the official is not modified
Primitives are also compared by value: two values are the same only if they have the same value.
Again this sounds fair for numbers, booleans, null and undefined because there is no other way to compare them. But again this is not so obvious for strings. If you compare two string values, JavaScript treats them as equal if, and only of, they have the same length and if the char at each index is the same.
Top comments (0)