21 Functions CS101

  • Upload
    jamal4u

  • View
    222

  • Download
    0

Embed Size (px)

Citation preview

  • 8/8/2019 21 Functions CS101

    1/53

    CS101 Introduction to Computing

    Lecture 21Functions(Web Development Lecture 7)

  • 8/8/2019 21 Functions CS101

    2/53

    T odays Goal:Functions

    T o be able to understand the concept of functions and their use for solving simple

    problems

    T o become familiar with the concept of local

    and global variables

  • 8/8/2019 21 Functions CS101

    3/53

    Function

    A group of statements that is put together (or defined) once and then can be used (byreference) repeatedly on a Web page

    Also known as subprogram, procedure,subroutine

  • 8/8/2019 21 Functions CS101

    4/53

    Advantages of Functions

    Number of lines of code is reduced

    Code becomes easier to read & understand

    Code becomes easier to maintain aschanges need to be made only at a singlelocation instead multiple locations

  • 8/8/2019 21 Functions CS101

    5/53

    function writeList ( heading , words ) {

    document.write( heading + "
    " ) ;

    for ( k = 0 ; k < words .length ; k = k + 1 ) {document.write( words [ k ] + "
    " ) ;

    }}

    Keyword

    Functionidentifier

    Pair of parenthesis

    Function argumentsseparated by commas

    Functiondefinitionenclosedin a pair of curlybraces

  • 8/8/2019 21 Functions CS101

    6/53

    Function Identifiers

    T he naming rules for function identifiersare the same as were discussed for variable and array identifiers

  • 8/8/2019 21 Functions CS101

    7/53

    Arguments of a Function

    Acomma-separated list

    Arguments define the interface between the

    function and the rest of the Web page

    Arguments values are passed to the functionby value (some other popular languagespass arguments by reference as well)

  • 8/8/2019 21 Functions CS101

    8/53

    function show_message(){window.alert( T his is an alert!);}

    show_message()

  • 8/8/2019 21 Functions CS101

    9/53

    T o ensure that a function is defined

    before it is called up, define allfunctions in the HEAD portion of Webpages

  • 8/8/2019 21 Functions CS101

    10/53

    T wo Ways of Calling Functions

    function add ( a , b ) {c = a + b ;

    return c ;}sum = add ( 2, 4 ) ;

    document.write( sum ) ;

    function popUp ( message ) {window.alert( message ) ;

    }

    popUp ( Warning! ) ; A function callappearing as part of a statement.Definitions of such functionsinclude a returnstatement

    A function callappearing as acompletestatement

  • 8/8/2019 21 Functions CS101

    11/53

    function popUp ( message ) {

    window.alert( message ) ;}popUp ( Warning! ) ;

    function popUp ( message ) {window.alert( message ) ;

    }a = popUp ( Warning! ) ;document.write( a ) ;

    What will getwritten by thisstatement?

    undefined

  • 8/8/2019 21 Functions CS101

    12/53

    function add ( a , b ) {c = a + b ;return c ;

    }sum = add ( 2, 4 ) ;

    document.write( sum ) ;

    function add ( a , b ) {

    c = a + b ;return c ;}add ( 2, 4 ) ;

    What wouldthis statementdo?

  • 8/8/2019 21 Functions CS101

    13/53

    function add ( a , b ) {c = a + b ;return c ;

    }sum = add ( 2, 4 ) ;

    document.write( sum ) ;

    What wouldthis statementdo?

    function add ( a , b ) {

    c = a + b ;return c ;}document.write( add ( 2, 4 ) ) ;

    What wouldthis modifica-tion do?

  • 8/8/2019 21 Functions CS101

    14/53

  • 8/8/2019 21 Functions CS101

    15/53

    M ethods

    M ethods are functions

    T hey are unusual in the sense that theyare stored as properties of objects

  • 8/8/2019 21 Functions CS101

    16/53

    O bject: A named collection of properties(data, state ) & methods ( instructions, behavior )

    prop 1prop 2

    prop 5

    name

    prop 3

    prop 4

    A collectionof properties& methods

    All objects have thename property: itholds the name of the object

    method 3method 1

    method 2

  • 8/8/2019 21 Functions CS101

    17/53

    O bject: A named collection of properties

    prop 1prop 2

    prop 5

    name

    prop 3

    prop 4

    A collectionof properties All objects have the

    name property: itholds the name of the object

    prop 8prop 6

    prop 7

  • 8/8/2019 21 Functions CS101

    18/53

    f unctionf unction

    event handler event handler

  • 8/8/2019 21 Functions CS101

    19/53

    Predefined, T op-Level or Built-In Functions

    Event handlers are not the only functions thatcome predefined with JavaScript. T here aremany others .

    Practically, there is no difference betweenpredefined functions and those that aredefined by the programmer (termed as user-defined or custom functions)

    T here are many of them, but here we discussonly two: parseInt( ) , parseFloat( )

    P arse: T o breakdown into simpler components and analyze

  • 8/8/2019 21 Functions CS101

    20/53

    Scope of Variable

    Defining the space in which a variable is effectiveis known as

    defining the scope of a variable

    A variable can beeither local or global

    in scope

  • 8/8/2019 21 Functions CS101

    21/53

    Local and Global Variables

    L ocal or Function-level VariableEffective only in the function in which they aredeclared

    Global Variables

    Visible everywhere on the Web page

  • 8/8/2019 21 Functions CS101

    22/53

    Local Variables

    Declaring variables (using the var keyword) within a function , makes themlocal

    T hey are available only within the functionand hold no meaning outside of it

  • 8/8/2019 21 Functions CS101

    23/53

    Global Variables

    All other variables used in a Web page (or window)are global

    They can be manipulated from the main code aswell as from any of the functions

    T hey include: All variables declared in the main code All variables used but not declared in the main code All variables used but not declared in any of the

    functions defined on the Web page (or window)

  • 8/8/2019 21 Functions CS101

    24/53

    var u ;document.write( m ) ;

    var c, d ;x = y * y ;

    r = s ;

    var a, b ;p = q + 2 ;

    Global Localu am bp cq dxyr s

    Variables declared within f unctions are local; all others global

  • 8/8/2019 21 Functions CS101

    25/53

    why havewhy havelocal variableslocal variables

    why not make allwhy not make allvariables globalvariables global

  • 8/8/2019 21 Functions CS101

    26/53

    Local vs- Global

    Global variables can make the logic of a Webpage difficult to understand

    Global variables also make the reuse andmaintenance of your code much more difficult

    HEURISTIC:If its possible to

    define a variable

    as local, do it!

  • 8/8/2019 21 Functions CS101

    27/53

    JavaScript O peratorsO perators operate on operands to achieve thedesired results

    JavaScript has numerous operators, classified inmany categories. We will look at only a few of them belonging to the following categories: Assignment operators -- Arithmetic operators Comparison operators -- String operators

    Logical operators

    Well look at a few more during future lectures, butunderstand that there are many more . Even thesupplementary textbook does not cover all of them!

  • 8/8/2019 21 Functions CS101

    28/53

    Assignment O perator =Changes the value of what is on the LHS, w.r.t. what is on the RHS

    total_number_of_students = 984 ;

    title = Understanding Computers ;

    swapFlag = false ;

    x = y + 33 ;

  • 8/8/2019 21 Functions CS101

    29/53

    Arithmetic O perators

    M ultiply 2 * 4 8

    Divide 2 / 4 0.5

    M odulus 5 % 2 1

    Add 2 + 4 6

    Subtract 2 - 4 -2

    Negate - (5) -5

  • 8/8/2019 21 Functions CS101

    30/53

    Comparison O perators

    Th e equal to ( == ) Comparison Operator

    if ( today == Sunday )document.write( T he shop is closed );

    Th e string Th e s h op is closed will be written tot h e document only if t h e variable today h as a

    value equal to Sunday

    Not the same as

    the assignment= operator

  • 8/8/2019 21 Functions CS101

    31/53

    Comparison O perators

    a == b T rue if a and b are the same

    a != b T rue if a and b are not the same

    a > b T rue if a is greater than b

    a >= b T rue if a is greater than or equal to b

    a < b T rue if a is less than b

    a

  • 8/8/2019 21 Functions CS101

    32/53

    Example

    if ( x != 0 )result = y / x;

    elseresult = not defined ;

  • 8/8/2019 21 Functions CS101

    33/53

    From comparison operators, we

    move to Logical O perators

  • 8/8/2019 21 Functions CS101

    34/53

    Logical O peratorsO perate on Boolean expressions or variables

    Th e AND ( && ) L ogical Operator

    if ( (pitch == hard ) && (bowler == fast ) )myStatus = Pulled muscle ;

    Th e value of t h e variable myStatus will be set toPulled muscle if bot h of t h e conditions are true

  • 8/8/2019 21 Functions CS101

    35/53

    Logical O perators

    a && b AND T rue if both are true

    a || b O R T rue of either or both are true

    !a N OT T rue if a is false

  • 8/8/2019 21 Functions CS101

    36/53

    Example

    if ( x || y )document.write ( Either or both are true );

    elsedocument.write ( Both are false );

  • 8/8/2019 21 Functions CS101

    37/53

    So far we have looked at the assignment operator,arithmetic operators, comparison operators andlogical operators

    T he final category that we are going to look at isstring operators

    In that category, we look at only one, theconcatenation operator

  • 8/8/2019 21 Functions CS101

    38/53

    T he + String O perator

    Th e + operator can be used to concatenate twostrings

    title = bhola + continental

    Th e value of t h e variable title becomes

    b h olacontinental

  • 8/8/2019 21 Functions CS101

    39/53

    Semicolon ;

    T erminate all JavaScript statements witha semicolon. It is not always necessary ,but highly recommended.

    a = 23 ;quotient = floor( a / 2) ;remainder = a % 2 ;

  • 8/8/2019 21 Functions CS101

    40/53

    Elements of JavaScript Statements

    b = 2;

    sum = sum + 49 ;

    name = Bhola + Continental ;

    x = M ath.floor ( x );

    Identifiers

    O perators

    Literals

    Punctuation

  • 8/8/2019 21 Functions CS101

    41/53

    T wo more elements that are found inJavaScript statements are whitespaces and line breaks

  • 8/8/2019 21 Functions CS101

    42/53

    White Spaces & Line Breaks

    White spaces: T he space & the tab characters

    JavaScript ignores any extra white spaces or line

    breaks that you put in the code

    T his gives you the freedom of using them for making your code appear neat and readable

  • 8/8/2019 21 Functions CS101

    43/53

    while ( x > 0) {remaind = x % 2;y = remaind + y;

    }

    while ( x > 0) {remaind = x % 2; y = remaind + y;}

    while ( x > 0) {remaind = x % 2;

    y = remaind + y;}

  • 8/8/2019 21 Functions CS101

    44/53

    Now lets talk about a very special

    type of JavaScript statement thatdoes not really do anything , but isfound in most pieces of code!

  • 8/8/2019 21 Functions CS101

    45/53

    Comments

    Comments are included on a Web page to explainhow and why you wrote the page the way you did

    Comments can help someone other than theauthor to follow the logic of the page in the authorsabsence

    T he commented text is neither displayed in thebrowser nor does it have any effect on the logicalperformance of the Web page, and is visible only

    when the actual code is viewed

  • 8/8/2019 21 Functions CS101

    46/53

    JavaScript Comments

    Single-line comments (two options)// Author: Bhola

  • 8/8/2019 21 Functions CS101

    47/53

    HTM L Comments

  • 8/8/2019 21 Functions CS101

    48/53

    commentsadd clarity!

  • 8/8/2019 21 Functions CS101

    49/53

    comments let the code speak

    for itself!

  • 8/8/2019 21 Functions CS101

    50/53

    x = 75 ; // x is the decimal number y = ; // y is the binary equivalentwhile ( x > 0) {

    remainder = x % 2 ;quotient = M ath.floor( x / 2 ) ;y = remainder + y ;x = quotient ;

    }

    document.write( y = + y) ;

    Decimal to Binary Conversion in JavaScript

  • 8/8/2019 21 Functions CS101

    51/53

    Assignment #7 (1)

    M odify the Web page that you built for assignment#4 so that it has the following additional interactivityfeatures :

    1. When the mouse goes over the SendM essage button, the Web page should check if any of the two fields is empty

    2. If a field is found empty , an appropriate alertmessage should be shown to the user

  • 8/8/2019 21 Functions CS101

    52/53

    Assignment #7 (2)

    3. T he alert must specify the name of the emptyfield

    4. If none of the fields are empty, and the user clicks on the Send M essage button, display amessage thanking the user for sending you thegreeting

    Deadline: 1:00pm, Friday, 22 O ctober 2004Details will be posted on the CS101 Web Site

  • 8/8/2019 21 Functions CS101

    53/53

    During T odays Lecture

    We looked at functions and their use for solving simple problems

    We became familiar with the concept of local and global variables