SlideShare a Scribd company logo
1 of 24
Running JavaScript
Chapter 18
2
Concatenation: Operating On Strings
 string concatenation: using the + operator between a
string and another value to make a longer string
 Examples:
'hello' + 42 is 'hello42'
1 + "abc" + 2 is "1abc2"
'abc' + 1 + 2 is 'abc12'
1 + 2 + "abc" is "3abc"
"1" + 1 is "11"
3
Popup Box
 Alert box syntax:
alert(<expression>);
 Examples:
alert("Hello, world!");
4
What Is In The Variable?
 Use alert boxes to reveal the value of variables.
var x = 100;
alert(x);
 Use string concatenation to make alert messages
even more useful.
alert("x = [" + x + "]");
better!
5
Linking JavaScript File To XHTML File
 Copy the type attribute and its corresponding
value verbatim
 Use the src attribute to specify the location of
a JavaScript file
 Path location may be absolute or relative
<head>
<title>...</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="filename.js" type="text/javascript"></script>
</head>
Conditionals
7
Conditionals
 "If button is clicked, then close the popup box."
 "If Mario touches the flag, then end the level."
 "If a correct password has been entered, then reveal
the top secret documents, otherwise contact the
FBI."
 "If the coin collected brings the total to one hundred,
make 1-up sound, otherwise make regular coin
collection sound."
8
The if Statement
 if statement: a control structure that executes a block
of statements only if a certain condition is true
 General syntax:
if (<test>) {
<statement(s)> ;
}
 Example:
var gpa = 3.25;
if (gpa >= 3.0) {
alert("Good job! Have a cookie.");
}
9
if Statement Flow Chart
10
The if/else Statement
 if/else statement: A control structure that executes one block of
statements if a certain condition is true, and a second block of
statements if it is false. We refer to each block as a branch.
 General syntax:
if (<test>) {
<statement(s)> ;
} else {
<statement(s)> ;
}
 Example:
var gpa = 3.25;
if (gpa >= 3.0) {
alert("Good job! Have a cookie.");
} else {
alert("No cookie for you!");
}
11
if/else Statement Flow Chart
12
Relational Expressions
 The <test> used in an if or if/else statement must
evaluate to a Boolean value (true or false).
 Relational expressions evaluate to Boolean values and
use the following relational operators:
Operator Meaning Example Value
== equals 1 + 1 == 2 true
!= does not equal 3.2 != 2.5 true
< less than 10 < 5 false
> greater than 10 > 5 true
<= less than or equal to 126 <= 100 false
>= greater than or equal to 5.0 >= 5.0 true
13
Evaluating Relational Expressions
 Relational operators have lower precedence than math
operators.
5 * 7 >= 3 + 5 * (7 - 1)
5 * 7 >= 3 + 5 * 6
35 >= 3 + 30
35 >= 33
true
 Relational operators should not be "chained" as they can
in algebra. WARNING! JavaScript will NOT complain if
you do so and you may get unexpected results.
2 <= 1 <= 10
false <= 10
true
???
14
Errors In Coding
 Many students new to if/else write code like this:
var percent = 85;
if (percent >= 90) {
alert("You got an A!");
}
if (percent >= 80) {
alert("You got a B!");
}
if (percent >= 70) {
alert("You got a C!");
}
if (percent >= 60) {
alert("You got a D!");
} else {
alert("You got an F!");
}
 What will happen? What’s the problem?
 You may get too many popup boxes. Try it out!
15
Nested if/else Statements
 Nested if/else statement: A chain of if/else that can select
between many different outcomes based on several tests.
 General syntax:
if (<test>) {
<statement(s)> ;
} else if (<test>) {
<statement(s)> ;
} else {
<statement(s)> ;
}
 Example:
if (number > 0) {
alert("Positive");
} else if (number < 0) {
alert("Negative");
} else {
alert("Zero");
}
16
Nested if/else Variations
 A nested if/else can end with an if or an else.
 If it ends with else, one of the branches must be taken.
 If it ends with if, the program might not execute any branch.
