JavaScript and Ajax (JavaScript Functions) Week 5 Web site:

Slides:



Advertisements
Similar presentations
JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Advertisements

Tutorial 5 Windows and Frames Section A - Working with Windows.
The Web Warrior Guide to Web Design Technologies
JavaScript Part for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable.
Outline IS400: Development of Business Applications on the Internet Fall 2004 Instructor: Dr. Boris Jukic JavaScript: Introduction to Scripting.
Chapter 6: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
Chapter 6: User-Defined Functions I
JavaScript, Third Edition
2012 •••••••••••••••••••••••••••••••••• Summer WorkShop Mostafa Badr
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
Computers and Scientific Thinking David Reed, Creighton University Functions and Randomness 1.
Introduction to scripting
CNIT 133 Interactive Web Pags – JavaScript and AJAX Functions.
Using Data Active Server Pages Objectives In this chapter, you will: Learn about variables and constants Explore application and session variables Learn.
Using Object-Oriented JavaScript CST 200- JavaScript 4 –
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
SYST Web Technologies SYST Web Technologies Lesson 6 – Intro to JavaScript.
Client Scripting1 Internet Systems Design. Client Scripting2 n “A scripting language is a programming language that is used to manipulate, customize,
Copyright ©2005  Department of Computer & Information Science Using Number & Math Objects.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
1 JavaScript in Context. Server-Side Programming.
Introduction to JavaScript Basharat Mahmood, Department of Computer Science, CIIT, Islamabad, Pakistan. 1.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Functions.
Pemrograman Teknologi Internet W06: Functions and Events.
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
20-753: Fundamentals of Web Programming 1 Lecture 12: Javascript I Fundamentals of Web Programming Lecture 12: Introduction to Javascript.
Chapter 5: Windows and Frames
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
Keeping it Neat: Functions and JavaScript Source Files Chapter 7.
WDMD 170 – UW Stevens Point 1 WDMD 170 Internet Languages eLesson: Variables, Functions and Events (there is an audio component to this eLesson) © Dr.
CS346 Javascript -3 Module 3 JavaScript Variables.
1Computer Sciences Department Princess Nourah bint Abdulrahman University.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
Chapter 2: Variables, Functions, Objects, and Events JavaScript - Introductory.
JavaScript, Fourth Edition
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
XP Tutorial 2 New Perspectives on JavaScript, Comprehensive1 Working with Operators and Expressions Creating a New Year’s Day Countdown Clock.
Java Script About Java Script Document Object Model Incorporating JavaScript Adding JavaScript to HTML Embedding a Javascript External Scripts Javascript.
Chapter 3: User-Defined Functions I
JavaScript: Functions © by Pearson Education, Inc. All Rights Reserved.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Functions Function is a standalone block of statements that performs some tasks and returns a value. Functions must be declared before they can be used.
MIT-AITI: Functions Defining and Invoking Functions Functions as Data Function Scope: The call Object Function Arguments: The arguments objects Function.
Tutorial 11 1 JavaScript Operators and Expressions.
PHP Reusing Code and Writing Functions 1. Function = a self-contained module of code that: Declares a calling interface – prototype! Performs some task.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Invoking methods in the Java library. Jargon: method invocation Terminology: Invoking a method = executing a method Other phrases with exactly the same.
Expressions and Data Types Professor Robin Burke.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
JavaScript Tutorial. What is JavaScript JavaScript is the programming language of HTML and the Web Programming makes computers do what you want them to.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
JavaScript Programming. What Is JavaScript “the most popular programming language in the world”— w3schools.com “the language for HTML, the Web, computers,
REEM ALMOTIRI Information Technology Department Majmaah University.
Chapter 6: User-Defined Functions I
Learning to Program D is for Digital.
Programming the Web using XHTML and JavaScript
JavaScript: Functions
Week#3 Day#1 Java Script Course
4. Javascript Pemrograman Web I Program Studi Teknik Informatika
Week#2 Day#1 Java Script Course
User-Defined Functions
JavaScript and Ajax (Expression and Operators)
Console.
T. Jumana Abu Shmais – AOU - Riyadh
Chapter 20: Programming Functions
Web Programming and Design
Presentation transcript:

