Sunday, January 30, 2011

JavaScript Data Types

JavaScript is a loosely typed language. You do not have to specify data types of a variable when you declare it. Data types are converted automatically as needed during script execution.

However, this is not good coding. Lets see an example:

var a = "20"; // string
var b = 30; // number
var c = a + b;

variable c contains the string "2030" and not 50 as expected.

For this reason (and many more) you should create variables for a specific type, such as an numbers, string, or boolean, and be consistent in the values that you store in the variable.
Although loosely typed, JavaScript contains six data types:

Three primitive types:

1. Number - 64bit floating point number. JavaScript does't distinguish between Integer and fraction. Every number is ... just a number.
2. String - sequence of Unicode characters quoted using the ' or " characters.
3. Boolean - true or false.

Special values:

4. null
5. undefined

Everything else:

6. object

Note that all of them defined using "var" and can be reset dynamically:

var str = "Hello World"; // string
var num = 20; // number

// changing type
str = num;

alert(str); // output: 20


Everything else in JavaScript is an object: functions, dates, regular expressions etc.

No comments:

Post a Comment