if (<test>) {
<statement(s)>;
} else if (<test>) {
<statement(s)>;
} else {
<statement(s)>;
}
if (<test>) {
<statement(s)>;
} else if (<test>) {
<statement(s)>;
} else if (<test>) {
<statement(s)>;
}
17
Nested if/else Flow Chart
if (<test>) {
<statement(s)>;
} else if (<test>) {
<statement(s)>;
} else {
<statement(s)>;
}
18
Nested if/else if Flow Chart
if (<test>) {
<statement(s)>;
} else if (<test>) {
<statement(s)>;
} else if (<test>) {
<statement(s)>;
}
19
Nested if/else Variations
if (place == 1) {
alert("You win the gold medal!");
} else if (place == 2) {
alert("You win a silver medal!");
} else if (place == 3) {
alert("You earned a bronze medal.");
}
 Are there any cases where this code will not print a
message?
 Yes, if the place variable is not 1, 2, or 3.
 How could we modify it to print a message to non-
medalists?
 Add an else clause.
20
Sequential if Flow Chart
if (<test>) {
<statement(s)>;
}
if (<test>) {
<statement(s)>;
}
if (<test>) {
<statement(s)>;
}
21
Summary: if/else Structures
 Choose exactly 1 set of statements
if (<test>) {
<statement(s)>;
} else if (<test>) {
<statement(s)>;
} else {
<statement(s)>;
}
 Choose 0, 1, or more set of statements
if (<test>) {
<statement(s)>;
}
if (<test>) {
<statement(s)>;
}
if (<test>) {
<statement(s)>;
}
 Choose 0 or 1 set of statements
if (<test>) {
<statement(s)>;
} else if (<test>) {
<statement(s)>;
} else if (<test>) {
<statement(s)>;
}
22
Which if/else Construct To Use?
 Reading the user's GPA and printing whether the student is on
the dean's list (3.8 to 4.0) or honor roll (3.5 to 3.7)
 Printing whether a number is even or odd
 Printing whether a user is lower-class, middle-class, or upper-
class based on their income
 Determining whether a number is divisible by 2, 3, and/or 5
 Printing a user's grade of A, B, C, D, or F based on their
percentage in the course
23
Which if/else Construct To Use?
 Reading the user's GPA and printing whether the student is on
the dean's list (3.8 to 4.0) or honor roll (3.5 to 3.7)
if / else if
 Printing whether a number is even or odd
if / else
 Printing whether a user is lower-class, middle-class, or upper-
class based on their income
if / else if / else
 Determining whether a number is divisible by 2, 3, and/or 5
if / if / if
 Printing a user's grade of A, B, C, D, or F based on their
percentage in the course
if / else if / else if / else if / else
24
That Thing Called Style
 As with HTML, you are required to indent your code
properly.
 Indent code within opening and closing curly braces.
 You should spend time on thinking or coding. You
should NOT be wasting time looking for that missing
closing brace.
 So code with style!

More Related Content

Similar to 11-ScriptsAndConditionals.ppt

Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statementsSaad Sheikh
 
CONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.pptCONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.pptSanjjaayyy
 
Scalar expressions and control structures in perl
Scalar expressions and control structures in perlScalar expressions and control structures in perl
Scalar expressions and control structures in perlsana mateen
 
Cprogrammingprogramcontrols
CprogrammingprogramcontrolsCprogrammingprogramcontrols
Cprogrammingprogramcontrolsteach4uin
 
control statements of clangauge (ii unit)
control statements of clangauge (ii unit)control statements of clangauge (ii unit)
control statements of clangauge (ii unit)Prashant Sharma
 
Working with comparison operators
Working with comparison operatorsWorking with comparison operators
Working with comparison operatorsSara Corpuz
 
The Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsThe Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsTech
 
Control Structures
Control StructuresControl Structures
Control StructuresGhaffar Khan
 