JavaScript and Ajax (JavaScript Functions) Week 5 Web site:

Functions A function is a block of JavaScript code that is defined once but may be invoked, or executed, any number of times. Functions may have parameters, or arguments – local variables whose value is specified when the function is invoked. Functions often use these arguments to compute a return value that becomes the value of the function invocation expression. When a function is invoked on an object, the function is called a method, and the object on which it is invoked is passed as an implicit argument of the function.

Types of Functions 1.Predefined functions: predefined by the JavaScript language but not associated with any particular object. [parseInt(), isNaN()] 2.Predefined methods: predefined by the JavaScript and associated with objects that have also been predefined by the language. [window.open(), document.write()] 3.User-defined functions (really user-defined window methods): defined by a programmer. However, when a programmer declare a function in JavaScript, it is actually defining a method of the window object. [helloWorld(), greetVisitor()] 4.User-defined methods: defined by a programmer and associated with a particular object, usually a user-defined object. [pen.write()]

The best function-programming practices 1.A well-written function performs one task and one task alone. 2.A well-written function stands on its own and causes no side effects to variables or objects outside its scope. 3.A well-written function is well documented with comments, including what the function does, what input it requires, and what output, if any, it returns.

(1) Functions Without Parameters A function definition needs to be placed such that the function gets defined and read into memory before it is called to work So, always declare them in the of the HTML document. function functionName() { Statements; } function helloWorld() { document.write("Hello, world!"); }

Calling a Simple Function To call a function that has no parameters, simply invoke its name: functionName(); You can call helloWorld by invoking its name: helloWorld(); If your function will execute any document.write statements, then it must be called within the of an HTML document.

(2) Functions With Parameters The proper syntax for declaring a function with one or more parameters function functionName(param1, param2, …) { statements; } Let’s declare a greetByName function that will accept visitorName as a parameter: function greetByName(visitorName) { alert("Hello, " + visitorName + "!"); } To see if it works, let’s call it. greetByName("Sam"); greetByName("Davan");

(a) Passing by value (primitive data types) Whenever primitive data types (number, string, Boolean) are used as arguments to function calls, those arguments are passed by value, that is, the function receives the actual value of the argument and stores that value in its parameter variable. The value of the variable used as an argument remains unchanged by the function call.

(b) Passing by reference (composite data types) Whenever you pass composite data types such as objects/arrays as arguments to a function, you pass the actual object itself. The parameter name becomes another reference to the object passed; that is, the parameter name becomes another name by which the object can be referred to. Anything you do to the parameter in the function affects the original object.

Pass by Reference Sample function arrayData(drinks) { drinks[0] = "Lemonade"; drinks[1] = "Iced tea"; drinks[2] = "Pepsi"; drinks[3] = "Dr. Pepper"; } var myCups = new Array(); document.write("Content of myCups: ", myCups, " "); arrayData(myCups); document.write("Content after function call: ", myCups, " ");

(3) Functions Return a Value If a function needs to return a value, you need to include a return statement in your function, usually as the last line. A function can have more than one return statement, each defined for a particular condition, but only one return statement can execute and only one value or object can be returned. function functionName(param1, param2, …) { statements; return someValue; }

