Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Fundamental Concepts Expressed in JavaScript Get with the Program lawrence snyder c h a p t e r 18
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 18-2 Overview: Programming Concepts Programming: Act of formulating an algorithm or program Basic concepts have been developed over last 50 years to simplify common programming tasks Concepts will be expressed in JavaScript –Fully general programming language –Designed for making active web pages/apps
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 18-3 Programming Concepts Not enough for fancy web pages, but these provide a basic set of first capabilities Names, values, variables Declarations Data types, numbers, string literals and Booleans Assignment Expressions Conditionals
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 18-4
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 18-5
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 18-6 Names, Values, And Variables A Name is a symbol that represents something Names Have Changing Values –The name U.S. President has current value of Barack Obama, previous values of Bill Clinton, George Washington Names in a Program Are Called Variables –The term “variable” reminds us that the value associated with the symbol can vary during program execution –Values associated with a variable change in programs using the assignment statement ( = )
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 18-7 Names and Changing Values
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 18-8 Identifiers and Their Rules An Identifier is the character sequence that is a variable's name Must be formed following specific rules –Must begin with a letter or underscore ( _ ) followed by any sequence of letters, digits, or underscore characters –Cannot contain spaces –Case sensitive (Capitalization matters!)
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 18-9 ValidInvalid firstOne 1stOne first1first-1 First_1first$1 First_Onefirst One fIRSToNE First1! _special 5 very_long_name_ok happy:) For each invalid identifier, what rule is broken? Identifiers and Their Rules
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley A Variable Declaration Statement Declaration: State what variables will be used –Command uses the keyword var –For example, a program to calculate area of a circle given a radius, might use variables area and radius: var radius, area; The variable declaration is a type of statement Can have many var statements in a program
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Statement Terminator A program is a list of statements –Several statements may be run together on a line Each statement is terminated by the statement terminator symbol –In JavaScript, this is the semicolon ( ; ) Forgetting the semi-colon is a very common error, so be warned (and wary)
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Rules for Declaring Variables Every variable used in a program must be declared (before it is used) –In JavaScript declaration can appear anywhere in the program –Programmers prefer to place them first (“up top”) Undefined values –A variable may be declared, but may not yet have any value associate with it (its initial value) var speed; // undefined initial value speed = 42; // now it has a value
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Initializing a Declaration We can set an initial value as part of a declaration: –var speed = 42; Related variables may be grouped in one declaration/initialization; unrelated variables are usually placed in separate statements var numA=27, numB, numC; var numA = 27; var numB; var numC; Since this is what programmers commonly do, but it is not required, it is called a programming convention
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Three Basic Date Types in JavaScript In JavaScript, values are grouped into related categories called data types, or just types –numbers (or numeric, for arithmetic) –strings (used for text) –Booleans (used for logic)
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Rules for Writing Numbers There are no "units" or commas Can have about 10 significant digits and can range from to Values with no decimal point are integers Values with a decimal point are real, or floating point
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Strings Strings are sequences of keyboard characters Strings are always surrounded by single ( ' ' ) or double quotes ( " " ) Strings can initialize a declaration –var hairColor = “black”, sign=‘Leo’; –var greeting = “Hello, how are you today?” Note that the string value “123” is not the same as the number value 123
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Rules for Writing Strings in JavaScript Must be surrounded by single or double quotes Allow most characters except return (Enter), backspace, tab, \ Double quoted strings can contain single quoted strings and vice versa ( “My dog ‘Spot’ is a yellow Lab” ) The apostrophe ( ' ) is the same as the single quote
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Any number of characters allowed in a string Minimum number of characters is zero ( "" ), which is the empty string; it contains no characters at all Quotes do not count in figuring a string’s length –Empty string has length 0, not 2 Note that the empty string is not the same as the string “ ”, which contains one blank Rules for Writing Strings in JavaScript
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Literals Literal is the term for a string or number value that is typed out in the program text String Literals stored in the computer –Quotes are removed (they are only used to delimit the string literal) –Any character can be stored in memory Even a character that cannot be typed can be stored, using escape mechanism – in JavaScript, the backslash ( \ ) var twoTabs = “\t\t”, singQuote=“\’”
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 18-20
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Boolean Values Two logical values: true and false They are values, not identifiers or strings –true is a Boolean value like 5 is a number value Used implicitly throughout the programming process; only occasionally for initializing variables –Mostly used to compare data or make decisions –var done=false, simpleMode=true, speed=42;
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Assignment Statement Used to change a variable's value ; Assignment Symbol: –In JavaScript, the equal sign ( = )
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Interpreting an Assignment Statement Value “flows” from the right side to the left side Read the assignment symbol as "is assigned" or "becomes" or "gets“ speed = 42 we say “speed gets 42” The expression (right side) is computed or evaluated first –If there are any variables in it, their current value is used Then this computed value becomes the value of the variable on the left side
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Three Key Points about Assignment All three of the components must be given –if anything is missing, the statement is meaningless Flow of value to name is always right to left Values of any variables used in the expression are always their values before the start of the execution of the assignment
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley A Fourth Key Point about Assignment Programming is not Algebra Consider this statement x = x + 1 –In Algebra, this is impossible… no number is the same as one greater than itself –In programming, we say “x gets x+1” meaning take the value in x, add 1, then store the new value back in x Some programming languages do not use ‘=‘ for the assignment symbol to avoid this confusion
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley An Expression and its Syntax An expression is a math-like formula –Describe the means of performing the actual computation –Built out of values and operators standard arithmetic operators are symbols of basic arithmetic relational operators compare values logical operators and string operators too
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Arithmetic Operators Add, subtract, multiply, divide ( +, -, *, / ) Multiplication must be given explicitly with the asterisk ( * ) multiply operator –2ab works in math, but in JavaScript we write 2*a*b Multiply and divide are performed before add and subtract –Unless grouped by parentheses –This is called operator precedence
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Arithmetic Operators Modulus or mod ( % ) divides two integers and returns the remainder JavaScript does not have an operator for exponents Binary operators operate on two operands –like + and * and % Unary operators operate on one operand –like - for negation
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Relational Operators Make comparisons between numeric values Outcome is a Boolean value, true or false < less than <=less than or equal to ==equal to (note difference between = and ==) !=not equal to >=greater than or equal to > greater than 5 < 10 evaluates to true 8.54 == 14.7 evaluates to false speed > 42 have to see what value speed has
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Logical Operators Used with Boolean values Logical And –Operator is && –Outcome of a && b is true if both a and b are true; otherwise it is false Logical Or –Operator is || –Outcome of a || b is true if either a is true or b is true Logical Not –Operator is ! –Unary operator. Outcome is opposite of value of operand
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley To test two or more relationships together –Teenagers are older than 12 and younger than 20 var age = 6 Evaluate age > 12 && age < 20 age > 12 evaluates to false age < 20 evaluates to true Finally, false && true evaluates to false Try it for var age = 14 age > 12 evaluates to true age < 20 evaluates to true Finally, true && true evaluates to true Logical Operators
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Operators (cont'd) Operator Overload –Use of one operator symbol with different data types –Case of interest in JavaScript is + Addition: When used with numbers, it adds –4 + 5 produces 9 Concatenation: When + is used with strings, it concatenates or joins the strings together –"four" + "five" produces "fourfive"
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley A Conditional Statement Conditional statements are used to perform tests based on variable values if ( ) ; Boolean expression is usually a relational expression; then-statement is any JavaScript statement
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley If Statements and Their Flow of Control The Boolean statement, called a predicate, is evaluated, producing a true or false outcome If the outcome is true, the then-statement is performed If the outcome is false, the then-statement is skipped Then-statement can be written on the same line as the Boolean or on the next line
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Compound Statements Sometimes we need to perform more than one statement on a true outcome of the predicate test –Then-statement can be a sequence of statements –Group these statements using curly braces { } if (waterTempC < 0) { waterState = “solid”; description = “ice”; } All statements in { } are executed on true outcome
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley if/else Statements To execute statements if a condition is false if ( ) { ; } else { ; } The Boolean expression is evaluated first –If the outcome is true, the then-statements are executed and the else-statements are skipped –If the outcome is false, the then-statements are skipped and the else-statements are executed
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Nested if/else Statements A then-statement (or an else-statement) can contain another if/else By rule, an else is associated with the closest preceding if Use curly braces to avoid confusion and to ensures that every else matches with its proper if
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley if ( ) { ; } else { ; } if ( ) if ( ) { ; } else { ; } Nested if/else Statements
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Freely Use Braces for Clarity if (flip1 == guess1) { if (flip2 == guess2) score = “win win”; else score = “win lose”; } else { // here we lost the first if (flip2 == guess2) score = “lose win”; else score = “lose lose”; }
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Espresso Program (again)
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Espresso Program Line 3 is a basic conditional statement Lines 4-4c use an if statement with conditionals in the then statement Line 5 uses basic if statement Lines 6, 7 compute using arithmetic operators Try tracing the logic for a “double tall latte” drink=“latte”; ounce=12; shots=2;
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Summary Names and values are distinct concepts; names of variables must be declared; variables can be initialized when declared; variable values are changed with assignment An assignment statement has a variable name on the left, an expression on the right, and the assignment symbol in the middle Assignment works by evaluating the expression on the right (using values currently in the variables) and then putting the new value into the variable on the left
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Summary JavaScript has 3 data types: number, string, and Boolean We can build expressions to compute values of these types Arithmetic operators, and relational operators work on number values; logical operators work on Boolean values Operator overloading means that sometimes one symbol is used to represent two different operations (on two types)
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Summary Conditional statements allow alteration of the normal flow of control from one statement to the next Conditional statements allow blocks of statements to be either executed or skipped, depending on the outcome of evaluating a Boolean expression Compound statements are sequences of statements, grouped in curly braces Conditional statements allow us to organize our programs so that groups of statements are executed only when “the conditions are right”