Decision Control Structure If & Else
Decision Control Structure If & ElseDecision Control Structure If & Else
Decision Control Structure If & ElseAbdullah Bhojani
 
Lecture 3 Conditionals, expressions and Variables
Lecture 3   Conditionals, expressions and VariablesLecture 3   Conditionals, expressions and Variables
Lecture 3 Conditionals, expressions and VariablesSyed Afaq Shah MACS CP
 
Absolute Java 5e Savitch Test Bank
Absolute Java 5e Savitch Test BankAbsolute Java 5e Savitch Test Bank
Absolute Java 5e Savitch Test BankLauriewest24
 
Selection Control Structures
Selection Control StructuresSelection Control Structures
Selection Control StructuresPRN USM
 
Python programing
Python programingPython programing
Python programinghamzagame
 

Similar to 11-ScriptsAndConditionals.ppt (20)

Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
Ch05.pdf
Ch05.pdfCh05.pdf
Ch05.pdf
 
Control Statement programming
Control Statement programmingControl Statement programming
Control Statement programming
 
CONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.pptCONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.ppt
 
Scalar expressions and control structures in perl
Scalar expressions and control structures in perlScalar expressions and control structures in perl
Scalar expressions and control structures in perl
 
Ch05-converted.pptx
Ch05-converted.pptxCh05-converted.pptx
Ch05-converted.pptx
 
Cprogrammingprogramcontrols
CprogrammingprogramcontrolsCprogrammingprogramcontrols
Cprogrammingprogramcontrols
 
Chapter 1 nested control structures
Chapter 1 nested control structuresChapter 1 nested control structures
Chapter 1 nested control structures
 
control statements of clangauge (ii unit)
control statements of clangauge (ii unit)control statements of clangauge (ii unit)
control statements of clangauge (ii unit)
 
Working with comparison operators
Working with comparison operatorsWorking with comparison operators
Working with comparison operators
 
The Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsThe Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming Concepts
 
Control Structures
Control StructuresControl Structures
Control Structures
 
Decision Control Structure If & Else
Decision Control Structure If & ElseDecision Control Structure If & Else
Decision Control Structure If & Else
 
Lecture 3 Conditionals, expressions and Variables
Lecture 3   Conditionals, expressions and VariablesLecture 3   Conditionals, expressions and Variables
Lecture 3 Conditionals, expressions and Variables
 
Absolute Java 5e Savitch Test Bank
Absolute Java 5e Savitch Test BankAbsolute Java 5e Savitch Test Bank
Absolute Java 5e Savitch Test Bank
 
Ch3.1
Ch3.1Ch3.1
Ch3.1
 
PPS-UNIT4.pptx
PPS-UNIT4.pptxPPS-UNIT4.pptx
PPS-UNIT4.pptx
 
Selection Control Structures
Selection Control StructuresSelection Control Structures
Selection Control Structures
 
Control All
Control AllControl All
Control All
 
Python programing
Python programingPython programing
Python programing
 

More from Anjali127411

Presentstion polymorphism opp Java muet u
Presentstion polymorphism opp Java muet uPresentstion polymorphism opp Java muet u
Presentstion polymorphism opp Java muet uAnjali127411
 
Engineering management ,notes PPT slides
Engineering management ,notes PPT slidesEngineering management ,notes PPT slides
Engineering management ,notes PPT slidesAnjali127411
 
6qh6iyoesuitvyv0exyn-signature-c0a664d80fc39ee9e26afe9aaa4fdd53cac2536d6a0ca7...
6qh6iyoesuitvyv0exyn-signature-c0a664d80fc39ee9e26afe9aaa4fdd53cac2536d6a0ca7...6qh6iyoesuitvyv0exyn-signature-c0a664d80fc39ee9e26afe9aaa4fdd53cac2536d6a0ca7...
6qh6iyoesuitvyv0exyn-signature-c0a664d80fc39ee9e26afe9aaa4fdd53cac2536d6a0ca7...Anjali127411
 
Presentation ethics
Presentation ethics Presentation ethics
Presentation ethics Anjali127411
 

