CNIT 133 - PowerPoint PPT Presentation

1 / 24
About This Presentation
Title:

CNIT 133

Description:

The increment and decrement operators, and --, are related to assignment ... simply a frequently used programming idiom that results when repeated if/else ... – PowerPoint PPT presentation

Number of Views:55
Avg rating:3.0/5.0
Slides: 25
Provided by: hy86
Category:
Tags: cnit | idiom

less

Transcript and Presenter's Notes

Title: CNIT 133


1
CNIT 133
  • Statements

2
Objectives
  • JavaScript Statements
  • Expression Statements
  • Compound Statements
  • If
  • Else if
  • Switch
  • While
  • Do/while
  • For
  • For/in
  • Labels
  • Break
  • Continue
  • Var
  • Function
  • Return
  • Throw
  • Try/catch/finally
  • The Empty Statement

3
Expression Statements
  • Assignment statements are one major category of
    expression statements
  • s Hello name
  • i 3
  • The increment and decrement operators, and --,
    are related to assignment statements
  • Counter
  • Function calls are another major category of
    expression statements
  • alert(Welcome, name)
  • window.close()

4
Compound Statements
  • JavaScript has a way to combine a number of
    statements into a single statement (or statement
    block)
  • x Math.PI
  • cx Math.cos(x)
  • alert(cos( x ) cx)
  • This statement block acts as a single statement,
    it does not end with a semicolon. The primitive
    statements within the block end in semicolons,
    but the block itself does not.

5
if
  • The if statement is the fundamental control
    statement that allows JavaScript to make
    decisions, or to execute statements
    conditionally.
  • This statement has two forms, the first form is
  • if (expression)
  • Statement
  • Expression is evaluated. If the resulting value
    is true, statement is executed. If false,
    statement is not executed
  • if (username null)
  • username John Doe
  • You can always replace a single statement with a
    statement block
  • if ((address null) (address ))
  • address undefined
  • alert(Please specify a mailing address.)

6
if
  • The second form of the if statement introduces an
    else clause that it executed when expression is
    false
  • if (expression)
  • statement 1
  • else
  • statement 2
  • Expression is evaluated, if it is true, statement
    1 is executed otherwise, statement 2 is
    executed
  • if (username null)
  • username prompt(Welcome! \n what is your
    name?)
  • alert(Hello username)
  • else
  • alert(Hello username Welcome.)

7
else if
  • else if is not really a JavaScript statement, but
    simply a frequently used programming idiom that
    results when repeated if/else statements are
    used
  • if (n 1)
  • // execute block 1
  • alert(N is 1)
  • else if (n 2)
  • // execute block 2
  • alert(N is 2)
  • else if (n 3)
  • // execute block 3
  • alert(N is 3)
  • else
  • // execute block 4
  • alert(N is greater than 3)

8
switch
  • The JavaScript switch statements is quite similar
    to the switch statement in Java or C
  • switch(expression)
  • statements
  • When a switch executes, it computes the value of
    expression and then looks for a case label that
    matches that value. If it finds one, it starts
    executing the block of code at the first
    statement following the case label. If it does
    not find a case label with a matching value, it
    starts execution at the first statement following
    a special default label. Or, if there is no
    default label, it skips the block of code
    altogether
  • switch(n)
  • case 1
  • //execute code block 1
  • break
  • case 2
  • //execute code block 2
  • break
  • case 3
  • /execute code block 3
  • break
  • default
  • //execute code block 4
  • break

9
while
  • The while statement is the basic statement that
    allows JavaScript to perform repetitive actions
  • while (expression)
  • statement
  • The while statement works by first evaluating
    expression. If it is false, JavaScript moves on
    to the next statement after while statement in
    the program. If it is true, the statement that
    forms the body of the loop is executed, and
    expression is evaluated again. The cycle
    continues until expression evaluates to false
  • var count 0
  • while (count lt 10)
  • document.write(count ltbrgt)
  • count

10
do/while
  • The do/while loop is much like a while loop,
    except that the loop expression is tested at the
    bottom of the loop rather than at the top. This
    means that the body of the loop is always
    executed at least once
  • do
  • statement
  • while (expression)
  • The do/while loop is less commonly used than its
    while cousin. It is somewhat uncommon to
    encounter a situation in which you are always
    sure that you want a loop to execute at least
    once
  • function printArray(a)
  • if (a.length 0)
  • document.write(Empty Array)
  • else
  • var i 0
  • do
  • document.write(ai ltbrgt)
  • while (i lt a.length)

11
for
  • The initialization, the test, and the update are
    the three crucial manipulations of a loop
    variable the for statement makes these three
    steps an explicit part of the loop
  • for (initialize test increment)
  • statement
  • In other words, the initialize expression is
    evaluated once. The test expression is evaluated
    before each iteration and controls whether the
    body of the loop is executed. If the test
    expression is true, the statement that is the
    body of the loop is executed. Finally, the
    increment expression is evaluated
  • for (var count 0 count lt 10 count)
  • document.write(count ltbrgt)

