Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we say that String is an object in Javascript?

I'm always confused when I hear strings are primitives in JS, because everybody knows that string has different methods like: length, indexOf, search etc.

let string = "Please locate where 'locate' occurs!";
let pos = str.lastIndexOf("locate");
let position = str.search("locate");
like image 984
Dmitry Avatar asked Sep 10 '19 15:09

Dmitry


1 Answers

It's true that everything in JavaScript is just like object because we can call methods on it. When we use new keyword with string it becomes an object otherwise it's primitive type.

console.log(typeof new String('str')); //object
console.log(typeof 'str'); //string

Now whenever we try to access any property of the string it box the the primitive value with new String()

'str'.indexOf('s')

is equivalent to

(new String(str)).indexOf('s').

The above process is called as "Boxing". "Boxing" is wrapping an object around a primitive value.

like image 142
Maheer Ali Avatar answered Nov 14 '22 20:11

Maheer Ali