cmps 211 javascript topic 1 javascript syntax. 2outline goals and objectives goals and objectives...

22
CMPS 211 JavaScript CMPS 211 JavaScript Topic 1 Topic 1 JavaScript Syntax JavaScript Syntax

Upload: wilfrid-mcbride

Post on 01-Jan-2016

219 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction

CMPS 211 JavaScriptCMPS 211 JavaScript

Topic 1Topic 1

JavaScript SyntaxJavaScript Syntax

Page 2: CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction

2

OutlineOutline Goals and ObjectivesGoals and Objectives Chapter HeadlinesChapter Headlines IntroductionIntroduction JavaScript and JavaJavaScript and Java Embedding JavaScript in XHTMLEmbedding JavaScript in XHTML Development EnvironmentDevelopment Environment VariablesVariables StatementsStatements Expressions and OperatorsExpressions and Operators Control StructuresControl Structures Code ExecutionCode Execution Input and OutputInput and Output SummarySummary

Page 3: CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction

3

Goals and ObjectivesGoals and Objectives GoalsGoals

Understand the basics of JavaScript, its syntax, the development Understand the basics of JavaScript, its syntax, the development environment, order of code execution, debugging and testing, its environment, order of code execution, debugging and testing, its inclusion in XHTML and Web pages, and the reasons of including inclusion in XHTML and Web pages, and the reasons of including JavaScript in Web pagesJavaScript in Web pages

ObjectivesObjectives Why use JavaScript?Why use JavaScript? JavaScript and SyntaxJavaScript and Syntax VariablesVariables StatementsStatements OperatorsOperators Control StructuresControl Structures Input/OutputInput/Output Practice: Integer Division, Dollars and CentsPractice: Integer Division, Dollars and Cents

Page 4: CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction

4

Topic HeadlinesTopic Headlines 1 1 IntroductionIntroduction

What is JavaScript and is it useful?What is JavaScript and is it useful? 2 2 JavaScript and JavaJavaScript and Java

Does learning JavaScript now help learning Java Does learning JavaScript now help learning Java later?later?

3 3 Embedding JavaScript in XHTMLEmbedding JavaScript in XHTML Are JavaScript and XHTML cousins?Are JavaScript and XHTML cousins?

4 4 Development EnvironmentDevelopment Environment You only need a debugging console to develop You only need a debugging console to develop

JavaScriptJavaScript 5 5 VariablesVariables

Use variables as you need them without Use variables as you need them without declarationsdeclarations

Page 5: CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction

5

Topic HeadlinesTopic Headlines 6 6 StatementsStatements

Comment statements help code reuse and Comment statements help code reuse and maintenancemaintenance

7 7 Expressions and OperatorsExpressions and Operators JavaScript operators are waiting to help youJavaScript operators are waiting to help you

8 8 Control StructuresControl Structures Control structures can provide more helpControl structures can provide more help

9 9 Code ExecutionCode Execution Follow the rule of top to bottom, left to rightFollow the rule of top to bottom, left to right

10 10 Input and OutputInput and Output Four functions are available for client-side data and Four functions are available for client-side data and

result handlingresult handling

Page 6: CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction

6

IntroductionIntroduction XHTML offers XHTML offers limited dynamicslimited dynamics JavaScript is used in web pages for:JavaScript is used in web pages for:

DynamicsDynamics : mouse clicks, pop up windows, and animations : mouse clicks, pop up windows, and animations Client-side execution Client-side execution : validating input, processing requests: validating input, processing requests

It It avoids Client/Server communication and trafficavoids Client/Server communication and traffic JavaScript is JavaScript is executed on client-sideexecuted on client-side JavaScript is JavaScript is simple, powerful, and interpretive simple, powerful, and interpretive language language

and requires only a web browserand requires only a web browser There have been a There have been a number of revisionsnumber of revisions, the latest version , the latest version

being 1.5being 1.5 Two types of JavaScript exists:Two types of JavaScript exists:

Client-side Client-side code is sent to the client’s browser for execution code is sent to the client’s browser for execution Server-side Server-side code stays on the server for execution code stays on the server for execution

Page 7: CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction

7

JavaScript and JavaJavaScript and Java JavaScript and Java are JavaScript and Java are similar in some wayssimilar in some ways and and

different in other waysdifferent in other ways JavaScript JavaScript supportssupports most Java most Java expressions and basic expressions and basic

control structurecontrol structure

JavaJava JavaScriptJavaScript

Class-based object modelClass-based object model Prototype-based model Prototype-based model

Special declarationsSpecial declarations No special declarations No special declarations

Explicit variable typesExplicit variable types Implicit variable types Implicit variable types Compared to Java, JavaScript is a very Compared to Java, JavaScript is a very free form language free form language JavaScript offers tools to much JavaScript offers tools to much wider, and non-wider, and non-

sophisticated audiencesophisticated audience

Page 8: CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction

8

