JScript .NET, Part II: Major Features: Data Types - Doc JavaScript | WebReference

JScript .NET, Part II: Major Features: Data Types - Doc JavaScript

JScript .NET, Part II: Major Features

Data Types

JavaScript does not enforce any data-typing. It has a very forgiving type system. You can assign a number to a variable in one line and assign a string to the same variable on the next line. JScript .NET is identical to JavaScript in this respect: variables can be un-typed. JScript .NET is different than JavaScript in that it requires the declaration of variables (with var), while JavaScript does not. This is valid JavaScript code:

a = 4;
a = "four";

That code will not compile in JScript .NET because of the missing var declaration:

var a;
a = 4;
a = "four";

JScript .NET's support for un-typed variables makes it very easy to develop short scripts. Novice and occasional developers can focus more on the business logic, rather than being concerned with what types their variables are. The drawback to using un-typed variables is that results are not always as you expect. Let's take the following example:

var x, y, z;
x = "2";
y = 2;
z = x + y;

What do you think the value of z will be? Since we did not declare the types of x and y, the compiler casts one of them to the other. In the case above, z will be 22. The variable y is casted to String and concatenated with x.

You specify a data type by adding its name to the variable definition. Separate the variable name and its data type by a colon:

var variableName : variableDataType;

Here are some examples:

var a : int;
var b : String;
var c : char;

Think of the colon as "of type." We defined above the variable a of type int, the variable b of type String, and the variable c of type char. Notice that data types are case-sensitive. The String data type starts with a capital letter. For example, if you try string instead of String, the JScript .NET compiler (jsc.exe) will complain, and will not compile your code. We'll explain in one of our next columns why some data types start with a lower case, while other data types start with an upper case.

JScript .NET incorporates almost all the features in ECMAScript Edition 3 and many of the proposed features for ECMAScript Edition 4. In addition, JScript .NET also has many unique features that are not provided by the ECMAScript languages. Support of data types is one of these features that are not provided by ECMAScript Edition 4. Will Edition 5 include data types? Too early to say. The data types supported by JScript .NET are: boolean, byte, char, decimal, double, float, int, long, Number, sbyte, short, String, uint, ulong, and ushort. We'll cover these data types in detail in one of our next JScript .NET installments.

Next: How to define constant variables and objects

Produced by Yehuda Shiran and Tomer Shiran
All Rights Reserved. Legal Notices.
Created: April 22, 2002
Revised: April 22, 2002

URL: http://www.webreference.com/js/column108/2.html