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

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.

主站蜘蛛池模板: 漳平市| 合阳县| 盘山县| 鞍山市| 安陆市| 麟游县| 垣曲县| 蓬安县| 西贡区| 长丰县| 万年县| 上犹县| 特克斯县| 海伦市| 秦安县| 新田县| 成武县| 祁门县| 台江县| 化州市| 太仓市| 山丹县| 南皮县| 虞城县| 平果县| 乌恰县| 佛山市| 宝丰县| 隆安县| 哈巴河县| 甘谷县| 嘉定区| 霞浦县| 瑞丽市| 北流市| 清流县| 新乡县| 娄底市| 陆河县| 塔河县| 鄱阳县|