Coding in JavaScript functions

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

A.A. 2008/09. Why introduce JavaScript. G. Cecchetti Internet Software Technologies

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

HTML5 and CSS3 More JavaScript Page 1

LECTURE-2. Functions review HTML Forms. Arrays Exceptions Events. CS3101: Scripting Languages: Javascript Ramana Isukapalli

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

Functions, Randomness and Libraries

CITS1231 Web Technologies. JavaScript Math, String, Array, Number, Debugging

The first sample. What is JavaScript?

Such JavaScript Very Wow

Princess Nourah bint Abdulrahman University. Computer Sciences Department

CSC Web Programming. Introduction to JavaScript

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

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University


write vs. writeln Prompting as Page Loads Today s Goals CSCI 2910 Client/Server-Side Programming Intermediate File vs. HTML Output

Client-Side Web Technologies. JavaScript Part I

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

CS110: PROGRAMMING LANGUAGE I

334 JavaScript/JScript: Functions Chapter 11. boss. worker1 worker2 worker3. Hierarchical boss function/worker function relationship.

Chapter 4 Mathematical Functions, Characters, and Strings

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

Chapter 1 Introduction to Computers and the Internet

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

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

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

Princeton University COS 333: Advanced Programming Techniques A Subset of JavaScript

Full file at

Chapter 3 - Simple JavaScript - Programming Basics. Lesson 1 - JavaScript: What is it and what does it look like?

Princeton University COS 333: Advanced Programming Techniques A Subset of JavaScript

AP Computer Science A. Return values

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

JavaScript: More Syntax

COMS 469: Interactive Media II

Pace University. Fundamental Concepts of CS121 1

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

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

JavaScript Basics. The Big Picture

Lecture 6: While Loops and the Math Class

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

CMPT 100 : INTRODUCTION TO

Chapter 2: Using Data

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

Introduction to Computer Science Unit 2. Notes

3 The Building Blocks: Data Types, Literals, and Variables

JavaScript for PHP Developers

Computer Programming I - Unit 2 Lecture 1 of 13

Introduction to Computer Science Unit 2. Notes

Types and Expressions. Chapter 3

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

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Methods (Deitel chapter 6)

Methods (Deitel chapter 6)

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017

Module 4: Characters, Strings, and Mathematical Functions

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

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

Chapter 5 Methods / Functions

Calculations, Formatting and Conversions

JAVASCRIPT BASICS. Type-Conversion in JavaScript. Type conversion or typecasting is one of the very important concept in

Chapter 16. JavaScript 3: Functions Table of Contents

Lesson 7: If Statement and Comparison Operators

Introduction to JavaScript

Working with JavaScript

Variables, Constants, and Data Types

The JavaScript Language

Variables and Typing

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

AP CS Unit 3: Control Structures Notes

Chapter 5 - Methods Prentice Hall, Inc. All rights reserved.

<form>. input elements. </form>

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

Chapter 2 Working with Data Types and Operators

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

Outline. Data and Operations. Data Types. Integral Types

Object Oriented Methods : Deeper Look Lecture Three

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

Important Java terminology

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

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

JavaScript: Functions Pearson Education, Inc. All rights reserved.

! Widely available. ! Widely used. ! Variety of automatic checks for mistakes in programs. ! Embraces full set of modern abstractions. Caveat.

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

Lecture 2: Intro to Java

Building Java Programs

JAVASCRIPT LESSON 4: FUNCTIONS

Input File Syntax The parser expects the input file to be divided into objects. Each object must start with the declaration:

Building Java Programs

CGS 3066: Spring 2015 JavaScript Reference

Programming language components

By the end of this section of the practical, the students should be able to:

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Installing and Using the Cisco Unity Express Script Editor

Full file at

Building Java Programs

PIC 40A. Lecture 10: JS: Wrapper objects, Input and Output, Control structures, random numbers. Copyright 2011 Jukka Virtanen UCLA 1 04/24/17

Lab 3 - Pizza. Purpose. Assignment

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

