Javascript and weakly defined types

Javascript is a weakly typed language, a variable can be equal to another if they have the same value even if they are different types.

As a result, Javascript has two equality operators;
== checks if the values of the compared objects are equal
=== checks if the values and types of the objects are equal

var fiveAsText = '5';
var fiveAsNumber = 5;

fiveAsText == fiveAsNumber // outputs true
fiveAsText === fiveAsNumber // outputs false

This can lead to some unusual behaviour when dealing with different types. For instance, when you perform mathematical operations on a string type with a numeric value

var five = '5';
var three = 3;

five + three // "53", string concatenation interprets the '5' as a string and overrides the addition operator
five - three // 2, subtraction interprets the '5' as a number

Update (28th August 2015)

A perfect example of the confusion that this can cause is as below
Javascript number/string casting

The explanation isn''t exactly intuitive but at least shows that there is some sort of logic behind it all

+ is overloaded as both the addition and string concatenation operator.

In mixed operations:

+ casts numbers to strings.

- casts strings to numbers.

Both are used to denote signage. Leading either on a string will cast it to a number, with that sign.

Pretty simple stuff, right?

Explicitly:

Number('5') - 3
'5' + (3).toString()
'5' + (5).toString()
'foo' + Number('bar').toString()
'5' + (-Number('2')).toString()
// Long ass sign flipping, same as above
Number(('5' + (3).toString())) - 3
(Number('5') - 3) + 3

The above explanation is courtesy of /u/RewindHoodie from Reddit''s /r/ProgrammerHumor


Share Tweet Send
0 Comments
Loading...
You've successfully subscribed to SimonReynolds.ie
Great! Next, complete checkout for full access to SimonReynolds.ie
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.