More from Anjali127411 (6)

Presentstion polymorphism opp Java muet u
Presentstion polymorphism opp Java muet uPresentstion polymorphism opp Java muet u
Presentstion polymorphism opp Java muet u
 
Engineering management ,notes PPT slides
Engineering management ,notes PPT slidesEngineering management ,notes PPT slides
Engineering management ,notes PPT slides
 
6qh6iyoesuitvyv0exyn-signature-c0a664d80fc39ee9e26afe9aaa4fdd53cac2536d6a0ca7...
6qh6iyoesuitvyv0exyn-signature-c0a664d80fc39ee9e26afe9aaa4fdd53cac2536d6a0ca7...6qh6iyoesuitvyv0exyn-signature-c0a664d80fc39ee9e26afe9aaa4fdd53cac2536d6a0ca7...
6qh6iyoesuitvyv0exyn-signature-c0a664d80fc39ee9e26afe9aaa4fdd53cac2536d6a0ca7...
 
Lec11cgu_10.ppt
Lec11cgu_10.pptLec11cgu_10.ppt
Lec11cgu_10.ppt
 
slides03.ppt
slides03.pptslides03.ppt
slides03.ppt
 
Presentation ethics
Presentation ethics Presentation ethics
Presentation ethics
 

Recently uploaded

Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 

Recently uploaded (20)

Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 