REVIEW. while (condition) { <body> for (<init> ; <condition> ; <increment>) { } if (condition) { <command> } else { <command> }

Java Classes: Math, Integer A C S L E C T U R E 8

Transcription:

Coding in JavaScript functions A function contains code that will be executed by an event or by a call to the function. You may call a function from anywhere within a page (or even from other pages if the function is embedded in an external.js file). Functions can be defined both in the <head> and in the <body> section of a document. However, to assure that a function is read/loaded by the browser before it is called, it could be wise to put functions in the <head> section. How to Define a Function Syntax function functionname(var1,var2,...,varx) some code The parameters var1, var2, etc. are variables or values passed into the function. The and the defines the start and end of the function. Note: A function with no parameters must include the parentheses () after the function name. Note: Do not forget about the importance of capitals in JavaScript! The word function must be written in lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a function with the exact same capitals as in the function name. Invoking Functions Defining a function doesn`t execute it. You have to call the function for it to do its work. You can invoke (or call) any function defined in the current page. You can also invoke functions defined by other named windows or frames. You should invoke a function by name. The name needs to be followed by a set of parentheses that contain zero or more values to be passed to the function. The number of values being passed should be equal to the number of arguments the function has. The values are assigned to the arguments in the order in which they appear in the list. JavaScript Function Example Example function displaymessage() println("hello World!"); displaymessage();

The return Statement The return statement is used to specify the value that is returned from the function. So, functions that are going to return a value must use the return statement. The example below returns the product of two numbers (a and b): Example function product(a,b) return a*b; println(product(4,3)); The Lifetime of JavaScript Variables If you declare a variable, using "var", within a function, the variable can only be accessed within that function. When you exit the function, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in different functions, because each is recognized only by the function in which it is declared. If you declare a variable outside a function, all the functions on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed. More Examples A function can even be recursive, that is, it can call itself. For example, here is a function that computes factorials: function factorial(n) if ((n == 0) (n == 1)) return 1; else result = (n * factorial(n-1) ) return result; You could then display the factorials of one through 10 as follows: for (i = 0; i < 10; i++) println( +i+" factorial is: "+factorial(i)); Some JavaScript Predefined Functions This section discusses JavaScript predefined functions such as escape, unescape, eval, isnan, tostring, alert, and others.

Conversion and Comparison escape(string) - Encodes a string from ASCII into an ISO Latin-1 (ISO 8859-1) character set which is suitable for HTML processing. It is passed the string to be encoded, and returns the encoded string. unescape - Converts an ISO8859-1 character set to ASCII. If a string is "My phone # is 123-456-7890", after the escape function, it is "My%20phone%20%23%20is%20123-456-7890". After unescape, it is "My phone # is 123-456-7890". eval()- Converts a string to integer or float value. It can also evaluate expressions included with a string. In the example, value1 becomes 62. value1 = eval("124/2"), isnan(value) - If the value passed is a not a number, the boolean value of true is returned, if it is a number, it returns false. if (isnan(string1)) document.write("string1 is not a number\n"); else document.write(string1 is a number\n"); parsefloat() - Returns floating point numbers the same as the parseint function, but looks for floating point qualified strings and returns their value as a float. The first line below returns a value of 123, and the second line returns 9.683. value1 = parsefloat("123") value2 = parsefloat("9.683") parseint()- Converts a string to an integer returning the first integer encountered which is contained in the string. In the example, value1 becomes 12. value1 = parseint("12b13"), If no integer value were found such as in the string "abcd", then a value of 0 is returned. Methods that belong to all objects tostring() - Converts an object to a string. The syntax is shown below. Radix is the base value for the conversion, which may be 10 for decimal conversion. The value 1 is used for binary conversion, and 8 is used for octal conversion. object.tostring(radix) Dialog Boxes

alert(message) - Displays an alert box with a message defined by the string message. Example: println("an error occurred!") confirm(message) - When called, it will display the message and two boxes. One box is "OK" and the other is "Cancel". If OK is selected, a value of true is returned, otherwise a value of false is returned. An example: if (confirm("select OK to continue, Cancel to abort")) println("continuing") else println("operation Canceled") prompt(message) - Displays a box with the message passed to the function displayed. The user can then enter text in the prompt field, and choose OK or Cancel. If the user chooses Cancel, a NULL value is returned. If the user chooses OK, the string value entered in the field is returned. An example: var response=prompt("enter your name") if (response!= null) println(response) Predefined Core JavaScript Functions The predefined core JavaScript functions are listed below. decodeuri() decodeuricomponent() encodeuri() encodeuricomponent() escape() unescape() eval() isfinite() isnan() Number() parsefloat() parseint() tostring() watch() unwatch() With the exception of watch() and unwatch(), you have already learned enough to be able to make use of all these functions. The watch() and unwatch() functions work with things called "object properties" to help in debugging. (As object properties are quite an advanced topic, and we haven't yet covered objects).

All these built-in functions either check or modify data in some way or another. To find out more details about each of these functions, go to the following URL: http://www.informit.com/articles/article.aspx?p=29797&seqnum=3 Mathematical Functions JavaScript provides an extensive library of predefined mathematical functions, including square root (Math.sqrt) and maximum (Math.max). These functions all have names beginning with the prefix "Math.", signifying that they are part a library of mathematical routines. (Technically speaking, Math is the name of a JavaScript object that contains these functions -- we will discuss objects later.) When calling a function in JavaScript, the function name is written first, followed by the arguments in parentheses. For example, the call Math.sqrt(25) would return the value 5, while Math.max(4, 7) would return 7. The arguments to a function can be any valid JavaScript values, including expressions and variables. Thus, the calls Math.sqrt(3*4 + 13) and Math.max(2+2, 42/6) would similarly return 5 and 7, respectively. Other Math functions in JavaScript Math.abs Math.min Math.floor Math.ceil Math.round Math.pow Math.random For more details on JavaScript s built-in or core functions, including those for Math, refer to this URL: http://www.tutorialspoint.com/javascript/javascript_builtin_functions.htm