I believe that one advantage JavaScript offers because of what you mention is easy type coercion.
As one comment implied earlier, JavaScript is loosely typed; you can declare a variable without having to declare what kind of variable it is and therefore without knowing what you're doing with it. This has simple advantages like being able to write:
var str = 'hello user #',
num = 3,
sayhello = str + num;
alert(sayhello); // alerts 'hello user #3'
Notice here how the number can simply be added to the string as if itself a string.
Therefore many operators and methods are available that perhaps wouldn't be so easy to use in a more strongly typed language. You can use the parseInt
method on an argument without having to check or convert the type of the argument first:
var returnWholeNumber = function (arg) {
return parseInt(arg, 10);
},
str = '5 is the answer',
num = 8.19437;
alert(returnWholeNumber(str)); // alerts number 5
alert(returnWholeNumber(num)); // alerts number 8
By supplying a temporary object wrapper, JavaScript saves you from having to do some conversions yourself. It simply supplies the wrapper based on what you trying to do and then discards it. As a result, JavaScript can be much more dynamic and expressive than more strongly typed languages.
This is also useful for conditionals. Some values (e.g., 0
or an empty string ''
) are what's known as falsey. That way you can do a simple boolean check on them and JavaScript will wrap the primitive data type in a Boolean wrapper.
if (!userInput) {
alert('no input');
}
However, type coercion can be confusing and requires caution:
alert('1' + 2 + 3); // alerts 123
alert('1' + '2' + '3'); // alerts 123
alert(1 + 2 + 3); // alerts 6
Also for conditionals. Use triple equals when checking type, to avoid unintended coercion:
var i = '3';
if (i == 3) { // type-coercing conditional; i can be a string or a number and this will be true
alert('i is 3'); // will successfully alert
}
if (i === 3) { // type-checking conditional; i has to be an actual number (and the value must be 3)
alert('i is a number 3'); // will not alert because i is a string
}