Presentation is loading. Please wait.

Presentation is loading. Please wait.

Svetlin Nakov Technical Trainer Software University Functions and Objects Reusable Parts of Code Objects in JavaScript.

Similar presentations


Presentation on theme: "Svetlin Nakov Technical Trainer Software University Functions and Objects Reusable Parts of Code Objects in JavaScript."— Presentation transcript:

1 Svetlin Nakov Technical Trainer www.nakov.com Software University http://softuni.bg Functions and Objects Reusable Parts of Code Objects in JavaScript

2 Table of Contents  Declaring and Calling Functions  Parameters, the arguments Object, Returning Values  Function Scope  Function Overloading  Objects in JavaScript  Primitive and Reference Types  JSON Objects 2

3 3  The "JavaScript Basics" course is NOT for absolute beginners  Take the "C# Basics" course at SoftUni first: https://softuni.bg/courses/csharp-basics https://softuni.bg/courses/csharp-basics  The course is for beginners, but requires previous coding skills  Requirements  Coding skills – entry level  Computer English – entry level  Logical thinking Warning: Not for Absolute Beginners

4 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 4 function triangleArea(width, height) { return width * height / 2; return width * height / 2;}

5 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 repeating code 5

6 Declaring and Calling Functions

7  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 }  Functions in JavaScript does not have return type Declaring and Creating Functions in JS function printHello() { console.log('Hello'); console.log('Hello');} 7

8 Ways to Define a Function in JS  Functions can be defined in several ways:  By function declaration  By function expression  Using the constructor of the Function object var printHello = new Function('console.log("Hello")'); 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 2. Parentheses: ( ) 3. A semicolon: ;  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 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(a + b, c); printMax(2 + 3, 10); printMax(100, 200); printMax(oldQuantity * 1.5, quantity * 2);

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  Holds the arguments passed to it  No need to be explicitly declared and exists in every JS function 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...  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 Return a Value from a Function Live Demo 26

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

28 Average Students Age Live Demo

29 Function Scope Scope of Variables and Functions

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

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

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

33 33  Immediately-Invoked Function Expression (IIFE)  A JavaScript block of code that hides variables  Prevents polluting the global scope 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

34 34  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?"]

35 Nested Functions Live Demo

36 Function Overloading Multiple Functions with the Same Name

37  JavaScript does not support function overloading  i.e. only one function with a specified name can exists 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

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

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

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

41 Function Overloading Live Demo 41

42 Svetlin Nakov Technical Trainer www.nakov.com Software University http://softuni.bg Using Objects Objects, Properties, Primitive and Reference Types

43 Object Types and Objects Modeling Real-world Entities with Objects

44  Software objects model real-world objects or abstract concepts  Examples:  bank, account, customer, dog, bicycle, queue  Real-world objects have state and behavior  Account' state:  holder, balance, type  Account' behavior:  withdraw, deposit, suspend What are Objects?

45 45  How do software objects implement real-world objects?  Use variables / data to implement state  Use methods / functions to implement behavior  An object is a software bundle of variables and related functions What are Objects? (2) account owner: "Peter" balance: 350.00 function deposit(sum) function withdraw(sum) state (data) (functions) behavior (functions)

46 46 Objects Represent  checks  people  shopping list …  numbers  characters  queues  arrays Things / concepts from the real world Things / concepts from the computer world

47 47  The formal definition of a object type (class): Definition by Google What is an Object Type (Class)? Object types act as templates from which an instance of an object is created at run time. Types define the properties of the object and the functions used to control the object's behavior.

48 48  Object types provide the structure for objects  Define their prototype, act as template  Object types define:  Set of attributes  Represented by variables and properties  Hold their state  Set of actions (behavior)  Represented by methods/functions Object Types

49 49  An object is a concrete instance of a particular object type  Creating an object from an object type is called instantiation  Objects have state  Set of values associated to their attributes  Example:  Type: Account  Objects: Ivan's account, Peter's account Objects

50 50 Object Types and Objects – Example Account ownerbalance suspend()deposit(sum)withdraw(sum) Object type ivanAccount owner = "Ivan Kolev" balance = 5000.0 peterAccount owner = "Peter Kirov" balance = 1825.50 kirilAccount owner = "Kiril Kirov" balance = 25.0 Object Object Object Attributes (properties and fields) Operations (functions)

51 JavaScript Objects Overview What are Objects?

52 52  JavaScript is designed on a simple object-based paradigm  An object is a collection of properties  An object property is association between a name and a value  A value of property can be either  Property (variable / field)  Function (method)  Lots of predefined objects available in JS  Math, document, window, etc…  Objects can be created by the developer Objects Overview

