Functions, Randomness and Libraries

Similar documents
A Balanced Introduction to Computer Science, 3/E

A Balanced Introduction to Computer Science, 3/E David Reed, Creighton University 2011 Pearson Prentice Hall ISBN

A Balanced Introduction to Computer Science, 3/E


Lecture 14. Introduction to JavaScript. Mr. Mubashir Ali Lecturer (Dept. of Computer Science)

The Math Class. Using various math class methods. Formatting the values.

JAVASCRIPT BASICS. JavaScript Math Functions. The Math functions helps you to perform mathematical tasks

Coding in JavaScript functions

Anatomy of a Function. Pick a Name. Parameters. Definition. Chapter 20: Thinking Big: Programming Functions

JavaScript Basics. The Big Picture

Princess Nourah bint Abdulrahman University. Computer Sciences Department

CS1046 Lab 4. Timing: This lab should take you 85 to 130 minutes. Objectives: By the end of this lab you should be able to:

AP CS Unit 3: Control Structures Notes

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Introduction to Computer Science Unit 2. Notes

Chapter 5 Methods / Functions

CS110: PROGRAMMING LANGUAGE I

Project 2: After Image

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,

Random number generation, Math object and methods, HTML elements in motion, setinterval and clearinterval

Lecture 6: While Loops and the Math Class

A Balanced Introduction to Computer Science, 3/E

Lab 8 CSE 3,Fall 2017

Task 1. Set up Coursework/Examination Weights

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

LAB: INTRODUCTION TO FUNCTIONS IN C++

AP Computer Science A. Return values

Working with JavaScript

AP Computer Science. Return values, Math, and double. Copyright 2010 by Pearson Education

Chapter 5 Methods. Modifier returnvaluetype methodname(list of parameters) { // method body; }

A Balanced Introduction to Computer Science, 3/E David Reed, Creighton University 2011 Pearson Prentice Hall ISBN

12. Numbers. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

C Functions. 5.2 Program Modules in C

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)

CISC 110 Week 3. Expressions, Statements, Programming Style, and Test Review

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

COMS 469: Interactive Media II

Building Java Programs

Building Java Programs

HTML5 and CSS3 More JavaScript Page 1

Chapter 5 Methods. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Chapter 6 Methods. Dr. Hikmat Jaber

Introduction to. Copyright HKTA Tang Hin Memorial Secondary School 2016

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

Lesson 6: Introduction to Functions

Building Java Programs

introjs.notebook March 02, 2014

Such JavaScript Very Wow

Downloaded from Chapter 2. Functions

Instructor s Notes Web Programming JavaScript Functions. Web Programming JavaScript Functions

Time series in html Canvas

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Building Java Programs

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

Like most objects, String objects need to be created before they can be used. To create a String object, we can write

Chapter 5 Methods. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

Functions. Systems Programming Concepts

Introduction to Computer Science Unit 2. Notes

c122mar413.notebook March 06, 2013

Building Java Programs

JAVASCRIPT LESSON 4: FUNCTIONS

CSC Web Technologies, Spring Web Data Exchange Formats

PIC 40A. Midterm 1 Review

Lecture 04 FUNCTIONS AND ARRAYS

CISC 1600 Lecture 2.4 Introduction to JavaScript

S A M P L E C H A P T E R

Building Java Programs

Chapter 4 Statements. Slides Modified by Vicky Seno

Arrays Structured data Arrays What is an array?

Midterms Save the Dates!

JavaScript CS 4640 Programming Languages for Web Applications

TI-84+ GC 3: Order of Operations, Additional Parentheses, Roots and Absolute Value

Lab # 2. For today s lab:

We have written lots of code so far It has all been inside of the main() method What about a big program? The main() method is going to get really

Chapter 1 Introduction to Computers and the Internet

CS-201 Introduction to Programming with Java

LSP 121. LSP 121 Math and Tech Literacy II. Topics. Loops. Loops. Loops

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

Lesson 7: If Statement and Comparison Operators

Lab 1 Concert Ticket Calculator

CSCE 120: Learning To Code

CSC Web Programming. Introduction to JavaScript