11-ScriptsAndConditionals.ppt

  • 2. 2 Concatenation: Operating On Strings  string concatenation: using the + operator between a string and another value to make a longer string  Examples: 'hello' + 42 is 'hello42' 1 + "abc" + 2 is "1abc2" 'abc' + 1 + 2 is 'abc12' 1 + 2 + "abc" is "3abc" "1" + 1 is "11"
  • 3. 3 Popup Box  Alert box syntax: alert(<expression>);  Examples: alert("Hello, world!");
  • 4. 4 What Is In The Variable?  Use alert boxes to reveal the value of variables. var x = 100; alert(x);  Use string concatenation to make alert messages even more useful. alert("x = [" + x + "]"); better!
  • 5. 5 Linking JavaScript File To XHTML File  Copy the type attribute and its corresponding value verbatim  Use the src attribute to specify the location of a JavaScript file  Path location may be absolute or relative <head> <title>...</title> <link rel="stylesheet" type="text/css" href="style.css" /> <script src="filename.js" type="text/javascript"></script> </head>
  • 7. 7 Conditionals  "If button is clicked, then close the popup box."  "If Mario touches the flag, then end the level."  "If a correct password has been entered, then reveal the top secret documents, otherwise contact the FBI."  "If the coin collected brings the total to one hundred, make 1-up sound, otherwise make regular coin collection sound."
  • 8. 8 The if Statement  if statement: a control structure that executes a block of statements only if a certain condition is true  General syntax: if (<test>) { <statement(s)> ; }  Example: var gpa = 3.25; if (gpa >= 3.0) { alert("Good job! Have a cookie."); }
  • 10. 10 The if/else Statement  if/else statement: A control structure that executes one block of statements if a certain condition is true, and a second block of statements if it is false. We refer to each block as a branch.  General syntax: if (<test>) { <statement(s)> ; } else { <statement(s)> ; }  Example: var gpa = 3.25; if (gpa >= 3.0) { alert("Good job! Have a cookie."); } else { alert("No cookie for you!"); }
  • 12. 12 Relational Expressions  The <test> used in an if or if/else statement must evaluate to a Boolean value (true or false).  Relational expressions evaluate to Boolean values and use the following relational operators: Operator Meaning Example Value == equals 1 + 1 == 2 true != does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true <= less than or equal to 126 <= 100 false >= greater than or equal to 5.0 >= 5.0 true
  • 13. 13 Evaluating Relational Expressions  Relational operators have lower precedence than math operators. 5 * 7 >= 3 + 5 * (7 - 1) 5 * 7 >= 3 + 5 * 6 35 >= 3 + 30 35 >= 33 true  Relational operators should not be "chained" as they can in algebra. WARNING! JavaScript will NOT complain if you do so and you may get unexpected results. 2 <= 1 <= 10 false <= 10 true ???
  • 14. 14 Errors In Coding  Many students new to if/else write code like this: var percent = 85; if (percent >= 90) { alert("You got an A!"); } if (percent >= 80) { alert("You got a B!"); } if (percent >= 70) { alert("You got a C!"); } if (percent >= 60) { alert("You got a D!"); } else { alert("You got an F!"); }  What will happen? What’s the problem?  You may get too many popup boxes. Try it out!
  • 15. 15 Nested if/else Statements  Nested if/else statement: A chain of if/else that can select between many different outcomes based on several tests.  General syntax: if (<test>) { <statement(s)> ; } else if (<test>) { <statement(s)> ; } else { <statement(s)> ; }  Example: if (number > 0) { alert("Positive"); } else if (number < 0) { alert("Negative"); } else { alert("Zero"); }
  • 16. 16 Nested if/else Variations  A nested if/else can end with an if or an else.  If it ends with else, one of the branches must be taken.  If it ends with if, the program might not execute any branch. if (<test>) { <statement(s)>; } else if (<test>) { <statement(s)>; } else { <statement(s)>; } if (<test>) { <statement(s)>; } else if (<test>) { <statement(s)>; } else if (<test>) { <statement(s)>; }
  • 17. 17 Nested if/else Flow Chart if (<test>) { <statement(s)>; } else if (<test>) { <statement(s)>; } else { <statement(s)>; }
  • 18. 18 Nested if/else if Flow Chart if (<test>) { <statement(s)>; } else if (<test>) { <statement(s)>; } else if (<test>) { <statement(s)>; }
  • 19. 19 Nested if/else Variations if (place == 1) { alert("You win the gold medal!"); } else if (place == 2) { alert("You win a silver medal!"); } else if (place == 3) { alert("You earned a bronze medal."); }  Are there any cases where this code will not print a message?  Yes, if the place variable is not 1, 2, or 3.  How could we modify it to print a message to non- medalists?  Add an else clause.
  • 20. 20 Sequential if Flow Chart if (<test>) { <statement(s)>; } if (<test>) { <statement(s)>; } if (<test>) { <statement(s)>; }
  • 21. 21 Summary: if/else Structures  Choose exactly 1 set of statements if (<test>) { <statement(s)>; } else if (<test>) { <statement(s)>; } else { <statement(s)>; }  Choose 0, 1, or more set of statements if (<test>) { <statement(s)>; } if (<test>) { <statement(s)>; } if (<test>) { <statement(s)>; }  Choose 0 or 1 set of statements if (<test>) { <statement(s)>; } else if (<test>) { <statement(s)>; } else if (<test>) { <statement(s)>; }
  • 22. 22 Which if/else Construct To Use?  Reading the user's GPA and printing whether the student is on the dean's list (3.8 to 4.0) or honor roll (3.5 to 3.7)  Printing whether a number is even or odd  Printing whether a user is lower-class, middle-class, or upper- class based on their income  Determining whether a number is divisible by 2, 3, and/or 5  Printing a user's grade of A, B, C, D, or F based on their percentage in the course
  • 23. 23 Which if/else Construct To Use?  Reading the user's GPA and printing whether the student is on the dean's list (3.8 to 4.0) or honor roll (3.5 to 3.7) if / else if  Printing whether a number is even or odd if / else  Printing whether a user is lower-class, middle-class, or upper- class based on their income if / else if / else  Determining whether a number is divisible by 2, 3, and/or 5 if / if / if  Printing a user's grade of A, B, C, D, or F based on their percentage in the course if / else if / else if / else if / else
  • 24. 24 That Thing Called Style  As with HTML, you are required to indent your code properly.  Indent code within opening and closing curly braces.  You should spend time on thinking or coding. You should NOT be wasting time looking for that missing closing brace.  So code with style!