Saturday, May 12, 2018

JavaScript


Example, 
var x = "John"
var y = new String("John");

// typeof x will return string
// typeof y will return object

Do not create strings as objects. It slows down execution speed. the new keyword complicates the code. This can produce some unexpected results:

When using the == operator, equal strings are equal:

Example

var x = "John";             
var y = new String("John");

// (x == y) is true because x and y have equal values
Try it Yourself »
When using the === operator, equal strings are not equal, because the === operator expects equality in both type and value.

Example

var x = "John";             
var y = new String("John");

// (x === y) is false because x and y have different types (string and object)
Try it Yourself »
Or even worse. Objects cannot be compared:

Example

var x = new String("John");             
var y = new String("John");

// (x == y) is false because x and y are different objects
Try it Yourself »

Example

var x = new String("John");             
var y = new String("John");

// (x === y) is false because x and y are different objects
Try it Yourself »
Note the difference between (x==y) and (x===y).
Comparing two JavaScript objects will always return false.

No comments:

Post a Comment