View
212
Download
0
Embed Size (px)
Citation preview
Friday, Week 2
Variables!What’s a variable???How do I use them in JavaScript???What are they good for???Some examples…Mini-Lab 2!!!
Variables in JavaScript
We use the var keyword to create or declare a variable:
var num, num2;
num num2
Variables in JavaScript
We use the = sign to assign a value to a variable (put it in the box)
num = 3;
num num2
3
Variables in JavaScript
When we use a variable name, we get the value it contains:
num2 = num + 13;
num num2
3 + 13 = 16
What are Variables Good For?
Storing temporary information:Compare:
// swap a and b a = b; b = a;
// swap a and b var temp = a; a = b; b = temp;
What are Variables Good For?
Storing shared informationOften, we want to have some information that several functions can useWe can create a global variable that is outside any functionNow, all the functions in that document can “see” the global variable!
What are Variables Good For?
Storing information from a user of a web page:var userName = document.guestbook.nameTextfield.val
ue;
Important Notes
Variable names in JavaScript are case sensitive – the case matters!
So, num and Num are different variable names!
Variable names must begin with a letter, and can have only letters, digits, and/or the underscore (_) – no spaces!.
OK – num, num2, cs105, my_numNot OK – 1num, money$, cs 105
Important Notes
Choose descriptive variable names:Helps you remember what is in the variable.Helps the grader read your code (hint, hint!).
Variables are declared with the var keyword
Variable declarations can be at the very beginning of a function (local variables), or outside all functions (global variables).You do not need to type var when you use a variable – just use the variable’s name!
Some Examples
function doSomething(){
var sum, numberValues, average;… //compute sum and numberValuesaverage = sum / numberValues;
}
Some Examples
function wholeName(){
var first, last, whole;first = “Jason”;last = “Atkins”;whole = first + last;
}
Some Examples
function wholeName(){
var first, last, whole;first = “Jason”;last = “Atkins”;whole = first + last;
}Problem: whole now has “JasonAtkins”
Some Examples
function wholeName(){
var first, last, whole;first = “Jason”;last = “Atkins”;whole = first + “ “ + last;
}Ok, better: whole now has “Jason Atkins”
Some Examples
function wholeName(){
var first, last, whole;first = document.guestbook.firstName.value;last = document.guestbook.lastName.value;whole = “Hello, “ + first + “ “ + last + “, how are you today?”;alert (whole);
}