JavaScript/Data types

From Wikibooks, open books for an open world
Jump to navigation Jump to search




Introduction[edit | edit source]

Each variable in JavaScript has a certain data type (Number, String, Boolean, ...) - as long as a value is stored in the variable. The type of the value determines the type of the variable. In contrast to strongly typed languages, it is possible to assign - over time - values of different types to the variable so that the type of the variable may change. This is called weakly or loosely typing. The advantage is that JavaScript programmers have a wealth of possibilities and freedom to use (or abuse) variables. On the other hand, in strongly typed languages, a lot of formal errors can be detected during compile-time.

JavaScript knows seven primitive data types (Number, String, Boolean, BigInt, Symbol, Undefined, Null) and diverse other data types, which are all derived from Object (Array, Date, Error, Function, RegExp) [1] [2]. Objects contain not only a value, they also have methods and properties. The same can happen with primitive data types. If they try to invoke methods, the JS engine 'wraps' them with a corresponding object wrapper and calls its methods instead. This technique is sometimes called boxing.

You may wonder why we describe data types and initialization in the same chapter. The reason is that they are very closely related to each other. The initialization (and subsequent assignments) of a value to a variable determines its type - as noted above. That's why there is no designation of a type during initialization, in contrast to some other languages private int i = 0; /* Java */

(Note: JSON is a text-based data format, not a data type. As such, it’s language-independent. It uses the JavaScript object syntax.)

Categories of data types[edit | edit source]

Data types are explained in the following chapters.

References[edit | edit source]