Embedding JavaScript in XHTMLEmbedding JavaScript in XHTML <script><script> tag is used to tag is used to embed JavaScript code embed JavaScript code in in

XHTML code of a web pageXHTML code of a web page The The <script><script> tag can be tag can be used anywhere used anywhere inside the code inside the code

but it is usually embedded but it is usually embedded right before of afterright before of after the the <head><head> tag closes tag closes

Any number of Any number of <script><script> tags can be embedded, but tags can be embedded, but usually usually one tag is enoughone tag is enough

NestingNesting <script><script> tags is tags is prohibitedprohibited and generates errors and generates errors HTML editors do not followHTML editors do not follow the the <script><script> tag guidelines tag guidelines

and embed the tag any where and any number of timesand embed the tag any where and any number of times

Page 9: CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction

9

Development EnvironmentDevelopment Environment JavaScript source code is JavaScript source code is written in an editorwritten in an editor and and run and run and

tested in a browsertested in a browser, like XHTML, like XHTML AceHTML editorAceHTML editor has a JavaScript template and also has a JavaScript template and also

allows writing code manuallyallows writing code manually Dreamweaver generates code automaticallyDreamweaver generates code automatically as the author as the author

adds JavaScript functionalityadds JavaScript functionality Error in JavaScript code prevent the page from being Error in JavaScript code prevent the page from being

rendered and thus rendered and thus debuggers are neededdebuggers are needed to find where the to find where the errors areerrors are

JavaScript JavaScript interpreters serve the purposeinterpreters serve the purpose by showing by showing where the error iswhere the error is

Errors are reported Errors are reported one at a timeone at a time and are usually and are usually easy to easy to fixfix

Page 10: CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction

10

Development EnvironmentDevelopment Environment Example 19.1Example 19.1: Hello World! JavaScript: Hello World! JavaScript

Write your first JavaScript ProgramWrite your first JavaScript Program

Page 11: CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction

11

VariablesVariables A variable is a A variable is a symbolic name that stores a valuesymbolic name that stores a value and has the some and has the some

characteristicscharacteristics IdentifiersIdentifiers

The name of the variable is its identifierThe name of the variable is its identifierIt must begin with a letter, underscore, or $ signIt must begin with a letter, underscore, or $ signIt cannot begin with a number or other charactersIt cannot begin with a number or other charactersJavaScript is case-sensitiveJavaScript is case-sensitiveExamples: Examples: test, Test, jam234, _best, $abc, test, Test, jam234, _best, $abc, a_1$4a_1$4

TypesTypesData types are implicit and are converted automaticallyData types are implicit and are converted automaticallyThe first use of a variable declares its typesThe first use of a variable declares its typesTypes can be numbers (integer or real), logical (boolean), or stringTypes can be numbers (integer or real), logical (boolean), or stringExamples: Examples: 3, 40, -10.5, true, false, “zeid”, 3, 40, -10.5, true, false, “zeid”, “9abc”“9abc”

Page 12: CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction

12

VariablesVariables ScopeScope

The code block within which the variable is availableThe code block within which the variable is availableGlobal variable is available everywhereGlobal variable is available everywhereLocal variable is available only inside a code blockLocal variable is available only inside a code blockGlobal variables are easy to manage but a bad habitGlobal variables are easy to manage but a bad habit

ConstantsConstantsRead only variables defined by a Read only variables defined by a constconst keyword keywordCannot change values or be re declaredCannot change values or be re declaredExamples: Examples: const x=35const x=35

LiteralsLiteralsFixed values (hard-coded values) in JavaScriptFixed values (hard-coded values) in JavaScriptNesting literals needs extra careNesting literals needs extra careExamples: Examples: 3.5, false, “Hello”3.5, false, “Hello”

Data Type ConversionData Type ConversionJavaScript converts data types automatically, but creates confusionJavaScript converts data types automatically, but creates confusionExamples: Examples: answer=true, answer=35answer=true, answer=35

Escaping and Special CharactersEscaping and Special CharactersBackslash is the escaping character and is used to define special onesBackslash is the escaping character and is used to define special ones

Page 13: CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction

13

VariablesVariables Example 19.2Example 19.2: JavaScript variables: JavaScript variables

Write JavaScript Program to use some variablesWrite JavaScript Program to use some variables

Page 14: CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction

14

VariablesVariables Example 19.3Example 19.3: JavaScript variable concepts: JavaScript variable concepts

Use constants, literals, data type conversion, and escaping and Use constants, literals, data type conversion, and escaping and special charactersspecial characters

Page 15: CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction

15

StatementsStatements A statement uses an A statement uses an assignment operatorassignment operator, an , an equal signequal sign The The operator has two operandsoperator has two operands on each of its side and the on each of its side and the

value of the value of the right operand is assigned to the leftright operand is assigned to the left one one Example :Example : x = yx = y Values of Values of right operand must always be knownright operand must always be known, if not, and , if not, and

