Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: String vs. Object [duplicate]

I've looked all the questions and answers on stackoverflow, but couldn't find the simple answer to this.

What is exactly the difference between string and object?

For example, if I have this code:

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

What exactly is the difference?

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

Also, I understand a==b is true, but going more strictly a===b is false. Why?

I seem to fail to understand the process behind the object and string creation. For example:

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

a==b is false

like image 933
super11 Avatar asked May 11 '16 08:05

super11


2 Answers

a is of type string, whereas b is of type object.

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

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

like image 141
chresse Avatar answered Oct 08 '22 04:10

chresse


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

And as far as your question regarding why == is true and === is false it's because:

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

Another example of this is:

var a = 1;

var b = '1';

a == b //True as they both have the same value

a === b //false as one is a string and one is an integer

like image 36
Jamie Livingstone Avatar answered Oct 08 '22 05:10

Jamie Livingstone