Data Typing

JavaScript is known as a loosely typed or weakly typed language because it is pretty forgiving about the types of data being stored in variables or returned from functions. In JavaScript, you do not have to declare ahead of time whether a variable you’re creating will be holding a number, string, array, function reference, or other type of data. The language even goes out of its way at times to make variables of incompatible data types work together (although not always with the results you desire). For example, if you try to add a string and a number, the language converts the number to a string, and concatenates the two values:

// JavaScript
var a = "100";
var b = 20;
var result = a + b;
   // result == "10020"

Such conversions are not always successful. Change the operator above to division, and you get a very different result, because that operator absolutely requires two numeric operands:

// JavaScript
var a = "100";
var b = 20;
var result = a / b;
   // result == NaN

As forgiving as this system might be, it can impose a burden on the scripter to keep track of value types that are stored in variables. For example, if a JavaScript variable you create to hold an array inadvertently gets assigned a string, you will encounter a runtime error if you later attempt to invoke an array object method on that string variable.

In contrast, Objective-C (thanks to its C heritage) requires that you explicitly declare the type of data that is to be assigned to every variable, assigned to ...

Get Learning the iOS 4 SDK for JavaScript Programmers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.