WEB150 » Lecture 03: Data Types & Conditions

Update: June 3rd, 2010

Assignment - Testing Conditions

You Will Need:

1. Conditional statements (today's lesson)
2. The data type coercive (==) comparison operator
3. The prompt() method (bottom of the notes)
4. console.log()

The Task

Create a page that prompts the user for a number (using 'prompt'). Capture that number in a variable and evaluate it. Log to the console:

1. whether the number is less than 5.
2. whether the number is greater than 5.
3. whether the number is equal to 5.

Extra credit:

  • log if the input is not a number (test its type)
  • if the log is not a number, prompt the user again

Publish this page on your Assignments Page by next week's first class lecture.

Required Reading

Lecture Notes

Declaration and Assignment

In general, JavaScript (like most, if not all, scripting languages) evaluates everything right-left, inside-out. This might seem a little odd at first, but it's not so strange if you try to do the evaluation yourself.

var x = 1;
/*
breakdown:
"var": tells the interpreter to create a variable scoped to the current context (we'll talk about scope and context more later)
"x": this is the name of our variable. We can access the variable in memory based on this name.
"=": tells the interpreter to assign what is on the right of this sign to the variable name
"1": the value to assign
";": end the statement
*/

Assignment Operators

= Assign
+= Add value then assign
-= Subtract value then assign
*= Multiply value then assign
/= Divide value then assign
%= Modulus value then assign

Loose Typing

JavaScript is a loosely typed language. This means that it doesn't care what type of data you put into a variable. If you are unfamiliar with other programming languages, this won't strike you as unusual.

Typeof

Since JavaScript is loosely typed, there is a handy built-in function called typeof() that examines a variable and tells you what the data type currently is. Most of the time, you will already know what the data type of a variable is (because you probably put the value there in the first place. But sometimes, you will want to check to be sure it's what you expect:

var x;
console.log(typeof(x)); // undefined
x = true;
console.log(typeof(x)); // boolean
x = 1;
console.log(typeof(x)); // number
x = 'blah';
console.log(typeof(x)); // string
x = {};
console.log(typeof(x)); // object
x = []; // array
console.log(typeof(x)); // object (I'll explain this later)
x = function(){};
console.log(typeof(x)); // function
x = null;
console.log(typeof(x)); // object (again, later)

Boolean

Either true or false. This is represented in JavaScript as non-zero or zero, respectively. These values are used in situations of decision making. The term Boolean is named after the 19th century mathematician George Boole [1815 - 1864], who devised a mathematical means to represent logical thought. This valuable insight, in turn, has later led to innovations like telephonic switching circuits and the modern computer. This is the basic building block that all other data types are build on.

var pageReady = false;
$(document).ready(function(){
   pageReady = true;
});

Undefined

The absence of a value, or nothing. It provides a means in JavaScript to test whether a variable has a value or not or if it even exists

var x;
console.log(x); // prints undefined
console.log(typeof(x)); // prints 'undefined' (as a string)
console.log(nonExistantVar); // throws an error
console.log(typeof(nonExistantVar)==='undefined') // prints a boolean true

Numbers

Why would I rewrite what Hunlock has already written? :)

  • Only one type (floating point)
  • Operators (+-*/, etc)
  • Increment & Decrement (++ and --)
  • NaN
var x = 1;
console.log(x); // 1
x++; // increment
console.log(x); // 2
x+=2; // add
console.log(x); // 4
x--; // decrement
console.log(x); // 3
x-=2; // subtraction
console.log(x); // 1
x*=8; // multiply
console.log(x); // 8
x/=2; // divide
console.log(x); // 4
 
// modulo
x = 3;
y = x%2;
console.log(y); // 1
 
x = 4;
y = x%2;
console.log(y); // 0

Strings

quirksmode explains
Hunlock says more

  • Single and Double Quotes
  • Built-in Functions (String.length, String.replace, etc)
  • Putting Strings and Numbers Together (Concatenating)
  • Special Escape Characters
var x = "blah!";
console.log(x);
x = x.replace("!"," :)");
console.log(x);
x = "blah!\nNew Line";
console.log(x);

Arrays

An array is basically a list of variables. You can store any data type or combination of data types within an array. Arrays are one of the types of objects that we will "loop" through or "iterate" a sequence of code on.
More info by Hunlock: Mastering Javascript Arrays.

var x = [];
console.log(x);
x = [1,2,3,4];
console.log(x);
x = [1,2,"3",4];
console.log(x);

Objects

An object is a holder for any combination of variables and values, indexed by name rather than numer. Objects are also powerful constructs that allow us to create JavaScript libraries, associative arrays and much more advanced code.

var x = {};
console.log(x);
x = {
   "param1":1,
   "param2":2,
   "param3":3
};
console.log(x);

Conditional Statements

Conditional statements test if a condition is true. If so, they run the code contained within the condition. You can also create connected blocks of code that can run in alternate test cases or in the case of the test returning false.

if( n === 1 )
{
   // Execute code block #1
}
else if( n === 2 ) // only runs if the first test returns false
{
   // Execute code block #2
}
else if( n === 3 )
{
   // Execute code block #3
}
else
{
   // If all else fails, execute code block #4
}

Comparison Operators

== Equals (with data type coercion)
=== Equals (without data type coercion--truly equal)
!= Not Equal (with data type coercion)
!== Not Equal (without data type coercion--truly not equal)
> Greater than
< Less than >= Greater than or equal to
<= Less than or equal to

Multiple Conditions

You can evaluate more than one condition at a time:

if(x===3 && y===2){
   // do something
}
 
// the above is functionally the same as below:
if(x===3){
   if(y===2){
      // do something
   }
}

Logical Operators

&& AND
|| OR
! NOT

Prompt

Among many other integrated functions like 'alert', JavaScript has a build in method called 'prompt' that will use in today's assignment.

// capture user input in a prompt and assign the value to x
var x = prompt("give me a number");
console.log(x);
console.log(typeof(x)); // string
x = Number(x);
console.log(typeof(x)); // number

The return information from a prompt will also be a String. So if you want to compare this value as a number, you will either need to convert the value to a number using the Number() method or use the type coercive comparison.

No comments yet.
You must be logged in to post a comment.
TOP