Introduction
In this article we discuss about type coercion and weak typing aspects of JavaScript, then we’ll see some applications.
Background
If you use a data type JavaScript did not expect, it tries to make sense of the operation rather than report an error.
JavaScript can convert data types behind the scenes to complete an operation. This is known as type coercion. For example, a string '0' could be converted to a number 1 in the following expression: ('0' > -1). As a result, the above expression would evaluate to true.
JavaScript is said to use weak typing because the data type for a value can change. Some other languages require that you specify what data type each variable will be. They are said to use strong typing.
Type coercion can lead to unexpected values in your code (and also cause errors). So it’s necessary to know the basics to get better results working with it.
Prerequisites
Primitive Data Types
As we know there are five primitive data types in JavaScript:
JavaScript Primitive Data Types Data Type
| Purpose
|
number | Numbers |
string | Strings |
boolean | True/False |
null | Empty Values |
undefined | Variable has been declared but not yet assigned a value |
| |
| |
TRUTHY & FALSY VALUES
Due to type coercion, every value in JavaScript can be treated as if it were true or false; and this has some interesting side effects.
Falsy values are treated as if they are false. The table below shows a sample variable with a series of values, all of which are falsy.
var sample = false;
var sample = 0;
var sample = '';
var sample = 10/'some string';
var sample;
| |
| |
Truthy values are treated as if they are true. Almost everything that is not in the falsy table can be treated as if it were true.
In addition, the presence of an object or an array is usually considered truthy, too. This is commonly used when checking for the presence of an element in a page, which is called feature detection.
var sample = true;
var sample = 1;
var sample = 'string';
var sample = 10/5;
var sample = 'true';
var sample = '0';
var sample = 'false';
Applications
CHECKING EQUALITY & EXISTENCE
Because the presence of an object or array can be considered truthy, it is often used to check for the existence of an element within a page.
if(document.getElementByid('footer')){
Found: do something
}
else {
Not found: do somethinng else
}
Because of type coercion, the strict equality operators === and !== result in fewer unexpected values than == and != do.
(false == 0)
(false === 0)
(false== ' ')
(false === ' ')
(0 == ' ')
(O === ' ')
(undefined == null)
(null == false)
(undefined == false)
(null == 0)
(undefined == 0)
(undefined === null)
SHORT CIRCUIT VALUES
Logical operators are processed left to right. They short-circuit (stop) as soon as they have a result - but they return the value that stopped the processing (not necessarily true or false).
Logical operators will not always return true or false, because:
- They return the value that stopped processing.
- That va lue might have been treated as truthy or falsy although it was not a Boolean.
Programmers use this creatively (for example, to set values for variables or even create objects).
As soon as a truthy value is found, the remaining options are not checked. Therefore, experienced programmers often:
- Put the code most likely to return true first in OR operations, and false answers first in AND operations.
- Place the options requiring the most processing powe.r last, just in case another value returns true and they do not need to be run.
Examples:
On line 1, the variable artist
is given a value of artman.
On line 2, if the variable artist
has a value, then artistA
will be given the same value as artist
(because a non-empty string is truthy).
var artist = 'artman' ;
var artistA = (artist || 'Unknown') ;
If the string is empty (see below), artistA
becomes a string 'Unknown' .
var artist = ' ' ;
var artistA = (artist || 'Unknown');
You could even create an empty object if artist
does not have a value:
var artist= '';
var artistA = (artist || {}) ;
Here are three values. If any one of them is considered truthy, the code inside the if statement will execute. When the script encounters valueB
in the logical operator, it will short circuit because the number 1 is considered truthy and the subsequent code block is executed.
valueA = 0;
valueB = 1;
valueC = 2;
if ( valueA || valueB || valueC ) {
}
This technique could also be used to check for the existence of elements within a page.
Notes
- Falsy values can also be treated as the number 0 .
- Truthy va lues can also be treated as the number 1.
- A unary operator returns a result with just one operand.
- Those new to JavaScript often think the following would do the same:
if(document.getElementByld('footer') == true)
and if(document.getElementByid('footer'))
but document.getElementByld('header')
would return an object which is a truthy value but it is not equal to a Boolean value of true.
Further Reading
It is highly recommended to search for the following concepts :
- JavaScript feature detection
- JavaScript object detection
- JavaScript feature detection libraries
Feel Free to Thevelop :)
The End