error is generatederror is generated Statement must be only Statement must be only one line longone line long and and cannot be brokencannot be broken Semicolon (Semicolon (;;) is used to ) is used to separate statementsseparate statements JavaScript also provides JavaScript also provides comment statementscomment statements

Inline CommentInline Comment statement statement //one line comment//one line comment Block CommentBlock Comment statement statement /* comment starts here/* comment starts here

comment ends here */ comment ends here */

Page 16: CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction

16

Expressions and OperatorsExpressions and Operators Expressions are a Expressions are a valid set of any variables that evaluates valid set of any variables that evaluates

to a single valueto a single value Arithmetic ExpressionsArithmetic Expressions evaluate to numbers evaluate to numbers Logical ExpressionsLogical Expressions evaluate to booleans (true or false) evaluate to booleans (true or false) String ExpressionsString Expressions evaluate to strings evaluate to strings

JavaScript has a JavaScript has a rich set of operatorsrich set of operators Assignment OperatorsAssignment Operators =, +=, -=, *=, /==, +=, -=, *=, /= Comparison OperatorsComparison Operators ==, !=, >, >=, <, <===, !=, >, >=, <, <= Arithmetic OperatorsArithmetic Operators +, -, *, /, %, ++, --+, -, *, /, %, ++, -- Logical OperatorsLogical Operators &&, ||, !&&, ||, !

Page 17: CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction

17

Control StructuresControl Structures Control structures Control structures control the code executioncontrol the code execution according to a according to a

certain criteriacertain criteria Conditional StatementsConditional Statements

- Executes if the specified condition statement is met- Executes if the specified condition statement is met- - ifif and and switchswitch statements are the two types statements are the two typesifif statements: statements: structure 1structure 1:: if (condition) {…………}if (condition) {…………}

structure 2structure 2:: if (condition) {…………}if (condition) {…………}else {…………}else {…………}

switchswitch statement: statement: switch (expression){switch (expression){case condition1:case condition1:statements; break;statements; break;case condition2:case condition2:statements; break;statements; break;default:default:statements;}statements;}

Page 18: CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction

18

Control StructuresControl Structures Loop StatementsLoop Statements

- Executes repeatedly till a specific condition is met- Executes repeatedly till a specific condition is met- - for, while,for, while, and and do whiledo while statements are used statements are used- - breakbreak exits the loop all together exits the loop all together- - continuecontinue skips the current iteration skips the current iterationforfor statement: statement: for (ini value; end value; incr)for (ini value; end value; incr){ {

statements statements}}

whilewhile statement:statement: while (condition) {while (condition) { statements statements}}

do whiledo while statement:statement: do {do {statementsstatements

}while (condition) }while (condition)

Page 19: CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction

19

Code ExecutionCode Execution JavaScript code shellJavaScript code shell looks like: looks like:

<script language=“javascript”><script language=“javascript”>function definition codefunction definition codefunction definition codefunction definition codefunction definition codefunction definition codestatementsstatementsfunction callsfunction callsstatementsstatementsfunction callsfunction calls</script></script>

JavaScript interpreter executes code JavaScript interpreter executes code top to bottomtop to bottom, , left to left to rightright

Function definitions are Function definitions are executed only when calledexecuted only when called

Page 20: CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction

20

Input and OutputInput and Output Client-side JavaScript has Client-side JavaScript has limited input/output utilitieslimited input/output utilities

due to due to security reasonssecurity reasons The The input functionsinput functions available are: available are:prompt (message, default)prompt (message, default) takes an input and takes an input and returns it to the JavaScript programreturns it to the JavaScript programconfirm (question)confirm (question) asks the user to confirm an asks the user to confirm an input value and return a boolean valueinput value and return a boolean value

The The output functionsoutput functions available are: available are:document.write (string)document.write (string)alert (string)alert (string)Both these functions are used to output results in a web Both these functions are used to output results in a web pagepage

Page 21: CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction

21

Input and OutputInput and Output Example 19.8Example 19.8: Use input functions: Use input functions

Use Use prompt()prompt() and and confirm()confirm() functions functions

Page 22: CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction

22

SummarySummary• JavaScript is a JavaScript is a powerful languagepowerful language and makes a web page and makes a web page

dynamicdynamic• JavaScript and Java are JavaScript and Java are fundamentally differentfundamentally different in most in most

waysways• JavaScript code isJavaScript code is embedded embedded in XHTML code in XHTML code• JavaScript code is JavaScript code is written and testedwritten and tested like XHTML code like XHTML code• JavaScript begins with JavaScript begins with variablesvariables• JavaScript uses JavaScript uses statementsstatements to build code block to build code block• JavaScript has a JavaScript has a rich set of operatorsrich set of operators• JavaScript has JavaScript has control structurescontrol structures to to control code executioncontrol code execution• Code execution follows Code execution follows top to bottomtop to bottom, , left to rightleft to right rule rule• Input and output is Input and output is handled using basic functionshandled using basic functions