23
CMPS 211 JavaScript CMPS 211 JavaScript Topic 2 Topic 2 Functions and Arrays Functions and Arrays

CMPS 211 JavaScript Topic 2 Functions and Arrays

Embed Size (px)

Citation preview

CMPS 211 JavaScriptCMPS 211 JavaScript

Topic 2Topic 2

Functions and ArraysFunctions and Arrays

2Chapter 20 - Functions and Arrays

OutlineOutline Goals and ObjectivesGoals and Objectives Chapter HeadlinesChapter Headlines IntroductionIntroduction Function DefinitionFunction Definition Function CallsFunction Calls Predefined FunctionsPredefined Functions RecursionRecursion Array Definition and PropertiesArray Definition and Properties Multidimensional ArraysMultidimensional Arrays Array ManipulationsArray Manipulations Associative ArraysAssociative Arrays Functions and ArraysFunctions and Arrays SummarySummary

3Chapter 20 - Functions and Arrays

Goals and ObjectivesGoals and Objectives GoalsGoals

Understand the basics of JavaScript functions and arrays, their Understand the basics of JavaScript functions and arrays, their definitions, their use, their role in automating repetitive tasks, their definitions, their use, their role in automating repetitive tasks, their algorithms, their input, their output, and the use of predefined algorithms, their input, their output, and the use of predefined JavaScript functionsJavaScript functions

ObjectivesObjectives Importance of functions and arraysImportance of functions and arrays Function definition and callingFunction definition and calling RecursionRecursion Array definition and useArray definition and use Array dimensionalityArray dimensionality Array manipulationArray manipulation Objects and associative arraysObjects and associative arrays Practice: use functions and arrays togetherPractice: use functions and arrays together

4Chapter 20 - Functions and Arrays

Topic HeadlinesTopic Headlines 1 1 IntroductionIntroduction

Functions and arrays are great concepts to learnFunctions and arrays are great concepts to learn 2 2 Function DefinitionFunction Definition

A function needs a head and a bodyA function needs a head and a body 3 3 Function CallsFunction Calls

All you need to use is the function headAll you need to use is the function head 4 4 Predefined functionsPredefined functions

Check out how JavaScript helps us use functionsCheck out how JavaScript helps us use functions 5 5 RecursionRecursion

Without recursion, JavaScript life would be difficult Without recursion, JavaScript life would be difficult to repeatto repeat

5Chapter 20 - Functions and Arrays

Topic HeadlinesTopic Headlines 6 6 Array Definition and PropertiesArray Definition and Properties

If you have patterns of data, then arrays are for youIf you have patterns of data, then arrays are for you 7 7 Multidimensional ArraysMultidimensional Arrays

As the patterns get tough, JavaScript has the As the patterns get tough, JavaScript has the solutionssolutions

8 8 Array ManipulationsArray Manipulations Find out what you can do with data patterns one Find out what you can do with data patterns one

defineddefined 9 9 Associative ArraysAssociative Arrays

Who needs these arrays?Who needs these arrays? 10 10 Functions and ArraysFunctions and Arrays

The combination allows you to write serious codeThe combination allows you to write serious code

6Chapter 20 - Functions and Arrays

IntroductionIntroduction Repetitive tasksRepetitive tasks are viewed as algorithms are viewed as algorithms Functions are a Functions are a set of statementsset of statements that take and input, use that take and input, use

the algorithm, and produces an outputthe algorithm, and produces an output Functions make programs Functions make programs modular and portablemodular and portable One can create a One can create a function libraryfunction library to reuse some functions to reuse some functions Array is a complex variableArray is a complex variable that can hold multiple values that can hold multiple values JavaScript uses arrays in a JavaScript uses arrays in a uniqueunique way way Arrays and functions Arrays and functions must be definedmust be defined before we can use before we can use

themthem

7Chapter 20 - Functions and Arrays

Function DefinitionFunction Definition A function definition has two parts:A function definition has two parts:

SignatureSignature specifies function name and input parameters specifies function name and input parametersBodyBody includes any legal JavaScript statements includes any legal JavaScript statements

Signature:Signature:function functionName([param1, param2,…])function functionName([param1, param2,…])Parameters provide Parameters provide input to the functioninput to the function and are optional and are optional

Body:Body:{{ statement 1; statement 1; statement 2; statement 2; return value; return value;}}Body is included between Body is included between two curly bracketstwo curly brackets

A function definition is A function definition is executed only when it is calledexecuted only when it is called

8Chapter 20 - Functions and Arrays

Function CallsFunction Calls Function definitions have to be Function definitions have to be called to be executedcalled to be executed Function call Function call if function returnsif function returns a value: a value:returnValue = functionName(val1, val2, …)returnValue = functionName(val1, val2, …)

Function call Function call if function does not returnif function does not return a value: a value:functionName(val1, val2, …)functionName(val1, val2, …)

The call consists of The call consists of function name and input valuesfunction name and input values known as arguments or parametersknown as arguments or parameters

Arguments in a call Arguments in a call must matchmust match those in the definition those in the definition Function call can be Function call can be placed before or afterplaced before or after the function the function

definitiondefinition Functions can be nestedFunctions can be nested and there is and there is no limit on levelno limit on level of of

nestingnesting

9Chapter 20 - Functions and Arrays

Function CallsFunction Calls Example 20.1Example 20.1: Define and call functions: Define and call functions

Function must take an integer and find numbers divisible by it in Function must take an integer and find numbers divisible by it in the range of 1 to 25the range of 1 to 25

10Chapter 20 - Functions and Arrays

Function CallsFunction Calls Example 20.3Example 20.3: XHTML tags in functions: XHTML tags in functions

Use XHTML tags in a function to format its outputUse XHTML tags in a function to format its output

11Chapter 20 - Functions and Arrays

Predefined FunctionsPredefined Functions JavaScript has JavaScript has several predefined functionsseveral predefined functions eval(string) eval(string) function takes a string and evaluates itfunction takes a string and evaluates it This function is This function is good to check small chunksgood to check small chunks of code of code

quicklyquickly There are two parse functions There are two parse functions parseFloat(string)parseFloat(string) and and parseInt(string)parseInt(string), they , they convert valid string into a convert valid string into a numbernumber

The The escape(string)escape(string) and and unescape(string)unescape(string) allow us allow us to to encode and decode strings respectivelyencode and decode strings respectively

12Chapter 20 - Functions and Arrays

RecursionRecursion Recursion helps in solving a Recursion helps in solving a large class of problemlarge class of problem Recursion is the Recursion is the decomposition of a problemdecomposition of a problem into sub into sub

problems of the same typeproblems of the same type Recursive functions Recursive functions support recursionsupport recursion A recursive function is a A recursive function is a function that calls itselffunction that calls itself JavaScript supportsJavaScript supports recursive functions recursive functions

13Chapter 20 - Functions and Arrays

RecursionRecursion Example 20.4Example 20.4: Use recursive functions: Use recursive functions

Calculate the factorial of a numberCalculate the factorial of a number

14Chapter 20 - Functions and Arrays

Array Definition and PropertiesArray Definition and Properties Array is an Array is an ordered set of values with a single variable ordered set of values with a single variable

namename, , colors=(red, blue, green, yellow)colors=(red, blue, green, yellow) We must We must define arraysdefine arrays as we define variables: as we define variables:myArray = new Array(4)myArray = new Array(4)

Each array has an Each array has an implicit data typeimplicit data type and and must have a namemust have a name It also has a It also has a size that specifies the number of elementssize that specifies the number of elements Array is a Array is a predefined JavaScript objectpredefined JavaScript object Arrays can be Arrays can be initialized initialized when they are definedwhen they are defined Array index is a counterArray index is a counter that locates the array element that locates the array elementmyArray[2]myArray[2] accesses the third element accesses the third element

JavaScript uses JavaScript uses zero-based arrayszero-based arrays, first element index is 0, first element index is 0 Array size Array size defines its boundsdefines its bounds

