Data Types:
JavaScript is a loosely typed language - you don't have to define what type of contents a variable can have and JavaScript automatically handles conversions between different data types. For example suppose you want to write i = 5.0 * 1. In this case, 5.0 is a real (recall your Arithmetic lessons) and 1 is an integer. JavaScript automatically handles the conversion from integer to real for multiplication. You may be surprised to know that certain languages do not allow such operations!
Although you will never define the data type of a variable in JavaScript, knowing various categories of variables is very helpful:
- Numbers: Used to represent both reals and integers. In computer science, a real is referred to as a floating point number. JavaScript allows integers to be written in decimal, octal or hexadecimal notation. A hexadecimal number starts with 0x. For example, 9A will be written as 0x9A. Similarly, an octal number starts with a leading 0. Floating point (real) numbers contain a decimal point and may also cotain an "e" or "E" to represent scientific notation. For example, 3.8 into 10 raised to the power 5 can be written as 3.8E5.
- Booleans: A boolean variable can take only two values - true and false. Unlike C++, Java and JavaScript differentiate between a 0 and a false. Boolean variables are important for evaluating conditions.
- Strings: Strings are the same as alphanumeric text. JavaScript allows you to concatenate two strings by using a plus operator. For example, you can make "Hello World" by writing "Hello" + " World".
- Undefined: A variable is said to have an undefined data type when it has been defined using a var statement but not given any values - that is, we cannot tell the data type of totalCost by seeing var totalCost.
- Objects: JavaScript has several built-in objects for you to use. To create a variable myObject to point to a built in image type, we write myObject = new image(). More on this later.
Summary:
JavaScript is a loosely typed and case sensitive scripting language. It also differs in a local and global variables. JavaScript provides automatic conversion between variables and constants of different data types and you don't declare the data type of a variable while defining it. A variable is defined by a var statement.