Place User-Defined Functions in the HEAD Section

JavaScript CS 4640 Programming Languages for Web Applications

Chapter 17. Fundamental Concepts Expressed in JavaScript

PES DEGREE COLLEGE BANGALORE SOUTH CAMPUS 1 K.M. before Electronic City, Bangalore WEB PROGRAMMING Solution Set II

COMP-202: Foundations of Programming. Lecture 4: Methods Jackie Cheung, Winter 2016

Variable Manipulator Driver. Installation and Usage Guide. Revision: 1.0 Date: Monday, July 10, 2017 Authors: Alan Chow

Expr Language Reference

Lab 1. Purpose. Assignment. Action Items/Programming Requirements

Objects and Classes -- Introduction

var num1 = prompt("enter a number between 1 and 12","1"); var promptstring = "What is " + num1 + " times 3?"; var num2 = prompt(promptstring);

CS 110 Exam 2 Spring 2011

Object Oriented Methods : Deeper Look Lecture Three

INFS 2150 Introduction to Web Development and e-commerce Technology. Programming with JavaScript

Objectives. Introduction to JavaScript. Introduction to JavaScript INFS Peter Y. Wu, RMU 1

CSCE 120: Learning To Code

Programming language components

JavaScript: Tutorial 5

Transcription:

Functions, Randomness and Libraries 1 Predefined Functions recall: in mathematics, a function is a mapping from inputs to a single output e.g., the absolute value function: -5 5, 17.3 17.3 in JavaScript, a function is applied to inputs via a function call specify the function name, followed by inputs in parentheses num = parsefloat(document.getelementbyid('numbox').value); in addition to parsefloat, JavaScript has numerous predefined mathematical functions the functest.html page allows you to explore these 2 1

Math Functions Math.sqrt determines the square root Math.sqrt(9) 9 = 3 Math.sqrt(12.25) 12.25 = 3.5 Math.max determines the maximum of two values Math.max(12, 8.5) 12 Math.max(-3, -8) -3 Math.pow raises a number to a power Math.pow(2, 10) 2 10 = 1024 Math.pow(2, -1) 2-1 = 0.5 Math.pow(9, 0.5) 9 0.5 = 3 Math.min, Math.abs, Math.round, Math.ceil, Math.floor, 3 Rounding Page uses the Math.round function to round a number to 1 digit Math.round(3.14159*10)/10 Math.round(31.4159)/10 31/10 3.1 4 2

Math.random Math.random generates a pseudo-random number in the range [0 1) pseudo-random refers to the fact that the numbers appear randomly distributed, but are in fact generated by a complex algorithm note: this function has no inputs; it returns a different number each call Math.random() 0.33008525626748814 Math.random() 0.213335955823927 Math.random() 0.8975001737758223 a call to Math.random can be placed in an expression to affect the range 2*Math.random() [0 2) Math.random() + 1 [1 2) 9*Math.random() + 1 [1 10) Math.floor(9*Math.random() + 1) 1, 2, 3,, 9 5 Lucky Number Page displays a random number from the range specified by the text boxes 6 3

Simplifying buttons consider the button from lucky1.html: the size of ONCLICK attribute makes the button complex and difficult to read plus, must be careful with nested quotes (" " vs. ' ') functions provide a mechanism for simplifying complex buttons such as this recall: functions minimize the amount of detail that has to be considered e.g., can use Math.sqrt without worrying about how it works functions reduce the length and complexity of code e.g., a single call to Math.sqrt replaces the underlying complex algorithm 7 Simple user-defined functions in addition to JavaScript's predefined functions, the user can define new functions in the HEAD section and call them within the page we will explore user-defined functions fully in Chapter 9 for now, the following simple form suffices for simplifying buttons a function definition begins with the word function followed by its name and () a function name should be descriptive of the task being performed lines beginning with // are comments that describe the function's behavior comments are ignored by the interpreter, but make code more user-readable the statements to be executed when the function is called are placed between the curly braces 8 4

