reusable parts of code doncho minkov telerik software academy academy.telerik.com technical trainer

50
Functions Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik .com Technical Trainer http://minkov.it

Upload: osborne-chambers

Post on 28-Dec-2015

223 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

FunctionsReusable parts of Code

Doncho Minkov

Telerik Software Academyacademy.telerik.com

Technical Trainerhttp://minkov.it

Page 2: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Table of Contents

Functions Overview Declaring and Creating Functions Calling Functions Functions with Parameters Examples: Functions With Parameters

Print the Sign of Number

Period Between Months

Printing a Triangle of Numbers 2

Page 3: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Table of Contents (2)

Returning Values From Functions Examples: Returning Values From Functions

Temperature Conversion

Positive Numbers

Data Validation

3

Page 4: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Functions OverviewWhat is a function?

4

Page 5: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

What is a Function?

A function is a kind of building block that solves a small problem

A piece of code that has a name and can be called from the other code

Can take parameters and return a value

Functions allow programmers to construct large programs from simple pieces

Functions are also known as methods, procedures, and subroutines

5

Page 6: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Why to Use Functions? More manageable programming

Split large problems into small pieces

Better organization of the program Improve code readability Improve code understandability

Avoiding repeating code Improve code maintainability

Code reusability Using existing functions several

times

6

Page 7: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Functions in JavaScript

7

Page 8: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Declaring and Creating Functions

Page 9: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Functions in JavaScript

Functions are first-class objects They are objects and can be

manipulated and passed around like just like any other object

They are actually Function objects.

Page 10: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Declaring and Creating Functions

Each function has a name It is used to call the Function

Describes its purpose

10

fucntion printLogo(){ console.log("Telerik Corp."); console.log("www.telerik.com");}

Function

name

Page 11: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

function printLogo(){ console.log("Telerik Corp."); console.log("www.telerik.com");}

11

Each function has a body It contains the programming code

Surrounded by { and }

Function body

Declaring and Creating Functions (2)

Page 12: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Declaring and Creating Functions

Live Demo

12

Page 13: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Ways of Defining a Function

Functions can be defined in four ways: By using the constructor of the

Function object

By function declaration

By function expression with anonymous function

By function expression with named function

13

var print = new Function("console.log('Hello')");

Function print() {console.log('Hello')};

var print = function() {console.log('Hello')};

var print = function printFunc() {console.log('Hello')};

Page 14: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Calling Functions

Page 15: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Calling Functions To call a function, simply use:

1. The function’s name

2. Parentheses (don’t forget them!)

3. A semicolon (;)

This will execute the code in the function’s body and will result in printing the following:

15

printLogo();

Telerik Corp.www.telerik.com

Page 16: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Calling Functions (2) A function can be called from:

Any other Function

Itself (process known as recursion)

16

function print(){ console.log("printed");}

function anotherPrint(){ print(); anotherPrint();}

Don't do this

at home

Page 17: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Declaring and Calling

FunctionsLive Demo

Page 18: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Functions with ParametersPassing Parameters and Returning

Values

Page 19: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Function Parameters To pass information to a function, you can use parameters (also known as arguments)

You can pass zero or several input values

You can pass values of different types

Each parameter has name

Parameters are assigned to particular values when the function is called

Parameters can change the function behavior depending on the passed values

19

Page 20: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Defining and Using Function Parameters

Function’s behavior depends on its parameters

Parameters can be of any type integer, floating-point, string, etc. Arrays

20

function printSign(number) { if (number > 0) console.log("Positive"); else if (number < 0) console.log("Negative"); else console.log("Zero");}

Page 21: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Defining and Using Function Parameters

(2) Functions can have as many parameters as needed:

21

function printMax(number1, number2){ var max = number1; if (number2 > number1) max = number2; console.log("Maximal number: " + max);}

Page 22: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Calling Functionswith Parameters

To call a function and pass values to its parameters: Use the function’s name, followed

by a list of expressions for each parameter

Examples:

22

printSign(-5);printSign(balance);printSign(2+3);

printMax(100, 200);printMax(oldQuantity * 1.5, quantity * 2);

Page 23: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Examples

Using Functions

With Parameters

Page 24: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Functions Parameters – Example

24

function printSign(number){ if (number > 0) console.log("The number " + number + " is positive."); else if (number < 0) console.log("The number " + number + " is negative."); else console.log("The number " + number + " is zero.");}

function printMax(number1, number2){ var max = number1; if (number2 > number1){ max = number2; } console.log("Maximal number: " + max);}

Page 25: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Live Demo

Function Parameters

Page 26: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Months – Example

Display the period between two months in a user-friendly way

26

function sayMonth(month) { var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October",

"November", "December"]; return monthNames[month-1];}

(the example continues)

Page 27: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Months – Example (2)

27

