Hands-On Full Stack Web Development with Aurelia
上QQ阅读APP看书,第一时间看更新

Dynamic typing

In most of the scripting languages, the type is associated with the value, not with the variable itself. What it means? JavaScript and other languages such as Python, called weakly typed, does not need to specify which kind of data we will use to store in the variable. JavaScript has many ways to ensure the correct type of an object, including duck typing.

Why duck?
Well, James Whitcomb did a humorous inference explaining the deductive thinking about it—"If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck
"

Let’s look at an example:

1.  var age = 26;
2. age = "twenty-six";
3. age = false;

In the preceding code, the defined variables accept any data type, because data types will be evaluated at runtime, so, for example, the age variable in line 1 will be an integer, will become a string in line 2 and, finally, Boolean. Sounds tricky? Don't worry, think of the variable as an empty vial without a label. You can put anything you want, cookies, milk, or salt. What you will store in the vial? Depending of your needs, if you want to make a breakfast, milk should be the better option. The only thing you must keep in mind, is remember what is containing this vial! We would hate to confuse salt with sweet.

If we need to ensure that the value belongs to some specific type, we can use the typeof operator to retrieve the data type of a given variable. Let's have a look at them:

  • typeof "Diego": This will return string
  • typeof false: This will return boolean
  • typeof "Diego" == boolean: This will return false

The typeof operator is very useful, but keep in mind it only gives primary types (number, string, boolean or object). Different from other similar operators such instanceof of Java, typeof won't return the object type.