Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

JavaScript User Defined Functions: Abstraction and Temperature Conversion, Slides of Artificial Intelligence

How to define and use user-defined functions in javascript, focusing on temperature conversion from fahrenheit to celsius. It covers the concept of functions as abstractions, user-defined functions, function parameters, and local variables. The document also discusses why and when to define functions, and provides an example of a function without a return statement for displaying verses of a song.

Typology: Slides

2012/2013

Uploaded on 04/24/2013

banani
banani 🇮🇳

4.3

(3)

91 documents

1 / 5

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
CSCI 100
Think Like Computers
Lecture 16
Fall 2008
Last Time …
JavaScript: numbers, variables,
expressions
Math functions
Write statement: document.write(…)
prompt(…,…)
parseFloat(…)
Abstraction
JavaScript functions (like Math.sqrt) provide
computational 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, …
Functions as Abstractions
JavaScript functions (like Math.sqrt) provide
computational abstraction
a function encapsulates some comp utation & hides
the details from the user
the user only needs to know how to call the function,
not how it works
in order to create our own abstractions, we must learn
how functions work
User Defined Functions
JavaScript’s predefined functions represent a
collection of useful, general-purpose
abstractions
the programmer can add additional abstractions via
user-defined functions
once defined, a user-defined function can be used the
same way as a predefined function
e.g., consider converting a temperature from
Fahrenheit to Celsius
tempInCelsius = (5/9) * (tempInFahr - 32);
User Defined Functions
this expression & assignment could be used whenever
we want to convert
requires remembering the formula every time
instead, we could define a function to encapsulate the
calculation
could then call that function whenever a conversion was
needed
freezing = FahrToCelsius(32);
current = FahrToCelsius(78);
function FahrToCelsius(tempInFahr)
// Assumes: tempInFahr is a temperature in Fahrenheit
// Returns: the equivalent temperature in Celsius
{return (5/9) * (tempInFahr - 32);
}
Docsity.com
pf3
pf4
pf5

Partial preview of the text

Download JavaScript User Defined Functions: Abstraction and Temperature Conversion and more Slides Artificial Intelligence in PDF only on Docsity!

CSCI 100

Think Like Computers

Lecture 16

Fall 2008

Last Time …

• JavaScript: numbers, variables,

expressions

• Math functions

• Write statement: document.write(…)

• prompt(…,…)

• parseFloat(…)

Abstraction

  • JavaScript functions (like Math.sqrt) provide

computational 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, …

Functions as Abstractions

• 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

Š in order to create our own abstractions, we must learn

how functions work

User Defined Functions

• JavaScript’s predefined functions represent a

collection of useful, general-purpose

abstractions

Š the programmer can add additional abstractions via

user-defined functions

Š once defined, a user-defined function can be used the

same way as a predefined function

Š e.g., consider converting a temperature from

Fahrenheit to Celsius

tempInCelsius = (5/9) * (tempInFahr - 32);

User Defined Functions

  • this expression & assignment could be used whenever

we want to convert

Š requires remembering the formula every time

  • instead, we could define a function to encapsulate the

calculation

  • could then call that function whenever a conversion was

needed

freezing = FahrToCelsius(32); current = FahrToCelsius(78);

function FahrToCelsius(tempInFahr) // Assumes: tempInFahr is a temperature in Fahrenheit // Returns: the equivalent temperature in Celsius { return (5/9) * (tempInFahr - 32); }

User Defined Functions

function FahrToCelsius(tempInFahr) // Assumes: tempInFahr is a temperature in Fahrenheit // Returns: the equivalent temperature in Celsius { return (5/9) * (tempInFahr - 32); }

• the 1

st

line specifies that we are defining a

function named FahrToCelsius that takes one

input

Š the variable name in parentheses is known as a

parameter

Š when the function is called, the provided input is

assigned to the parameter

e.g., for the call FahrToCelsius(32), the value 32 would

be assigned to tempInFahr for the calculation

User Defined Functions

function FahrToCelsius(tempInFahr) // Assumes: tempInFahr is a temperature in Fahrenheit // Returns: the equivalent temperature in Celsius { return (5/9) * (tempInFahr - 32); }

