JavaScript Variables and Data Manipulation, Slides of Artificial Intelligence

A part of the lecture notes for csci 100 'think like computers' course, fall 2008. It covers the basics of javascript variables, memory cells, and data manipulation. How to declare and assign variables, store values in memory cells, and reuse variables. It also discusses the use of prompts with defaults and localizing changes using variables. Additionally, it touches upon the importance of converting strings to numbers using parsefloat function.

Typology: Slides

2012/2013

Uploaded on 04/24/2013

banani
banani 🇮🇳

4.3

(3)

91 documents

1 / 5

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
CSCI 100
Think Like Computers
Lecture 15
Fall 2008
Last Time …
JavaScript: THE scripting tool for
webpages
For creating dynamic HTML webpages
(DHTML)
JavaScript Overview
<script type=“text/javascript>
……. // script code here
</script>
<body onUnload=“alert(‘Thanks for visiting!’);” >
Variables
VARIABLE = prompt("PROMPT MESSAGE", "") ;
firstName = prompt("Please enter your name", "");
Write to the web page:
document.write("MESSAGE TO BE DISPLAYED " + VARIABLE + "
MORE MESSAGE" + ...);
document.write("Hello " + firstName + ", welcome to my Web page. ");
Formatted Output
the output produced by a write statement is embedded in
the page
the browser displays this output just as it does any other text
if the text contains HTML tags, the browser will interpret the tags and format the
text accordingly
document.write("Hello <i>" + firstName +
"</i>, welcome to my Web page.");
assuming the variable firstName has been assigned "Dave", the browser
would execute the statement to produce
Hello <i>Dave</i>, welcome to my Web p age.
which would be displayed by the browser as
Hello Dave, welcome to my Web page.
Syntax Errors
an error in the format of an HTML or JavaScript
statements is known as a syntax error
some syntax errors are ignored by the browser
e.g., misspelling an HTML tag name
most JavaScript syntax errors will generate an error message
document.write("This example is illegal since the
string is broken across lines");
yields: Error: unterminated string literal
document.write("The value of x is " x);
yields: Error: missing ) after argument list
JavaScript Variables
a variable name can be any sequence of letters, digits, and underscor es
(but must start with a letter)
valid: tempInFahr SUM current_age Sum2Date x
invalid: 2hotforU salary$ two words "sum_to_date"
variable names are case sensitive, so Sum and SUM are treated a s different
variables
Docsity.com
pf3
pf4
pf5

Partial preview of the text

Download JavaScript Variables and Data Manipulation and more Slides Artificial Intelligence in PDF only on Docsity!

CSCI 100

Think Like Computers

Lecture 15

Fall 2008

Last Time …

• JavaScript: THE scripting tool for

webpages

• For creating dynamic HTML webpages

(DHTML)

JavaScript Overview

  • Variables Š VARIABLE = prompt("PROMPT MESSAGE", ""); Š firstName = prompt("Please enter your name", "");

  • Write to the web page: Š document.write("MESSAGE TO BE DISPLAYED " + VARIABLE + " MORE MESSAGE" + ...); Š document.write("Hello " + firstName + ", welcome to my Web page.");

Formatted Output

  • the output produced by a write statement is embedded in

the page

Š the browser displays this output just as it does any other text Š if the text contains HTML tags, the browser will interpret the tags and format the text accordingly

document.write("Hello " + firstName + ", welcome to my Web page.");

assuming the variable firstName has been assigned "Dave", the browser would execute the statement to produce Hello Dave, welcome to my Web page.

which would be displayed by the browser as Hello Dave , welcome to my Web page.

Syntax Errors

  • an error in the format of an HTML or JavaScript

statements is known as a syntax error

Š some syntax errors are ignored by the browser ƒ e.g., misspelling an HTML tag name Š most JavaScript syntax errors will generate an error message document.write("This example is illegal since the string is broken across lines");

yields: Error: unterminated string literal

document.write("The value of x is " x);

yields: Error: missing ) after argument list

JavaScript Variables

  • a variable name can be any sequence of letters, digits, and underscores (but must start with a letter)