12
for/in (advance topic)
  • The for/in syntax
  • for (variable in object)
  • statement
  • The for/in statement provides a way to loop
    through the properties of an object. The body of
    the for/in loop is executed once for each
    property of object. Before the body of the loop
    is executed, the name of one of the objects
    properties is assigned to variable, as a string.
    Within the body of the loop, you can use this
    variable to look up the value of the objects
    property with the operator
  • for (var prop in my_object)
  • document.write(name value
    my_objectprop, ltbrgt)
  • You can copy the name of all object properties
    into an array
  • var o x1, y2, z3
  • var a new Array()
  • var i 0
  • for (ai in o) / empty loop body /
  • JavaScript arrays are simply a specialized kind
    of object
  • for (i in a) alert(i)

13
Labels
  • The case and default labels used with the switch
    statement are a special case of a more general
    label statement. Any statement may be labeled by
    preceding it with an identifier name and a colon
  • identifier statement
  • The identifier can be any legal JavaScript
    identifier that is not a reserved word.
  • parser
  • while (token ! null)
  • // code omitted here
  • By labeling a statement, you give it a name that
    you can use to refer to it elsewhere in your
    program. You can label any statement, although
    the only statements that are commonly labeled are
    loops while, do/while, for and for/in. By giving
    a loop a name, you can use break and continue to
    exit the loop or to exit a single iteration of
    the loop.

14
break
  • The break statement causes the innermost
    enclosing loop or a switch statement to exit
    immediately
  • break
  • JavaScript allows the break keyword to be
    followed by the name of a label
  • break labelname
  • When break is used with a label, it jumps to the
    end of, or terminates, the named statement, which
    may be any enclosing statement.
  • As discussed before, a newline is not allowed
    between the break keyword and the lebelname.
  • for (i 0 i lt a.length i)
  • if (ai target)
  • break

15
continue
  • The continue statement is similar to the break
    statement. Instead of exiting a loop, however,
    continue restarts a loop in a new iteration
  • continue
  • The continue statement can also be used with a
    lebel
  • continue labelname
  • The continue statement, in both its labeled and
    unlabeled forms, can be used only within the body
    of a while, do/while, for, or for/in loop. Using
    it anywhere else causes a syntax error.
  • When the continue statement is executed, the
    current iteration of the enclosing loop is
    terminated, and the next iteration begins
  • In a while loop, the specified expression at the
    beginning of the loop is tested again. If it is
    true, the loop body is executed starting from the
    top.
  • In a do/while loop, execution skips to the bottom
    of the loop, where the loop condition is tested
    again before restarting the loop at the top.
  • In a for loop, the increment expression is
    evaluated, and the test expression is tested
    again to determine if another iteration should be
    done.
  • In a for/in loop, the loop starts over with the
    next property name being assigned to the
    specified variable.
  • Unlabeled continue statement
  • for (i 0 i lt data.length i)
  • if (datai null)
  • continue // cannot process with
    undefined data
  • total datai
  • Line breaks are not allowed between the continue
    statement and its labelname.

16
var
  • The var statement allows you to explicitly
    declare a variable or variables
  • var name_1 value_1,, name_n value_n
  • The var keyword is followed by a comma-separated
    list of variables to declare each variable in
    the list may optionally have an initializer
    expression that specifies its initial value
  • var i
  • var j 0
  • var p, q
  • var greeting hello name
  • var x 2.34, y Math.cos(0.75), r, theta
  • If no initial value is specified for a variable
    with the var statement, the variable is defined,
    but its initial value is undefined.
  • The var statement can also appear as part of the
    for and for/in loops
  • for (var i 0 i lt 10 i)
    document.write(i, ltbrgt)
  • for (var i 0, j 10 i lt 10 i, j--)
    document.write(ij, ltbrgt)
  • for (var i in o) document.write(i, ltbrgt)

17
function
  • The function statement defines a JavaScript
    function
  • function funcname (arg1 , arg2 , argn)
  • statements
  • The body of the function is composed of any
    number of JavaScript statements, contained within
    curly braces. These statements are not executed
    when the function is defined. Instead, they are
    compiled and associated with the new function
    object for execution when the function is invoked
    with the () function call operator. Note that
    the curly braces are a required part of the
    function statement.
  • A function definition creates a new function
    object and stores that object in a newly created
    property named funcname
  • function welcome() alert(Welcome to my web
    site!)
  • function print(msg)
  • document.write(msg, ltbrgt)
  • function factorial(n) // a recursive function
  • if (n lt 1) return 1
  • return n factorial(n 1)