• the 2nd^ and 3rd^ lines are comments that describe

the behavior of the function

Š anything to the right of // is ignored by the browser

(so not strictly required)

Š but, you should ALWAYS have comments in any

user-defined function to make the code easier to read

and understand

User Defined Functions

function FahrToCelsius(tempInFahr) // Assumes: tempInFahr is a temperature in Fahrenheit // Returns: the equivalent temperature in Celsius { return (5/9) * (tempInFahr - 32); }

• the actual code that carries out the function's

computation is enclosed in { }

Š here, the function definition contains only one

statement, but could be more

Š a return statement specifies the value that should be

returned by the function (i.e., it's output)

General Function Form

  • in general, the form of a user-defined function is as

follows:

Š function names follow the same rules as variables: consist of letters, digits, and underscores and must start with a letter Š note that there may be: ƒ more than one parameter, separated by commas ƒ no parameters at all, in which case the function name is followed by () ƒ more than one statement inside the curly braces (more later)

function FUNCTION_NAME(PARAMETER_1, PARAMETER_2,..., PARAMETER_n) // Assumes: DESCRIPTION OF ASSUMPTIONS MADE ABOUT PARAMETERS // Returns: DESCRIPTION OF VALUE RETURNED BY FUNCTION { STATEMENTS_TO_PERFORM_(AND_RETURN)_THE DESIRED_COMPUTATION; }

Example

function difference(num1, num2) // Assumes: num1 and num2 are numbers // Returns: the absolute difference between num1 and num { return Math.abs(num1 – num2); }

Temperature Conversion Page

  • to include a user-defined function in a page, the simplest way is to include its definition in SCRIPT tags in the HEAD Š once the function is defined in the HEAD, it can be called just like any other function

note: if a page requires more than one user- defined function, they can all be enclosed in the same pair of SCRIPT tags

Designing Functions

  • 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 within a page

  • when defining a function, you must identify

Š the inputs Š the computation to be performed using those inputs Š the output

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
  • Technically, a parameter is a local variable, meaning it

exists only inside its particular function

Š 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 and Locals

  • variables that appear in the BODY of the page are global

variables, meaning they exist and can be accessed by

JavaScript code anywhere in the page

Š note: it is possible to use the same name to refer to a local variable and a global variable ƒ within the function, the local variable is accessible ƒ outside that function, the global variable is accessible

Local vs. Global

  • here, the variable names animal and sound are Š used for parameters in the function definition (local variables)

Š used for variables in the BODY (global variables)

  • we can think of these as completely separate variables, identifiable via a subscript Š animal (^) OldMacVerse and soundOldMacVerse are used in the function Š animal (^) BODY and soundBODY are used in the BODY

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 ƒ but what if the same variable name is already used elsewhere?

Declaring Local Variables

function IncomeTax(income, itemized) // Assumes: income >= 0, itemized >= 0 // Returns: flat tax (13%) due after deductions { var deduction, taxableIncome, totalTax; deduction = Math.max(itemized, 4150); taxableIncome = Math.max(income - deduction, 0); totalTax = 0.13*taxableIncome

return totalTax; }

  • to avoid name conflicts, the programmer can declare

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;

random.js

  • general-purpose functions can be grouped together in a

library

Š a library is a text file that contains one or more function definitions Š once the functions are defined in the library, that library can be loaded into pages as needed

  • e.g., the random.js library contains useful functions for

generating random values

random.js

  • to load a library of functions in a page, use a special pair

of SCRIPT tags

  • -

Using random.js

  • in the page below, the random.js library is accessed via the Web

Š you can download the file and store it on your own machine Š then, simply specify the file name in the SRC attribute (the default is that the file is in the same folder as the Web page that includes it)

Errors to Avoid

  • When beginning programmers attempt to load a JavaScript code library, errors of two types commonly occur:

‡ 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 Navigator), where XXX represents the typed function name

Errors to Avoid

‡ 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

‡ if you want additional JavaScript code or another library, you must use another pair of SCRIPT tags