Join the DZone community and get the full member experience.Join For Free
Access over 20 APIs and mobile SDKs, up to 250k transactions free with no credit card required
What is Loose Typing?
Well, this seems like a good place to start. It is important to understand both what loose typing is, and what loose typing is not. Loose typing means that variables are declared without a type. This is in contrast to strongly typed languages that require typed declarations. Consider the following examples:
var a = 13; // Number declaration
var b = "thirteen"; // String declaration
/* Java Example (strong typing) */
int a = 13; // int declaration
String b = "thirteen"; // String declaration
Ya really - Null and Undefined too.
Type coercion is a topic that is closely associated with loose typing. Since data types are managed internally, types are often converted internally as well. Understanding the rules of type coercion is extremely important. Consider the following expressions, and make sure you understand them:
7 + 7 + 7; // = 21
7 + 7 + "7"; // = 147
"7" + 7 + 7; // = 777
In the examples above, arithmetic is carried out as normal (left to right) until a String is encountered. From that point forward, all entities are converted to a String and then concatenated.
Type coercion also occurs when doing comparisons. You can, however, forbid type coercion by using the === operator. Consider these examples:
1 == true; // = true
1 === true; // = false
7 == "7"; // = true
7 === "7"; // = false;
There are methods to explicitly convert a variable's type as well, such as parseInt and parseFloat (both of which convert a String to a Number).
Double negation (!!) can also be used to cast a Number or String to a Boolean. Consider the following example:
true == !"0"; // = false
true == !!"0"; // = true
Published at DZone with permission of Jeremy Martin . See the original article here.
Opinions expressed by DZone contributors are their own.