18
return
  • The return statement specifies the value returned
    by a function
  • return expression
  • A return statement may appear only within the
    body of a function. It is a syntax error for it
    to appear anywhere else. When the return
    statement is executed, expression is evaluated
    and returned as the value of the function.
    Execution of the function stops when the return
    statement is executed, even if there are other
    statements remaining in the function body
  • function square(x) return x x
  • The return statement may also be used without an
    expression to simply terminate execution of the
    function without returning a value
  • function display_object(obj)
  • if (obj null) return
  • // rest of the function goes here
  • If a function executes a return statement with no
    expression, or if it returns because it reaches
    the end of the function body, the value of the
    function-call expression is undefined.
  • Because of JavaScripts automatic semicolon
    insertion, you may not include a line break
    between the return keyword and the expression
    that follows it.

19
throw
  • An exception is a signal that indicates that some
    sort of exceptional condition or error has
    occurred.
  • To throw an exception is to signal such an error
    or exceptional condition.
  • To catch an exception is to handle it to take
    whatever actions are necessary or appropriate to
    recover from the exception.
  • In JavaScript, exceptions are thrown whenever a
    runtime error occurs and whenever the program
    explicitly throws one using the throw statement.
  • Exceptions are caught with the try/catch/finally
    statement.
  • The throw syntax
  • throw expression
  • Expression may evaluate to a value of any type.
    Commonly, it is an Error object or an instance of
    one of the subclasses of Error. It can also be
    useful to throw a string that contains an error
    message, or a numeric value that represent some
    sort of error code

20
throw (continue)
  • function factorial(x)
  • if (x lt 0) // if input invalid, throw
    exception
  • throw new Error(x must not be
    negative)
  • for (var f 1 x gt 1 f x, x--)
  • return f
  • When an exception is thrown, the JavaScript
    interpreter immediately stops normal program
    execution and jumps to the nearest exception
    handler.
  • Exception handlers are written using the catch
    clause of the try/catch/finally statement.
  • If the block of code in which the exception was
    thrown does not have an associated catch clause,
    the interpreter checks the next highest enclosing
    block of code to see if it has an exception
    handler associated with it.
  • This continues until a handler is found. If no
    exception handler is ever found, the exception is
    treated as an error and is reported to the user.
  • The throw statement is standardized by ECMAScript
    v3 and implemented in JavaScript 1.4.
  • The Error class and its subclasses are also part
    of ECMAScript v3, but they were not implemented
    until JavaScript 1.5.

21
try/catch/finally
  • The try/catch/finally statement is JavaScripts
    exception-handling mechanism.
  • The try clause of this statement simply defines
    the block of code whose exceptions are to be
    handled.
  • The try block is followed by a catch clause,
    which is a block of statements that invoked when
    an exception occurs anywhere within the try
    block.
  • The catch clause is followed by a finally block
    containing cleanup code that is guaranteed to be
    executed, regardless of what happens in the try
    block.
  • Both the catch and finally blocks are optional,
    but a try block must be accompanied by at least
    one of these blocks.
  • The try, catch, and finally blocks all begin and
    end with curly braces. These braces are a
    required part of the syntax and cannot be
    omitted.
  • The try/catch/finally statement is standardized
    by ECMAScript v3 and implemented in JavaScript
    1.4.

22
try/catch/finally (continue)
  • try/catch/finally syntax
  • try
  • // this code runs from the top of the block
  • // to the bottom without problems. But it
    can
  • // sometimes throw an exception, either
    directly, with
  • // a throw statement, or indirectly, by
    calling a method
  • // that throws an exception.
  • catch (e)
  • // the statements in this block are executed
    if, and only
  • // if, the try block throws an exception.
    These statements can
  • // use the local variable e to refer to
    the Error object or other
  • // value that was thrown.
  • finally
  • // this block contains statements that are
    always executed. They are
  • // executed whether the try block
    terminates
  • // 1) normally, after reaching the bottom of
    the block
  • // 2) because of a break, continue, or
    return statement

23
try/catch/finally (continue)
  • Example of try/catch statement
  • try
  • var n prompt(Please enter a positive
    integer, ) // ask user to enter a num
  • var f factorial(n) // calc factorial
  • alert(n ! f) // display result
  • catch (ex) // if input was not valid
  • alert(ex) // display error

24
The Empty Statement
  • The empty statement
  • Executing the empty statement has no effect and
    performs no action
  • Initialize an array a
  • for (i 0 i lt a.length ai 0)
  • When you intentionally use the empty statement,
    it is a good idea to comment your code in a way
    that makes it clear that you are doing it on
    purpose
  • for (i 0 i lt a.length ai 0) / empty
    /
Write a Comment
User Comments (0)
About PowerShow.com