function sayPeriod(startMonth, endMonth){ var period = endMonth - startMonth; if (period < 0){ period = period + 12; // From December to January the // period is 1 month, not -11! } var resultString = "There are "; resultString += period + " + months from "; resultString += sayMonth(startMonth); resultString += " to "; resultString += sayMonth(endMonth); }

Page 28: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Live Demo

Months

Page 29: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Printing Triangle – Example

Creating a program for printing triangles as shown below:

11 1 21 2 1 2 31 2 3 1 2 3 41 2 3 4 1 2 3 4 5

n=5 1 2 3 4 5 n=6 1 2 3 4 5 61 2 3 4 1 2 3 4 51 2 3 1 2 3 41 2 1 2 31 1 2

1 29

Page 30: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Printing Triangle – Example

30

int n = read("input-tb");

var line;for (line = 1; line <= n; line++) printLine(1, line);for (line = n-1; line >= 1; line--) printLine(1, line);

function printLine(start, end){ var line=""; for (var i = start; i <= end; i++){ line += " " + i; } console.log(line);}

Page 31: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Printing TriangleLive Demo

Page 32: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Returning Values From

Functions

Page 33: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Returning Values from Functions

In JavaScript functions can return a value The returned values can be of any

type

Even of type void (no type)

Returned value Can be assigned to a variable:

Can be used in expressions:

Can be passed to another Function:

var head = arr.shift();

var price = getPrice() * quantity * 1.20;

var age = parseInt("5");

Page 34: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Defining Functions That Return a Value

Functions can return any type of data (int, string, array, etc.)

The combination of function's name and parameters is called function signature

Use return keyword to return a result

34

function multiply(int firstNum, int secondNum){ return firstNum * secondNum;}

Page 35: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

The return Statement The return statement:

Immediately terminates function’s execution

Returns specified expression to the caller

Example:

To terminate void function, use just:

Return can be used several times in a function body To return a different value in

different cases

35

return -1;

return;

Page 36: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Examples

Returning Values From

Functions

Page 37: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Temperature Conversion –

Example Convert temperature from Fahrenheit to Celsius:

37

function fahrenheitToCelsius(degrees){ var celsius = (degrees - 32) * 5 / 9; return celsius;}

var tStr = read("input-tb");var t = parseInt(tStr);t = fahrenheitToCelsius(t);console.log("Temperature in Celsius: " + t);

Page 38: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Live Demo

Temperature Conversion

Page 39: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Positive Numbers – Example

Check if all numbers in a sequence are positive:

39

function arePositive(sequence){ for (var i in sequence) { var number = sequence[i]; if (number <= 0) { return false; } } return true;}

Page 40: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Live Demo

Positive Numbers

Page 41: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Data Validation – Example

Validating input data:

41

function validate(username, password, email) { return validateUsername(username) && validatePass(password) && validateEmail(email);}

function validateUsername(username) { return username != "" && username.length > 3 && username.length < 20;}

function validatePass(pass) { return pass != "" && pass.length > 6 && pass.length < 20;}

function validateEmail(email) { var containsAt = email.indexOf("@"); return containsAt > 3 && email.length - containsAt > 3;}

Page 42: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Live Demo

Data Validation

Page 43: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Variable Scope

Page 44: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Local and Global Variables

Variables can be either local or global Global variables are accessible from

any JS code

Locals can be accessed only from their scope

Global variables can be made in two ways: Defining a common variable outside

of function

The variables becomes local to the window

Define a variable inside a function, without var

Page 45: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Variable ScopeLive Demo

Page 46: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Functions – Best Practices

Each function should perform a single, well-defined task

Function’s name should describe that task in a clear and non-ambiguous way Good examples: calculatePrice, readName

Bad examples: f, g1, Process

In JS functions should start with lower letter

Avoid functions longer than one screen Split them to several shorter

functions

46

Page 47: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Questions?

Questions?

Functions

http://academy.telerik.com

Page 48: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Exercises

1. Write a function that asks the user for his name and prints “Hello, <name>” (for example, “Hello, Peter!”). Write a script to test this function.

2. Write a function GetMax() with two parameters that returns the bigger of two integers. Write a script that reads 3 integers and prints the biggest of them using the function GetMax().

3. Write a function that returns the last digit of given integer as an English word. Examples: 512 "two", 1024 "four", 12309 "nine".

48

Page 49: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Exercises (2)

4. Write a function that counts how many times given number appears in given array. Write a test script to check if the function is working correctly.

5. Write a function that checks if the element at given position in given array of integers is bigger than its two neighbors (when such exist).

6. Write a Function that returns the index of the first element in array that is bigger than its neighbors, or -1, if there’s no such element.

Use the function from the previous

exercise.

49

Page 50: Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer

Exercises (3)

7. Write a function that reverses the digits of given decimal number. Example: 256 652

8. Write a function that adds two positive integer numbers represented as arrays of digits (each array element arr[i] contains a digit; the last digit is kept in arr[0]). Each of the numbers that will be added could have up to 10 000 digits.

50