Javascript: String vs. Object

I looked through all the questions and answers on stackoverflow, but could not find a simple answer to this question.

What is the difference between a string and an object?

For example, if I have this code:

var a = 'Tim'; var b = new String('Tim'); 

What is the difference?

I understand that new complicates the code, and new String slows it down.

In addition, I understand that a==b is true , but more strictly a===b is false . Why?

I don't seem to understand the process of creating an object and a string. For instance:

 var a = new String ('Tim'); var b = new String ('Tim'); 

a==b false

+5
source share
3 answers

a has a type string, while b has a type object.

=== includes typechecking and the reason string is not an object a === b will give you false

new String ('Tim') === new String ('Tim') will evaluate to false too, because both are different objects

+6
source

For ordinary strings there is no need to create an object, just create your own variable and assign a value to it.

And as for your question as to why == is true and === is false, because:

== Compares values ​​=== Compares values ​​AND type (One is a string, one is an object).

One more example:

var a = 1;

var b = '1';

a == b // True, since they both have the same meaning

a === b // false, since one is a string and one is an integer

+3
source

You can do the following to see the difference:

 var a = "foo"; var b = new String("foo"); console.log(a); console.log(b); 

enter image description here

The first is a string literal , and the second is a String object. Therefore, when you compare them, they are not equal, but when you compare their values, they are. You can learn more about literals here .

+1
source

All Articles