Lucky Number Revisited the code from the button is moved to the userdefined GenerateNumber function SCRIPT tags enclose the function definition in the HEAD as a result, the button is greatly simplified GENERAL ADVICE: if more than one statement is to be associated with a button, define a separate function 9 Example: Dice Simulation suppose we wanted to simulate the roll of a 6-sided die at the click of a button, see a randomly selected roll of a die can use Math.random and Math.floor to generate a random roll between 1 & 6 roll = Math.floor(Math.random()*6) + 1; die images are stored as http://balance3e.com/images/die1.gif, http://balance3e.com/images/die2.gif,, http://balance3e.com/images/die6.gif 10 5

Example: Dice Simulation the desired die image can be selected using the roll variable ' /die' + roll + '.gif' 11 Example: Slide Show the dice simulation page can be generalized into a random slide show name the slide images using a consistent naming scheme slide1.jpg, slide2.jpg, slide3.jpg, each time the button is clicked, the SelectImage function is called to randomly change the image to select a random slide at the start, make use of the ONLOAD attribute of the BODY tag <body onload="code_to_execute_after_page_loads"> here, call SelectImage after the page loads in order to start with a random image <body onload="selectimage();"> 12 6

Example: Banner Ads the random slide show page can be generalized into random banner ads name the ad images using a consistent naming scheme ad0.jpg, ad1.jpg, ad2.jpg, the SelectAd function changes the ad to a random image instead of calling the function at the click of a button, can automate using the predefined setinterval function setinterval('javascript_function_call', INTERVAL_IN_MSEC) sets a timer and repeatedly executes the specified function at set intervals <body onload="setinterval('selectad()', 5000);"> will call the function to change the ad image every half second 13 Example: Banner Ads 14 7

Abstraction abstraction is the process of ignoring minutiae and focusing on the big picture in modern life, we are constantly confronted with complexity we don't necessarily know how it works, but we know how to use it e.g., how does a TV work? a car? a computer? we survive in the face of complexity by abstracting away details to use a TV/car/computer, it's not important to understand the inner workings we ignore unimportant details and focus on those features relevant to using it e.g., TV has power switch, volume control, channel changer, JavaScript functions (like Math.sqrt) provide computational abstraction a function encapsulates some computation & hides the details from the user the user only needs to know how to call the function, not how it works Chapter 7 introduced simple user-defined functions could encapsulate the statements associated with a button, call the function as needed 15 General Function Form to write general-purpose functions, we can extend definitions to include: 1) parameters, 2) local variables, and 3) return statements parameters are variables that correspond to the function s inputs (if any) parameters appear in the parentheses, separated by commas local variables are temporary variables that are limited to that function only if require some temporary storage in performing calculations, then declare local variables using the keyword var, separated by commas a local variable exists only while the function executes, so no potential conflicts with other functions a return statement is a statement that specifies an output value consists of the keyword return followed by a variable or expression 16 8

Declaring Local Variables we have seen that variables are useful for storing intermediate steps in a complex computation within a user-defined function, the programmer is free to create new variables and use them in specifying the function s computation however, by default, new variables used in a function are global (i.e., exist and are accessible anywhere in the page) but what if the same variable name is already used elsewhere? to avoid name conflicts, the programmer should declare temporary variables to be local a variable declaration is a statement that lists all local variables to be used in a function (usually the first statement in a function) general form: var LOCAL_1, LOCAL_2,..., LOCAL_n; 17 ESP Test Page consider a simple ESP test 1. user thinks of a number between 1-4 2. clicks on the button to see the computer's pick number is declared local to picknumber only exists while the function executes 18 9

