Chapter 2. JavaScript Data Types and Variables

Variables in JavaScript are basically named buckets of data, a way of creating a reference to that data—regardless of whether the data is a string, number, boolean, array, or other object—so that you can access the same data again and again. More importantly, you can use variables to persist data from one process to another. For instance, your JavaScript application can store the value of a form element in a variable, and manipulate that value without having to actually manipulate the form element itself.

The variable’s data type is the JavaScript scripting engine’s interpretation of the type of data that variable is currently holding. A string variable holds a string; a number variable holds a number value, and so on. However, unlike many other languages, in JavaScript, the same variable can hold different types of data, all within the same application. This is a concept known by the terms loose typing and dynamic typing, both of which mean that a JavaScript variable can hold different data types at different times depending on context.

With a loosely typed language, you don’t have to declare ahead of time that a variable will be a string or a number or a boolean, as the data type is actually determined while the application is being processed. If you start out with a string variable and then want to use it as a number, that’s perfectly fine, as long as the string actually contains something that resembles a number and not something ...

Get Learning JavaScript, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.