53 53 Objects in JS – Example var tom = { firstName: 'Tom', firstName: 'Tom', lastName: 'Miller', lastName: 'Miller', toString: function () { toString: function () { return this.firstName + " " + this.lastName; return this.firstName + " " + this.lastName; }} var kate = { firstName: 'Kate', firstName: 'Kate', lastName: 'Brown', lastName: 'Brown', toString: function () { toString: function () { return this.firstName + " " + this.lastName; return this.firstName + " " + this.lastName; }}

54 Objects and Properties Live Demo

55 Object and Primitive Types Types in JavaScript 55

56 56  JavaScript is a typeless language  Variables don’t have type, but their values do  JavaScript has six different types:  number, string, boolean, null, undefined and object  Object is the only Object type  It is copied by reference  number, string, boolean, null, undefined are primitive types  Copied by value Reference and Primitive Types

57 57  The primitive types are boolean, number, string, undefined and null  All the other types are actually of type object  Including arrays, dates, custom types, etc…  All types derive from object  Their type is object Reference and Primitive Types (2) console.log(typeof new Object() === typeof new Array()); // true console.log(typeof new Object() === typeof new Date()); // true console.log(typeof new Array() === typeof new Date()); // true

58 58  Primitive types are passed by value  When passed as argument  New memory is allocated  The value is copied in the new memory  The value in the new memory is passed  Primitive types are initialized with type literals  Primitive types have a object type wrapper Primitive Types var number = 5; var text = 'Hello there!';

59 59  Assign string values to two variables  Create an object using their value  Change the value of the variables  Each object has its own value Primitive Types – Example var fName = 'Pesho'; var lName = 'Ivanov'; var person = { firstName: fName, lastName: lName }; lName = 'Petrov'; console.log(person.lastName) // logged 'Ivanov'

60 Primitive and Reference Types in JS Live Demo

61 61  Object is the only object type  When passed to a function, the value is not copied, but instead a reference of it is passed Object Type var marks = [ { subject : 'Java', score : 6.00 }, { subject : 'Java', score : 6.00 }, { subject : 'HTML5', score : 5.90 }, { subject : 'HTML5', score : 5.90 }, { subject : 'JavaScript', score : 6.00 }, { subject : 'JavaScript', score : 6.00 }, { subject : 'PHP', score : 6.00 }]; { subject : 'PHP', score : 6.00 }]; var student = { name: 'Deyan Dachev', marks: marks }; marks[1].score = 5.50; console.log(student.marks[1]); // logs 5.50 for HTML5 score

62 62  Shared object – two variables holding the same object:  Cloned objects – two variables holding separate objects: Object Cloning var peter = { name: 'Peter', age: 21 }; var maria = peter; maria.name = 'Maria'; console.log(maria); // Object {name: "Maria", age: 21} console.log(peter); // Object {name: "Maria", age: 21} var peter = { name: 'Peter', age: 21 }; var maria = JSON.parse(JSON.stringify(peter)); maria.name = 'Maria'; console.log(maria); // Object {name: "Maria", age: 21} console.log(peter); // Object {name: "Peter", age: 21}

63 Object Types Live Demo

64 JSON Objects Creating Simple objects 64

65  JSON stands for JavaScript Object Notation  A data format used in JavaScript, the " prop:value " notation  Then the object properties can be used: JSON Objects var person = { firstName: 'Dicho', firstName: 'Dicho', lastName: 'Dichov', lastName: 'Dichov', toString: function personToString() { toString: function personToString() { return this.firstName + ' ' + this.lastName; return this.firstName + ' ' + this.lastName; }} console.log(person.toString()); // '' // 'Object {firstName: "Dicho", lastName: "Dichov", toString: function}'

66 66  JSON.stringify(obj)  Converts a JS object to JSON string:  JSON.parse(str)  Creates a JS object by JSON string: JS Object ↔ JSON String var obj = { town: 'Sofia', gps: {lat: 42.70, lng: 23.32} } var str = JSON.stringify(obj); var str = '{"town":"Sofia","gps":{"lat":42.70,"lng":23.32}}'; var obj = JSON.parse(str);

67 67  JSON is great, but repeating code is not, right?  Lets make several persons: Building a JSON Object var dicho = {fname: 'Dicho', lname: 'Dichov', toString: function() { return this.fname + ' ' + this.lname; } toString: function() { return this.fname + ' ' + this.lname; }} var georgiev = { fname: 'Georgi', lname: 'Georgiev', toString: function() { return this.fname + ' ' + this.lname; } } var kirova = { fname: 'Maria', lname: 'Kirova', toString: function() { return this.fname + ' ' + this.lname; } }

68 68  A function for building JSON objects  Just pass first and last name and get an object  Something like a constructor JSON Building Function function BuildPerson(fname, lname) { return { return { fname: fname, fname: fname, lname: lname, lname: lname, toString: function () { return this.fname + ' ' + this.lname; } toString: function () { return this.fname + ' ' + this.lname; } }} var minkov = BuildPerson('Dicho', 'Dichov'); var georgiev = BuildPerson('Georgi', 'Georgiev');

69 JSON Objects Live Demo

70 1.Declaring and calling functions  Functions with and without parameters  Function scope  Function overloading in JS (fake) 2.Creating and using objects  Object properties 3.Primitive and reference types 4.JSON objects Summary

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

72 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 72  Attribution: this work may contain portions from  “JavaScript Basics" course by Telerik Academy under CC-BY-NC-SA licenseJavaScript BasicsCC-BY-NC-SA

73 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 "Svetlin Nakov Technical Trainer Software University Functions and Objects Reusable Parts of Code Objects in JavaScript."

Similar presentations


Ads by Google