15Chapter 20 - Functions and Arrays

Array Definition and PropertiesArray Definition and Properties Example 20.5Example 20.5: Use arrays: Use arrays

Calculate the sum of squares of (2, 5, 6, -3, 0, -7, 9, 4)Calculate the sum of squares of (2, 5, 6, -3, 0, -7, 9, 4)

16Chapter 20 - Functions and Arrays

Multidimensional ArraysMultidimensional Arrays Dimensionality is determined by the Dimensionality is determined by the number of bracket number of bracket

pairspairs ( ([][])) Arrays can be Arrays can be n-dimensionaln-dimensional i.e. 2D, 3D, …., nD i.e. 2D, 3D, …., nD 2D array becomes a 2D array becomes a matrix gridmatrix grid, 3D array becomes a , 3D array becomes a

boxbox, further visualization is not possible, further visualization is not possible Each dimension of an array corresponds to an indexEach dimension of an array corresponds to an index for for

its accessibilityits accessibility We can nest array definitionsWe can nest array definitions to create multidimensional to create multidimensional

arrays, for example 2 x 3 array is created asarrays, for example 2 x 3 array is created asarr = new Array(new Array(2), new Array(3));arr = new Array(new Array(2), new Array(3));

The elements of the array can be accessed using The elements of the array can be accessed using arr[i]arr[i][j][j]

17Chapter 20 - Functions and Arrays

Multidimensional ArraysMultidimensional Arrays

18Chapter 20 - Functions and Arrays

Array Definition and PropertiesArray Definition and Properties Example 2.6Example 2.6: Use multidimensional arrays: Use multidimensional arrays

19Chapter 20 - Functions and Arrays

Array ManipulationsArray Manipulations Arrays can be Arrays can be resized, copied, sortedresized, copied, sorted by using predefined by using predefined

functions in JavaScriptfunctions in JavaScript

FunctionFunction DescriptionDescription

reverse()reverse() reverses the order of array elementsreverses the order of array elements

sort()sort() sorts elements in ascending/alphabetical ordersorts elements in ascending/alphabetical order

concat()concat() combines the elements of two arrayscombines the elements of two arrays

slice()slice() slices an array and returns a sub array of itslices an array and returns a sub array of it

20Chapter 20 - Functions and Arrays

Array ManipulationsArray Manipulations Example 20.7Example 20.7: Sorting Arrays: Sorting Arrays

Write a program that sorts string and number arraysWrite a program that sorts string and number arrays

21Chapter 20 - Functions and Arrays

Associative ArraysAssociative Arrays It is an It is an interesting conceptinteresting concept It allows us to It allows us to associate implicit arrays with objectsassociate implicit arrays with objects to to

save their properties and variablessave their properties and variables It requires It requires thorough understanding of objectsthorough understanding of objects and their and their

conceptsconcepts

22Chapter 20 - Functions and Arrays

Functions and ArraysFunctions and Arrays Functions can use arrays Functions can use arrays in their bodiesin their bodies or arrays can be or arrays can be passed passed

into functions as argumentsinto functions as arguments for manipulations and processing for manipulations and processing Example 20.8Example 20.8: Pass arrays to functions: Pass arrays to functions

23Chapter 20 - Functions and Arrays

SummarySummary• Functions and arrays provide a Functions and arrays provide a useful combinationuseful combination in in

programmingprogramming• Function definition has a Function definition has a signature and bodysignature and body• Function callsFunction calls call the function body for execution call the function body for execution• JavaScript has several JavaScript has several predefined functionspredefined functions• JavaScript supports JavaScript supports recursive functionsrecursive functions• Arrays are usefulArrays are useful in many applications in many applications• Arrays can be Arrays can be n-dimensionaln-dimensional• Arrays can be Arrays can be manipulated manipulated using predefined functionsusing predefined functions• Associative arrays is an Associative arrays is an interesting conceptinteresting concept• Function can use arraysFunction can use arrays