Presentation is loading. Please wait.

Presentation is loading. Please wait.

Functions Reusable Parts of Code SoftUni Team Technical Trainers Software University

Similar presentations


Presentation on theme: "Functions Reusable Parts of Code SoftUni Team Technical Trainers Software University"— Presentation transcript:

1 Functions Reusable Parts of Code SoftUni Team Technical Trainers Software University http://softuni.bg

2 Table of Contents  Declaring and Calling Functions  Parameters, the arguments Object  Function Returning Values  Function Scope  Function Overloading  Function context 2

3 What is a Function?  A function is a reusable block of code  Designed to perform a particular task  Can be invoked from other code  Usually has a name  Can take parameters and return a value  Functions allow breaking a large program into smaller pieces 3 function triangleArea(side, height) { return side * height / 2; return side * height / 2;}

4 Why to Use Functions?  More manageable code  Split large problems into smaller pieces  Better organization of the program  Improve code readability and understandability  Enhance abstraction  Improves code maintainability  Promotes code reuse  Avoids code repetition 4

5 Declaring and Calling Functions

6  Typically a function has:  A name  It is used to call the function  Describes its purpose  A body  It contains the programming code  Surrounded by { and }  A set of parameters  Functions in JavaScript do not have return type Declaring and Creating Functions in JS function printHello() { console.log('Hello'); console.log('Hello');} 6

7 7  Functions are Objects!  can be assigned to variables or as object properties  Anonymous functions are functions which do not have a name  they are created in the memory  unless we store a reference to such function in a variable, we cannot access it Anonymous functions (function () {}); // that’s it, we cannot refer // to this function anymore // to this function anymore var fn = function () {}; // but we can refer to this one function () {}) instanceof Object; ( function () {}) instanceof Object; // true

8 Ways to Define a Function in JS  Functions can be defined in several ways:  By function declaration  By function expression (anonymous function)  Using the Function constructor (anonymous function) var printHello = new Function('console.log("Hello")'); var sum = new Function('a', 'b', 'return a + b;'); function printHello() { console.log('Hello') }; var printHello = function() { console.log('Hello') }; var printHello = function printFunc() { console.log('Hello') };

9 Calling Functions  To call a function, simply use: 1. The function’s name or reference 2. Parentheses: ( ) 3. A semicolon: ; (optional)  This will execute the code in the function’s body  Will result in printing the following: printHello(); Hello