Functions with Inputs most of the predefined function we have considered expect at least one input e.g., Math.sqrt takes a number as input, and returns its square root as output Math.sqrt(9) 3 e.g., Math.max takes two numbers as inputs, and returns the maximum as output Math.max(7, 3) 7 in English, the word parameter refers to some aspect of a system that can be varied in order to control its behavior in JavaScript, a parameter is a variable (declared inside the function's parentheses) whose value is automatically initialized to the corresponding input value when the function is called parameters allow the same function to perform different (but related) tasks when called with different input values 19 ESP Test Page Revisited better design: have a button for each guess to guess 1, the user clicks the 'Guess 1' button instead of 4 different functions (that behave similarly), have 1 function with a parameter the number corresponding to the guess is passed in as an input, displayed as the guess 20 10

Multiple Inputs if a function has more than one input, parameters in the function definition are separated by commas input values in the function call are separated by commas values are matched to parameters by order 1 st input value in the function call is assigned to the 1 st parameter in the function 2 nd input value in the function call is assigned to the 2 nd parameter in the function... <input type="button" value="cow Verse" onclick="oldmacverse('cow', 'moo');"> 21 Parameters and Locals parameters play an important role in functions they facilitate the creation of generalized computations i.e., the function defines a formula, but certain values within the formula can differ each time the function is called parameters are special instances of local variables when the function is called, memory cells are allocated for the parameters and each input from the call is assigned to its corresponding parameter once a parameter has been assigned a value, you can refer to that parameter within the function just as you would any other variable when the function terminates, the parameters go away, and their associated memory cells are freed parameters are declared and initialized automatically do not declare them as local variables 22 11

Functions with Return displaying results using an INNERHTML assignment or alert is OK for some functions for full generality, we need to be able to return an output value, which can then be used in other computations e.g., number = Math.sqrt(9); cm = InchesToCentimeters(in); a return statement can be added to a function to specify its output value when the return statement is reached, the variable or expression is evaluated and its value is returned as the function's output general form: return OUTPUT_VALUE; 23 Function Libraries functions such as InchesToCentimeters can be added to the HEAD of a page tedious if the function is to be used in many pages involves creating lots of copies that all must be maintained for consistency the alternative for general purpose functions is to place them in a library file a library file is a separate text file that contains the definitions of one or more JavaScript functions it can be loaded into any page by adding an HTML element to the HEAD <script type="text/javascript" src="library_filename"><script> advantages of library files: avoids duplication (only one copy of the function definition) makes it easy to reuse functions (simply load the library file into any page) makes it easy to modify functions (a single change to the library file automatically affects all pages that load the library 24 12

Conversion Page the convert.js library file is loaded into the page this makes the InchesToCentimeters function accessible within the page since ConvertToCm is specific to this page, it directly in the HEAD (as opposed to a library file) 25 random.js Library the random.js library contains useful functions for generating random values any page can utilize the functions by first loading the random.js library <script type="text/javascript" src="http://balance3e.com/random.js"> </script> for example, could revise the ESP Test page to use RandomInt: number = RandomInt(1, 4); 26 13

Errors to Avoid When beginning programmers attempt to load a JavaScript code library, errors of two types commonly occur: 1. if the SCRIPT tags are malformed or the name/address of the library is incorrect, the library will fail to load this will not cause an error in itself, but any subsequent attempt to call a function from the library will produce Error: Object Expected (using Internet Explorer) or Error: XXX is not a function (using Firefox), where XXX is the entered name 2. when you use the SRC attribute in a pair of SCRIPT tags to load a code library, you cannot place additional JavaScript code between the tags think of the SRC attribute as causing the contents of the library to be inserted between the tags, overwriting any other code that was erroneously placed there <script type="text/javascript" src="filename"> ANYTHING PLACED IN HERE WILL BE IGNORED </script> if you want additional JavaScript code or another library, you must use another pair of SCRIPT tags 27 Designing Functions functions do not add any computational power to the language a function definition simply encapsulates other statements still, the capacity to define and use functions is key to solving complex problems, as well as to developing reusable code encapsulating repetitive tasks can shorten and simplify code functions provide units of computational abstraction user can ignore details functions are self-contained, so can easily be reused in different applications when is it worthwhile to define a function? if a particular computation is complex meaning that it requires extra variables and/or multiple lines to define if you have to perform a particular computation repeatedly when defining a function, you must identify the inputs the computation to be performed using those inputs the output 28 14

Design Example consider the task of designing an online Magic 8-ball (Mattell, Inc.) must be able to ask a yes/no type question receive an answer (presumably, at random) could use: a text box for entering the question a DIV element for displaying the answer a clickable image for initiating the action which involves calling a function to process the question, select an answer, and display it in the DIV 29 15