+ All Categories
Home > Documents > CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Variables.

CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Variables.

Date post: 06-Jan-2018
Category:
Upload: merilyn-gwenda-rodgers
View: 242 times
Download: 1 times
Share this document with a friend
Description:
Variable A variable is a symbolic name that represents a value that can, and likely will, change or vary during a program’s execution. Physically, it is a storage place in memory that you can access using a symbolic name that you choose when you define or declare that variable. When you declare a variable, the JS interpreter tells the computer to set aside space in memory to hold the value of your variable.
23
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Variables
Transcript
Page 1: CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Variables.

CNIT 133 Interactive Web Pags –JavaScript and AJAX

JavaScript Variables

Page 2: CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Variables.

Agenda

• My Web Site: http://fog.ccsf.edu/~hyip (download syllabus, class notes).

• Declare and initialize variables• Variable naming rules• Data types conversion• NaN and isNaN• The typeof operator

Page 3: CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Variables.

Variable• A variable is a symbolic name that represents

a value that can, and likely will, change or vary during a program’s execution. Physically, it is a storage place in memory that you can access using a symbolic name that you choose when you define or declare that variable.

• When you declare a variable, the JS interpreter tells the computer to set aside space in memory to hold the value of your variable.

Page 4: CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Variables.

Declaring Variables• In order to use a variable, you should first declare it and,

preferably, initialize it.• It is good programming practice to declare and initialize

a variable before using it in your program, JS does not require you to do so.

• To declare a variable, you simply type the special keyword var, followed by a space and the name of your variable:

var myVariable /* the value is undefined */Var num1, firstName, isOn

Page 5: CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Variables.

Initializing Variables• To initialize a variable is to assign it a default or starting

value. • The best time to initialize a variable is when you declare

it.var num1 = 37var firstName = "Tina"var isOn = falsevar num1 = 37, firstName = "Tina", isOn = false;var visitor = promopt("What \’s your name? ", "");

Page 6: CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Variables.

Variable Naming Rules• JS has a few rules for naming variables:

Only letters, numbers, and the underscore (_) are valid characters in a variable name.

Variable names may not begin with a number. They must start with a letter or an underscore (_).

Variable names may not contain spaces. Reserved words may not be used as variable names. Pre-defined object, property, method, and built-in function names are

also off limits, for example, document, window, form, name, src, isNaN, etc.

Page 7: CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Variables.

Variable Naming Rules (continue…)Rule Invalid Variable Names Valid Variable Name

No Punctuation except underscore (_)

first-namelast-name

first_namelast_name

May not begin with a number

1stName2be3rdNumber

firstName_2beNum3

No spaces allowed last name lastName

No reserved words caseclasspackage

myCaseclass2zPackage

No object, property, method, or built-in function names

documentform

theDocumentzForm

Page 8: CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Variables.

Variable Naming Rules (continue…)

• One last note about naming JS variables: JS is case sensitive.

• Thus, the names sitevisitor, SITEVISITOR, siteVisitor, SiteVisitor, are different variables.

Page 9: CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Variables.

Evaluating Expressions

• Expression evaluation is closely related to data values and variables.

• To determine the value of a variable, you have to assess, calculate, or evaluate the expression that declare it or was later assigned to it.

var num1 = 37; // num1 evaluates to 37

Page 10: CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Variables.

Undefined Variable• zVar is "undefined" because it was never declared

nor initialized. Using it results in a runtime error.

<html><head><title>Undefined Variable</title></head><body><script language= "JavaScript " type= "text/javascript">document.write(zVar);</script></body></html>

Page 11: CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Variables.

Defined variable whose value is undefined

• If an unassigned variable were formally declared using the var keyword, an evaluation of that variable would result in undefined.

<html><head><title>Undefined</title></head><body><script language="JavaScript" type="text/javascript">var zVar;document.write(zVar);</script></body></html>

Page 12: CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Variables.

Dynamically Typed• JS is a loosely typed language.• You do not have to specify the data type of a variable

when you declare it or before you use it. var guess = 37; // numberguess = "white"; // stringguess = true; // booleanguess = "pink"; // stringguess = 22; // number

• Because of this feature, Netscape describes JS as a “dynamically typed” language.

Page 13: CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Variables.

Convert from Number to String• It is also easy to convert from one data type to another.• When a JS expression involving the plus or concatenation operator

contains numbers followed by strings, JS automatically converts the numbers to string values before evaluating the expression.

var result = 7 + "up"; // result: 7upresult = "hi" + 5; // result: hi5var num1 = 85; // initialize num1 as a numeric 85num1 = num1 + ""; // num1 is a string

Page 14: CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Variables.

Convert from String to Number• JS has two built-in functions: parseInt() and parseFloat().• parseInt() parses only integers

