overview: programming concepts

44
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

Upload: penn

Post on 21-Jan-2016

59 views

Category:

Documents


0 download

DESCRIPTION

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 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Overview: Programming Concepts

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

Page 2: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-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

Page 3: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-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

Page 4: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-4

Page 5: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-5

Page 6: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-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 ( = )

Page 7: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-7

Names and Changing Values

Page 8: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-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!)

Page 9: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-9

Valid InvalidfirstOne 1stOnefirst1 first-1First_1 first$1First_One first OnefIRSToNE First1!

_special 5 very_long_name_ok happy:)

For each invalid identifier, what rule is broken?

Identifiers and Their Rules

Page 10: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-10

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

Page 11: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-11

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)

Page 12: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-12

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

Page 13: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-13

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

Page 14: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-14

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)

Page 15: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-15

Rules for Writing Numbers

• There are no "units" or commas

• Can have about 10 significant digits and can range from 10-324 to 10308

• Values with no decimal point are integers10 1567238 -487 -776734551 0

• Values with a decimal point are real, or floating point

10.0 3.1415926 -478934.4 0.000101101111

Page 16: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-16

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

Page 17: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-17

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

Page 18: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-18

• 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

Page 19: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-19

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=“\’”

Page 20: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-20

Page 21: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-21

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;

Page 22: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-22

The Assignment Statement

• Used to change a variable's value<variable> <assignment symbol> <expression> ;

• Assignment Symbol:

– In JavaScript, the equal sign ( = )

Page 23: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-23

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

Page 24: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-24

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

Page 25: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-25

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

Page 26: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-26

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

Page 27: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-27

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

Page 28: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-28

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

Page 29: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-29

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

Page 30: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-30

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

Page 31: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-31

• To test two or more relationships together– Teenagers are older than 12 and younger than 20

• var age = 6

• Evaluate age > 12 && age < 20age > 12 evaluates to false

age < 20 evaluates to true

Finally, false && true evaluates to false

• Try it for var age = 14age > 12 evaluates to true

age < 20 evaluates to true

Finally, true && true evaluates to true

Logical Operators

Page 32: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-32

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"

Page 33: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-33

A Conditional Statement

• Conditional statements are used to perform tests based on variable values

if ( <Boolean expression> )

<then-statement> ;

• Boolean expression is usually a relational expression; then-statement is any JavaScript statement

Page 34: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-34

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

Page 35: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-35

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

Page 36: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-36

if/else Statements

• To execute statements if a condition is false

if ( <Boolean expression> ) {<then-statements>;

}else {

<else-statements>;}

• 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

Page 37: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-37

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

Page 38: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-38

if (<Boolean exp1>) { if (< Boolean exp2>) { <then-stmts for exp2>; }} else { <else-stmts for exp1>;}

if (<Boolean exp1>) if (< Boolean exp2>) { <then-stmts for exp2>; } else { <else-stmts for exp2>; }

Nested if/else Statements

Page 39: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-39

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”;}

Page 40: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-40

The Espresso Program (again)

Page 41: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-41

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;

Page 42: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-42

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

Page 43: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-43

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)

Page 44: Overview: Programming Concepts

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley18-44

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”