Tuesday, August 28, 2012

JavaScript Basics: Types


Primary Data Types
  • Boolean
  • String
  • Number


Composite Data Types

  • Object
  • Array


Special Data Types

  • Undefined
  • Null

As you might expect, Boolean can have one of two values: true or false.

String is one or more unicode values strung together.

JavaScript does not make a distinction between integer and floating-point values. Number includes positive and negative integers and 0. Values can be represented in decimal, hexadecimal, and base 8. The special value of NaN is the result of a conversion that does not produce a meaningful number.

Undefined has a single value - undefined. If a variable has been declared but has no value or an object property that does not exists will return undefined.

The Null data type can have only one value - null. Null is used to refer to the absence of value or an object. Assigning null to a variable means that the variable holds no valid Boolean, String, Number, Object, or Array. You can assign null to a variable in the case you intend for it to have to value. Note that the typeof operator in JavaScript will report a variable with value of null to be of type Object, and not of type null. This is legacy functionality that is present for backwards compatibility.

The skinny on undefined  and null is this: If you declare a variable without assigning a value, the value of that variable is undefined. Null is explicitly assigned to designate the absence of a value or object.


var foo;
console.log( foo )// undefined
foo = null; //explicitly assign null to designate an absence of value or object assignment

The typeof operator is an introspective feature of the JavaScript language. It is useful in determining the type of a variable. A confusing caveat to typeof: Variables of type null will be come back as type object.

var myVar = "Wherever you go...";
typeof( myVar ); // prints "string"



Notes:

Chapter 8, Ecma-262

No comments:

Post a Comment