parseInt(“3 blind mice”); // 3parseInt(“12.34 meters”); // 12parseInt(“height is 5 ft”); // NaN

• parseFloat() parses both integers and floating-point numbers.

parseFloat(“3.14 meters”); // 3.14parseFloat(“3 ft hight”); // 3parseFloat(“$72.47”); // NaN

Page 15: CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Variables.

Convert from String to Number - sample

• HTML only provides a text box, such as prompt().• Enter 10 for quantity; 9.95 for price• The result is 99.5 (ok).

<html><head><title>prompt</title></head><body><script language="JavaScript" type="text/javascript">var qty = prompt("Enter quantity", "");var price = prompt("Enter price", "");Alert("Your total is: " + qty * price);</script></body></html>

Page 16: CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Variables.

Convert from String to Number – No Conversion

• Enter 15 for first number, 22 for second number.• Sum is 1522 (wrong)

<html><head><title>Sum</title></head><body><script language="JavaScript" type="text/javascript">var num1 = prompt("Enter first number", "");var num2 = prompt("Enter second number", "");Alert("Sum is: " + (num1 + num2));</script></body></html>

Page 17: CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Variables.

Convert from String to Number – No Conversion (continue…)

• Use parseInt() or parseFloat() to fix the problem.

var num1 = parseFloat(prompt("Enter first number", ""));var num2 = parseFloat(prompt("Enter second number", ""));

OR

alert("Sum is: " + (parseFloat(num1) + parseFloat(num2)));

• Now the SUM is 37

Page 18: CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Variables.

NaN• NaN is a special keyword that indicates the value is not a

number.• Display NaN

<html><head><title>NaN</title></head><body><script language="JavaScript" type="text/javascript">var guess = "white";document.write(parseFloat(guess));</script></body></html>

Page 19: CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Variables.

NaN & isNaN()• To display message: Not a number instead of NaN• Output: Guess: NaN (No error message)

<html><head><title>NaN</title></head><body><script language= "JavaScript" type= "text/javascript" >var guess = "white";var newGuess = parseFloat(guess);document.write("Guess: ", guess, "<br>");if (newGuess == NaN) // if newGuess is equal to NaN{

document.write("It is not a number.", "<br>");}</script></body></html>

Page 20: CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Variables.

NaN & isNaN() (continue…)• isNaN() is a built-in function to see if an expression evaluates to NaN or

not.• Use isNaN() to fix the previous problem.

<html><head><title>NaN</title></head><body><script language= "JavaScript" type= "text/javascript" >var guess = "white";var newGuess = parseFloat(guess);document.write("Guess: ", guess, "<br>");if (isNaN(newGuess)) // if newGuess is equal to NaN{

document.write("It is not a number.", "<br>");}</script></body></html>

Page 21: CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Variables.

The typeof Operator• The typeof operator determines the current data type of any variable. • The result of a typeof operation are

“number”“string”“boolean”“object”“undefined”

• The syntax istypeof (operand)typeof operand

• Operand is the variable, object, object property, literal, or special keyword (null, undefined, etc) whose type you wish to know

• NOTE: the parentheses are optional, but it is considered good programming style to use them.

Page 22: CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Variables.

Possible values returned by the typeof operator

<html><head><title>Typeof </title></head><body><script language="JavaScript" type="text/javascript">var myNum = 7;var myWord = "oh, my!";var answer = false;var today = new Date();var notDefined;var noValue = "";

document.write("<b>Variable: Typeof: </b><br>" );document.write("myNum: " , typeof(myNum), "<br>" );document.write("myWord: ", typeof(myWord), "<br>");document.write("answer: ", typeof(answer), "<br>" );document.write("today: ", typeof(today), "<br>");document.write("document: ", typeof(document), "<br>");document.write("notDefined: ", typeof(notDefined), "<br>");document.write("noValue: ", typeof(noValue), "<br>");document.write("undefined: ", typeof(undefined), "<br>");document.write("null: ", typeof(null), "<br>");document.write("NaN: ", typeof(NaN), "<br>");document.write("undeclared: ", typeof(undeclared), "<br>");document.write("document.bgColor: ", typeof(document.bgColor), "<br>" );</script></body></html>

Page 23: CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Variables.

Tips avoid JS dynamic data typing1. Declare all variables before using them with the keyword

var, preferably at the beginning of your program.2. Use descriptive names when defining your variables3. Initialize all variables and try to stick to the initial data type

throughout your program. 4. Describe each variable with a brief comment when you

declare and initialize it.5. When in doubt about whether JS will convert a string to a

number for your or not, perform the conversion yourself. 6. Always convert form field entries and prompt box responses

for which you expect numeric input into numbers with parseInt() or parseFloat(), and test the result of these operations with isNaN() before performing any mathematical operations.


Recommended