10 10  A function can be called from:  Any other function  Itself (process known as recursion) Calling Functions (2) function print() { console.log('printed'); console.log('printed');} function anotherPrint() { print(); print(); anotherPrint(); // recursion anotherPrint(); // recursion}

11 Declearing and Calling Functions Live Demo

12 Functions with Parameters Passing Parameters and Returning Values

13  To pass information to a function, you can use parameters  Parameters accept input data in the function  Each parameter has a name  You can pass zero or several input values  Parameters are assigned to particular values (called "arguments") when the function is called  Parameters can change the function behavior  Depending on the passed values Function Parameters

14  Function’s behavior depends on its parameters  Parameters can be of any type  number, string, object, array, etc.  Even function (callbacks) Defining and Using Function Parameters function printMax(number1, number2) { var max = number1; var max = number1; if (number2 > number1) if (number2 > number1) max = number2; max = number2; console.log('Maximal number: ' + max); console.log('Maximal number: ' + max);}

15 Calling Functions with 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: printMax(-5, -10); printMax(100, 200); printMax(oldQuantity * 1.5, quantity * 2); // Passing missing arguments to function results in // undefined parameters var myFunction = function f(x) { return x; } console.log(myFunction()); // Logs undefined

16 Function Parameters Live Demo

17 Printing a Triangle – Example  Creating a program for printing triangles as shown below: 1 11 2 1 21 2 3 1 2 31 2 3 4 1 2 3 41 2 3 4 5 n=5  1 2 3 4 5 n=6  1 2 3 4 5 6 1 2 3 41 2 3 4 5 1 2 31 2 3 4 1 21 2 3 11 2 1

18 18 Printing a Triangle – Source Code var n = 5; for (var line = 1; line <= n; line++) printLine(1, line); printLine(1, line); for (line = n-1; line >= 1; line--) printLine(1, line); printLine(1, line); function printLine(start, end) { var line = ''; var line = ''; for (var i = start; i <= end; i++){ for (var i = start; i <= end; i++){ line += ' ' + i; line += ' ' + i; } console.log(line); console.log(line);};

19 Printing a Triangle Live Demo 19

20 The arguments Object Processing Function Arguments

21  Every function have a special object called arguments  Array-like object  Holds the arguments passed to it  No need to be explicitly declared and exists in every JS function (local) Arguments Object function printArguments() { for (var i in arguments) { for (var i in arguments) { console.log(arguments[i]); console.log(arguments[i]); }} printArguments(1, 2, 3, 4); // 1, 2, 3, 4

22 The arguments Object Live Demo

23 Returning Values Returning Results from a Function

24 24  Functions can return any type of data  E.g. number, string, object, etc...  Even other functions  Use return keyword to return a result Defining Functions That Return a Value function createStudent(name, age, gender) { var obj = { name: name, age: age, gender: gender }; var obj = { name: name, age: age, gender: gender }; return obj; return obj;} var student = createStudent("Deyan", 21, "male"); console.log(student);

25 The return Statement  The return statement  Returns the specified expression to the caller and stops the function’s execution  Example:  To stop the function's execution, use just:  Return can be used several times in a function body  To return a different values in different cases return; return -1;

26 26  Functions always return  unless stated, they return undefined by default  constructors always return object - the new instance Default return values function Class() {} Class(); // returns undefined new Class(); // returns object, instance of Class function hi5() { return 5; return 5;} hi5(); // returns 5 new hi5(); // returns object, instance of hi5

27 Return a Value from a Function Live Demo 27

28  Calculate the avarage age of Student objects in array Average Students Age – Example var studentsArr = [{name: 'Ivan', age: 16, gender: 'male'}, {name: 'George', age: 15, sex: 'male'}, {name: 'George', age: 15, sex: 'male'}, {name: 'Maria', age: 22, gender: 'female'}]; {name: 'Maria', age: 22, gender: 'female'}]; function calculateAverageAge(studentsArr) { var sum = 0; var sum = 0; for (var i = 0; i < studentsArr.length; i++) { for (var i = 0; i < studentsArr.length; i++) { sum += studentsArr[i].age; sum += studentsArr[i].age; } return sum / studentsArr.length; return sum / studentsArr.length;} var avgStudentsAge = calculateAverageAge(studentsArr); console.log(avgStudentsAge); 28

29 Average Students Age Live Demo

30 Function Scope Scope of Variables and Functions

31  Every variable has its scope of usage  The scope defines where the variable is accessible Function Scope var arr = [1, 2, 3, 4, 5, 6, 7]; // global scope function countOccurences(value) { var count = 0; // local scope (for the function only) for (var i = 0; i < arr.length; i++) if (arr[i] == value) count++; return count; } countOccurences(arr); console.log(arr); // [1, 2, 3, 4, 5, 6, 7] console.log(typeof(count)); // undefined 31

32  In JS we have functional scope, not block scope!  Example of local function scope variables: Local Scope function play() { for (var x = 1; x < 5; x++) { var y = x * x; console.log(x + " " + y); } play(); console.log(typeof(x)); // undefined console.log(typeof(y)); // undefined

33 33  Example of global scope variables:  Global variables (declared without var ) are different than variables in the global scope Global Scope for (var x = 1; x < 5; x++) { var y = x * x; console.log(x + " " + y); } console.log("x=" + x + " y=" + y); // x=5 y=16 // Now "x" and "y" are variables in the global scope

34 34  Immediately-Invoked Function Expression (IIFE)  Create anonymous function & invoke it immediately  A JavaScript block of code that hides variables  Prevents polluting the global scope (Encapsulation) Hiding Variables through IIFE (function() { for (var x = 1; x < 5; x++) { var y = x * x; console.log(x + " " + y); } })(); console.log(typeof(x) + " " + typeof(y)); // undefined undefined

35 35  Functions in JS can hold other functions  Inner functions can access the variables hold in their parent Functions in JS can be Nested function getWordsUppercase(str) { var words = extractWords(str); var wordsUppercase = []; words.forEach(function(w) { wordsUppercase.push(w.toUpperCase()); }); return wordsUppercase; function extractWords(str) { return str.split(/\s+/); } } getWordsUppercase('Hi, how are you?'); // ["HI", "HOW", "ARE", "YOU?"] // nested functions are inaccessible outside parent scope extractWords('Hello functions'); // ReferenceError

36 Nested Functions Live Demo

37 Function Overloading Multiple Functions with the Same Name

38  JavaScript does not support function overloading  i.e. only one function with a specified name can exist in the same scope Function Overloading function print(number) { console.log('Number: ' + number); console.log('Number: ' + number);} function print(number, text) { console.log('Number: ' + number + '\nText: ' + text); console.log('Number: ' + number + '\nText: ' + text);} print(2); // print(2); // The second print() overwrites the first one

39 39  Function overloading by checking the number of arguments: Different Number of Parameters function printText (number, text) { switch (arguments.length) { switch (arguments.length) { case 1 : console.log ('Number :' + number); break; case 1 : console.log ('Number :' + number); break; case 2 : case 2 : console.log ('Number :' + number); console.log ('Number :' + number); console.log ('Text :' + text); console.log ('Text :' + text); break; break; }} printText (5); // Logs 5 printText (5, 'Lorem Ipsum'); // Logs 5 and Lorem Ipsum

40 40  Function overloading by checking the arguments' type: Different Types of Parameters function printValue (value) { var log = console.log; var log = console.log; switch (typeof value) { switch (typeof value) { case 'number' : log ('Number: ' + value); break; case 'number' : log ('Number: ' + value); break; case 'string' : log ('String: ' + value); break; case 'string' : log ('String: ' + value); break; case 'object' : log ('Object: ' + value); break; case 'object' : log ('Object: ' + value); break; case 'boolean' : log ('Number: ' + value); break; case 'boolean' : log ('Number: ' + value); break; }} printValue (5); printValue ('Lorem Ipsum'); printValue ([1, 2, 3, 4]); printValue (true);

41 41  Default parameters are checked in the function body  If the parameter is not present  assign a value Default Parameters // Only the str parameter is required function substring (str, start, end) { start = start || 0; start = start || 0; end = end || str.length; end = end || str.length; // function code comes here… // function code comes here…}

42 Function Overloading Live Demo 42

43 Function Context What’s this ?

44  In function body the this keyword represents the context  The context is an object reference  Depends on how the function was invoked  as function ( this refers to the global object)  as constructor ( this refers to the new instance)  as method ( this refers to the owner object)  as callback ( this refers to the global object) Function Context

45 45  In this situation the context refers to the global object Invoking the function as function function foo() { console.log(this); console.log(this);} foo(); // logs "window"

46 46  In this situation the context refers to the new instance Invoking the function as constructor function Foo() { console.log(this); console.log(this);} new Foo(); // logs "Foo {}" where the object is new instance of " Foo"

47 47  In this situation the context refers to the owner object Invoking the function as method var object = { foo: 'bar', foo: 'bar', getFoo: function () { getFoo: function () { return this.foo; // "this " refers to "object" return this.foo; // "this " refers to "object" }}; object.getFoo(); // returns "bar"

48 48  In this situation the context refers to the global object Invoking the function as callback var object = { foo: 'bar', foo: 'bar', getFoo: function () { getFoo: function () { console.log(this.foo); console.log(this.foo); }}; // pass "getFoo" as callback to "setTimeout" setTimeout(object.getFoo, 100); // the console logs "undefined" after 100ms

49 Function Context Live Demo

50 1.Declaring and Calling Functions  Parameters  The arguments Object 2.Function Returning Values 3.Function Scope  Global scope  Function scope 4.Function Overloading 5.Function context Summary

51 ? ? ? ? ? ? ? ? ? https://softuni.bg/courses/javascript-basics Functions and Objects

52 License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" licenseCreative Commons Attribution- NonCommercial-ShareAlike 4.0 International 52  Attribution: this work may contain portions from  “JavaScript Basics" course by Telerik Academy under CC-BY-NC-SA licenseJavaScript BasicsCC-BY-NC-SA

53 Free Trainings @ Software University  Software University Foundation – softuni.orgsoftuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg softuni.bg  Software University @ Facebook  facebook.com/SoftwareUniversity facebook.com/SoftwareUniversity  Software University @ YouTube  youtube.com/SoftwareUniversity youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bgforum.softuni.bg


Download ppt "Functions Reusable Parts of Code SoftUni Team Technical Trainers Software University"

Similar presentations


Ads by Google