官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 东台市| 濉溪县| 手游| 新津县| 屏东县| 汽车| 出国| 和田市| 新巴尔虎左旗| 南丹县| 剑阁县| 会同县| 青川县| 青岛市| 溧阳市| 枝江市| 进贤县| 抚宁县| 甘洛县| 建德市| 福安市| 红桥区| 鲁甸县| 图们市| 西平县| 北川| 华安县| 黄浦区| 邹城市| 新田县| 永德县| 余庆县| 阿拉尔市| 内乡县| 太仓市| 孟连| 丹凤县| 达孜县| 买车| 正镶白旗| 庆元县|