In Javascript, strings like numbers are primitive types. (Think int, char, etc in Java.)
You can tell that this is true, by running
typeof 'my string';//results in 'string'
'my string' instanceof Object;//results in false!
Because strings are primitive types in javascript, it is safe to use the == and === operators. Just like in Java it is safe to compare integers with ==.
Like Java there are object wrapper types for the primitive types, which cannot be compared using == and ===. (Think Integer, Character, etc in Java.)
So while technically you can create a String object by running new String('my string')
, it is usually a bad idea because it can break expectations about being able to compare strings.
typeof new String('my string');//results in 'object'
new String('my string') instanceof Object;//results in true
'my string' instanceof String;//results in false
Like Java (at least Java 5 and up), Javascript has autoboxing. This allows strings to be treated as though they have properties and functions. Running 'my string'.toUpperCase()
is actually doing something more like new String('my string').toUpperCase()
.
So to summarise:
- strings are primitive types, so you can use the comparison operators
- beware of creating string objects that cannot be compared in this way
- autoboxing allows us to call functions on primitive types.