Functions Reusable Parts of Code SoftUni Team Technical Trainers Software University

Slides:



Advertisements
Similar presentations
Subroutines in Computer Programming Svetlin Nakov Telerik Corporation
Advertisements

Svetlin Nakov Technical Trainer Software University Functions and Objects Reusable Parts of Code Objects in JavaScript.
C# Advanced Topics Methods, Classes and Objects SoftUni Team Technical Trainers Software University
AngularJS Routing Routes, Route Parameters, Templates, Location, Navigation SoftUni Team Technical Trainers Software University
PHP Flow Control Loops, Functions, Return, Exit, Require, Try...Catch Software University SoftUni Team Technical Trainers.
AngularJS Services Built-in and Custom Services SoftUni Team Technical Trainers Software University
Methods Writing and using methods, overloads, ref, out SoftUni Team Technical Trainers Software University
Subroutines in Computer Programming Svetlin Nakov Telerik Corporation
Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer
JavaScript Syntax Data Types, Variables, Operators, Expressions, Conditional Statements Svetlin Nakov Technical Trainer Software University.
Project Tracking Tools Trello, Asana, Basecamp, GitHub Issue Tracker, TRAC SoftUni Team Technical Trainers Software University
AngularJS Directives Defining Custom Directives SoftUni Team Technical Trainers Software University
Software Testing Lifecycle Exit Criteria Evaluation, Continuous Integration Ivan Yonkov Technical Trainer Software University.
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
JavaScript Design Patterns Private Fields, Module, Revealing Module, Revealing Prototype, … Software University Technical Trainers SoftUni.
Conditional Statements Implementing Control-Flow Logic in C# SoftUni Team Technical Trainers Software University
Loops Repeating Code Multiple Times SoftUni Team Technical Trainers Software University
Entity Framework Performance SoftUni Team Technical Trainers Software University
Svetlin Nakov Technical Trainer Software University
Processing Redis with.NET How to Operate with Redis Databases SoftUni Team Technical Trainers Software University
Multidimensional Arrays, Sets, Dictionaries Processing Matrices, Multidimensional Arrays, Dictionaries, Sets SoftUni Team Technical Trainers Software University.
Project Tracking Tools Trello, Asana, Basecamp, GitHub Issue Tracker, TRAC Angel Georgiev Part-time Trainer Software University
Test-Driven Development Learn the "Test First" Approach to Coding SoftUni Team Technical Trainers Software University
Defining Classes Classes, Fields, Constructors, Methods, Properties SoftUni Team Technical Trainers Software University
Static Members and Namespaces Static Members, Indexers, Operators, Namespaces SoftUni Team Technical Trainers Software University
JavaScript Syntax Data Types, Variables, Operators, Expressions, Conditional Statements SoftUni Team Technical Trainers Software University
JavaScript Best Practices Learn How to Write Better Quality JavaScript Software University Technical Trainers SoftUni Team.
Controllers and Markup Controllers, $scope, Markup, Directives, Expressions, Binding, Filters, Validation SoftUni Team Technical Trainers Software University.
AMD and RequireJS Splitting JavaScript Code into Dependent Modules Software University Technical Trainers SoftUni Team.
Asynchronous Web Services Writing Asynchronous Web Services SoftUni Team Technical Trainers Software University
Jekyll Static Site Generator Template-Based Site Generation Svetlin Nakov Technical Trainer Software University
JavaScript Modules and Patterns Private Fields, Module, Revealing Module, Revealing Prototype, … Software University Technical Trainers.
Web Development Tools Tools for Front-End Developers Writing HTML and CSS Code SoftUni Team Technical Trainers Software University
Responsive Design Design that Adapts to Different Devices SoftUni Team Technical Trainers Software University
Processing JSON in.NET JSON, JSON.NET LINQ-to-JSON and JSON to XML SoftUni Team Technical Trainers Software University
Tables, Rows, Columns, Cells, Header, Footer, Colspan, Rowspan
High-Quality Programming Code Code Correctness, Readability, Maintainability Svetlin Nakov Technical Trainer Software University
Svetlin Nakov Technical Trainer Software University Functions and Objects Reusable Parts of Code Objects in JavaScript.
Regular Expressions /^Hel{2}o\s*World\n$/ SoftUni Team Technical Trainers Software University
CSS Transitions and Animations Animated HTML Elements SoftUni Team Technical Trainers Software University
Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer
Prototype Chain and Inheritance Prototype chain, Inheritance, Accessing Base Members Software University Technical Trainers SoftUni Team.
Events Event Handling in JavaScript SoftUni Team Technical Trainers Software University
Mocking with Moq Tools for Easier Unit Testing SoftUni Team Technical Trainers Software University
Simulating OOP in JavaScript Function Constructor, Prototypes, "this" Object, Classical and Prototypal Model Software University Technical.
Operators and Expressions
Functions and Function Expressions Closures, Function Scope, Nested Functions Telerik Software Academy
Mocking Unit Testing Methods with External Dependencies SoftUni Team Technical Trainers Software University
Mocking with Moq Mocking tools for easier unit testing Svetlin Nakov Technical Trainer Software University
Functions and Function Expressions Closures, Function Scope, Nested Functions, IIFE Software University Technical Trainers SoftUni Team.
Test-Driven Development Learn the "Test First" Approach to Coding Svetlin Nakov Technical Trainer Software University
Sets, Dictionaries SoftUni Team Technical Trainers Software University
Creating Content Defining Topic, Creating Technical Training Materials SoftUni Team Technical Trainers Software University
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer Software University
Doctrine The PHP ORM SoftUni Team Technical Trainers Software University
JavaScript Best Practices Learn How to Write Better Quality JavaScript Software University Technical Trainers SoftUni Team.
Creating Content Defining Topic, Creating Technical Training Materials SoftUni Team Technical Trainers Software University
Web Storage and Cookies Cookies, Local and Session Storage SoftUni Team Technical Trainers Software University
First Steps in PHP Creating Very Simple PHP Scripts SoftUni Team Technical Trainers Software University
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
Static Members Static Variables & Methods SoftUni Team Technical Trainers Software University
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Generics SoftUni Team Technical Trainers Software University
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
Mocking tools for easier unit testing
Repeating Code Multiple Times
First-Class Functions
Iterators and Generators
Subroutines in Computer Programming
Functions Declarations, Function Expressions and IIFEs
Presentation transcript:

Functions Reusable Parts of Code SoftUni Team Technical Trainers Software University

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

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;}

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

Declaring and Calling Functions

 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  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

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') };

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  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}

Declearing and Calling Functions Live Demo

Functions with Parameters Passing Parameters and Returning Values

 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

 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);}

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

Function Parameters Live Demo

Printing a Triangle – Example  Creating a program for printing triangles as shown below: n=5  n=6 

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);};

Printing a Triangle Live Demo 19

The arguments Object Processing Function Arguments

 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

The arguments Object Live Demo

Returning Values Returning Results from a Function

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);

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  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

Return a Value from a Function Live Demo 27

 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

Average Students Age Live Demo

Function Scope Scope of Variables and Functions

 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

 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  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  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  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

Nested Functions Live Demo

Function Overloading Multiple Functions with the Same Name

 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  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  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  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…}

Function Overloading Live Demo 42

Function Context What’s this ?

 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  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  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  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  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

Function Context Live Demo

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

? ? ? ? ? ? ? ? ? Functions and Objects

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

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