Java Basics

JavaScript: Basic Statements and Declarations


Literals

Numbers: Same as most languages, 4, 3.33333, etc.

Strings: Again similar to many languages, "Hi, How are you today?"

Boolean:

Boolean values can either be true or false. We define boolean values by declaring new Boolean().

What we put in the parenthesis, make the boolean value either true or false.

These return true:

new Boolean(true);

new Boolean("false");

new Boolean("yellow snow");

As you can see, all full strings, even the string "false", return true.

 

 

These return false:

new Boolean(false);

new Boolean();

new Boolean("");

new Boolean(null);

new Boolean(0);

 


Variables

Unlike Java and most other languages there are no declared types for local variables, class variables. While JavaScript has in some sense the notion of Objects and Classes (we will discuss next), you do not need to declare an object you simply create it as we will see later. This can be quite confusing for the experienced programmer.....and makes code (I think) hard to read.

What is even stranger is that you can change the type of data stored in a variable at any time in the code.

Instance Variables:

 

Example of creating variables.

<SCRIPT language="JavaScript">

<!--

        show_info = new Boolean(true);

        Year = "2002";

var Name = "Butch";     //instance variable

var Age = 6;     //instance variable

..........

Age ="Six Years"; //this is legal to change

.........

//-->

</SCRIPT>

 

 


Return Types

Unlike other languages there is no return type for a function (we will discuss functions later)

 


Arrays

Simply define a variable to be an array and call the built-in JavaScript class Array's constructor as follows:

var Names = new Array(3); //says there will 3 elements in the array

for(var i=0; i<Names.length; i++) //initially all names to a dummy string

Names[i] = "Unknown";


//Alternative declaration

var Names = new Array("Unknown","Unknown","Unknown");

 

 


Operators

These are basically the same as in C/C++. See your book for details.