Š valid: tempInFahr SUM current_age Sum2Date x Š invalid: 2hotforU salary$ two words "sum_to_date"

  • variable names are case sensitive, so Sum and SUM are treated as different variables

Variables & Memory Cells

  • computers keep track of the values that variables represent by associating each variable with a specific piece of memory, known as a memory cell

Š when a JavaScript assignment is executed,

firstName = prompt("Please enter your name", "");

Š the value entered by the user (e.g., "Dave") is stored in a memory cell associated with the variable firstName

  • "Dave"
  • firstName

Š any future reference to the variable name evaluates to the value stored in its associated memory cell

Reusing Variables

  • food = prompt("What is your favorite

food?", "");

  • document.write("Your favorite food is " +

food + "");

the first pair of statements

  • stores the user's favorite food
  • displays that food in the page

Reusing Variables (cont.)

  • food = prompt("What is your least favorite food?", "");
  • document.write("Your least favorite food is " + food + "");

the second pair of statements

  • stores the user's least favorite food (overwriting the old value)
  • displays that food in the page

Prompts with Defaults

  • so far, all prompts have been of the form

VARIABLE = prompt("PROMPT MESSAGE", "");

  • sometimes it makes sense to provide default values for prompts Š can specify a string literal instead of "" Š this string will appear in the prompt box when it appears ƒ if the user wants to accept the default value, can just click OK
  • EXAMPLE: suppose we wanted to create a page that displays a verse of the children's song, Old MacDonald had a Farm Š the page should be able to display any verse Š can accomplish this by prompting the user for the animal and sound Š can specify default values so that it is easy to display a common verse

animal = prompt("Enter a kind of animal:", "cow"); sound = prompt("What kind of sound does it make?", "moo");

Old MacDonald Localizing Changes

• so far, we have used variables to store values

read in via prompts

• another common use is to store values used

repeatedly in a page

Š suppose we wanted to change the spelling of the

refrain in Old MacDonald

("E-I-E-I-O" Æ "Eeyigh-Eeyigh-Oh")

Š as is, would need to find and update all occurrences

in the verse

Temperature Conversion Conversion Page

  • note that the prompt has a default value of 32

Common Pattern

  • many tasks that we will consider have the same basic

form

  1. prompt the user for numbers
  2. store them in variables
  3. perform some calculation(s) using those numbers
  4. display the results
  • not surprisingly, there is a pattern to the code

Predefined Functions

  • JavaScript provides an extensive library of predefined

mathematical functions

Š Math.sqrt returns the square root of a number

e.g., Math.sqrt(9) Æ 3

Š Math.max returns the maximum of two numbers

e.g., Math.max(3.2, 1.8) Æ 3.

Tester Other Useful Functions

• Math.pow raises a number to a power

Math.pow(2, 10) Æ 210 = 1024 Math.pow(2, -1) Æ 2 -1^ = 0. Math.pow(9, 0.5) Æ 9 0.5^ = 3

• Math.random generates a random number in the

range [0…1)

Š note: this function has no inputs; it returns a different number each call

Math.random() Æ 0. Math.random() Æ 0. Math.random() Æ 0.

Errors and Debugging

  • in computer jargon, the term bug refers to an error in a

program

Š the process of systematically locating and fixing errors

is debugging

Errors and Debugging

  • three types of errors can occur 1. syntax errors: typographic errors ƒ e.g., omitting a quote or misspelling a function name ƒ since the browser catches these, they are usually "easy" to identify and fix 2. run-time errors: occur when operations are applied to illegal values ƒ e.g., attempting to multiply a string or divide by zero ƒ also caught by the browser, which either produces an error message or else returns a special value (string multiplication produces NaN, for "Not a Number"; division by zero produces Infinity) 3. logic errors: flaws in the design or implementation of a program ƒ whenever your program produces the wrong result ƒ since they are not caught by the browser (the program is legal, just not what you wanted), logic errors are hardest to identify

Debugging

• useful technique for identifying bugs: diagnostic

write statements

Š at various intervals in the code, write out the values of

key variables

Š you can then isolate at what point the program is

going wrong