Function Return a Value Sample function getMax(num1, num2) { if (num1 > num2) { return num1; } else { return num2; } document.write("Max of 8 and 15 is ", getMax(8, 15), " "); document.write("Max of -9 and 17 is ", getMax(-9, 17), " "); document.write("Max of 8 and 8 is ", getMax(8, 8), " "); document.write("Max of 1.1 and 1 is ", getMax(1.1, 1), " ");

Defining and Invoking Functions There are two ways to define JavaScript functions: 1.The most common way to define a function is with the function statement. function f(x) { return x * x; } function factorial(x) { if (x <= 1) { return 1; } return x * factorial(x – 1); } var a = f(2); var b = factorial(3);

Defining and Invoking Functions (continue…) 2.JavaScript allows functions to be defined with function literals. A function literal is an expression that defines an unnamed function. The syntax for a function literal is much like that of the function statement, except that it is used as an expression rather than as a statement and no function name is required. Function literals create unnamed functions which is useful when writing recursive functions that call themselves. Var f1 = function(x) { return x * x; };// function literal var f2 = function(x) { if (x <= 1) return 1; else return x * f2(x – 1); }; var a = f1(2); var b = f2(3);

Naming Functions Any legal JavaScript identifier can be a function name. When a name includes multiple words, one convention is to separate words with underscores like_this(); Another convention is to begin all words after the first with an uppercase letter likeThis(). Functions that are supposed to be internal or hidden are sometimes given names that begin with an underscore.

Creating Libraries in External JavaScript files A function definition can be placed in an external JavaScript file and linked into a document with a script tag in the of the HTML document. Place a bunch of regularly used function definitions in one external JavaScript file and you are got yourself a library. A library is a group of reusable function definitions, usually related to each other in some way.

HTML with external JS file Function with external file document.write("Max of 8 and 15 is ", getMax(8, 15), " "); document.write("Max of -9 and 17 is ", getMax(-9, 17), " "); document.write("Max of 8 and 8 is ", getMax(8, 8), " "); document.write("Max of 1.1 and 1 is ", getMax(1.1, 1), " ");

Content of the external file – myscript.js function getMax(num1, num2) { if (num1 > num2) { return num1; } else { return num2; }

JavaScript built-in functions window has two common methods setTimeout() and setInterval(). The window method setTimeout lets you call a function after a specified number of milliseconds have elapsed. It allows you to set a timer that calls a JavaScript statement or function after a certain period of time. setTimeout("statement", numMilliseconds); setTimeout("functionName()", numMilliseconds);

Built-in function – setTimeout() var reminder; function displayAlert() { alert("5 seconds have elapsed."); } function callTimer() { reminder = setTimeout("displayAlert()", 5000); } Click the button on the left for a reminder in 5 seconds; click the button on the right to cancel the reminder before it is displayed.

setTimeout() and clearTimeout() The setTimeout() will return an integer representing the timeout’s unique identification. By assigning the returned ID to a variable, you can control the time-out, stopping it if necessary. If you don’t assign the value returned by setTimeout to a variable when it is called, you will have no way to identify the time-out so you can tell it to stop. var timerName = setTimeout("functionName()", numMilliseconds); clearTimeout(timerName);

setInterval() and clearInterval() var reminder; function displayAlert() { alert("5 seconds have elapsed."); } function callTimer() { reminder = setInterval("displayAlert()", 5000); } Click the button on the left for a repeated reminder every 5 seconds; click the button on the right to cancel the reminder before it is displayed.

setInterval() and clearInterval() (continue…) The window method, setInterval differs from its cousin and predecessor setTimeout in that it repeatedly calls a statement or function every so many milliseconds. setInterval("statement/functionName", numMilliseconds); Syntax for saving an interval’s unique ID: var timerName = setInterval("functionName()", numMilliseconds); Syntax for using clearInterval(): clearInterval(timerName);

Built-in function – Math Object The Math object is a built-in JavaScript object that includes math constants and functions.  Math.ceil(): rounds a number up to the next integer.  Math.floor(): rounds a number down to the next integer.  Math.round(): rounds a number to the nearest integer.  Math.sin(): calculate sines.  Math.cos(): calculate cosines.  Math.PI: is a property, Mathematical constants PI.  Math.random(): generate a random decimal number between zero and one.