Peter Aron Zentai
Peter Aron Zentai

Reputation: 11740

Any difference in " 'value' == typeof X " VS " typeof X == 'value' "

Is there any difference (compiler/interpreter/juju wise, etc) between the two versions of checking the result of the typeof operator?

I am asking because I see the first version a lot of times, as if it followed a concept, while version two is way more readable and better describes my intention: primarily I am interested in the type of a variable and not a string being equal with something.

UPDATE: while it's not part of the original question it worth noting that x == y is never a good practice when you are about to check equality. One should always use the === operator for that.

Upvotes: 2

Views: 191

Answers (2)

Sarfraz
Sarfraz

Reputation: 382696

Update

There is no difference in terms of functionality but it seems that in JavaScript, you get an error in either way (which is good, thanks to JS):

Invalid left-hand side in assignment

So it seems to be just a habit of developers from other programming languages. For example in PHP if you did:

if ($var = 'foo') 

PHP will silently assign foo as value to $var but with following:

if ('foo' = $var) 

It will throw an error.


I am asking because I see the first version a lot of times

There is no difference in what they do. However first version will throw an error if you happen to write:

'value' = typeof X

Notice = instead of == or ===

This is generally good practice, people from other languages have habit of doing it that way in JavaScript also.

Upvotes: 4

Nathan White
Nathan White

Reputation: 1080

There will be no difference, as the equivalence operation will return the same thing, regardless of which way round it is.

Upvotes: 0

Related Questions