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

Slides:



Advertisements
Similar presentations
JavaScript Basics Course Introduction SoftUni Team Technical Trainers Software University
Advertisements

C# Advanced Topics Methods, Classes and Objects SoftUni Team Technical Trainers Software University
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
PHP Basics Course Introduction SoftUni Team Technical Trainers Software University
JavaScript Syntax Data Types, Variables, Operators, Expressions, Conditional Statements Svetlin Nakov Technical Trainer Software University.
Advanced JavaScript Course Introduction 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.
NoSQL Databases NoSQL Concepts SoftUni Team Technical Trainers Software University
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
Objects, Properties, Primitive and Reference Types Learning & Development Team Telerik Software Academy.
Methods, Arrays, Lists, Dictionaries, Strings, Classes and Objects
Svetlin Nakov Technical Trainer Software University
Using the Standard.NET Framework Classes Svetlin Nakov Telerik Corporation
Multidimensional Arrays, Sets, Dictionaries Processing Matrices, Multidimensional Arrays, Dictionaries, Sets SoftUni Team Technical Trainers 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
Functions Reusable Parts of Code SoftUni Team Technical Trainers Software University
JavaScript Best Practices Learn How to Write Better Quality JavaScript Software University Technical Trainers SoftUni Team.
JavaScript Basics Course Introduction Svetlin Nakov Technical Trainer Software University
Java Collections Basics Arrays, Lists, Strings, Sets, Maps Svetlin Nakov Technical Trainer Software University
Templating, Routing, lodash Extending functionality using Collections SoftUni Team Technical Trainers Software University
Arrays, Lists, Stacks, Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
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
C# Basics Course Introduction Svetlin Nakov Technical Trainer Software University
Jekyll Static Site Generator Template-Based Site Generation Svetlin Nakov Technical Trainer Software University
Forms Overview, Query string, Submitting arrays, PHP & HTML, Input types, Redirecting the user Mario Peshev Technical Trainer Software.
JavaScript Modules and Patterns Private Fields, Module, Revealing Module, Revealing Prototype, … Software University Technical Trainers.
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
Associative Arrays and Objects Associative Arrays, Objects Svetlin Nakov Technical Trainer Software University
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
Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer
Advanced C# Course Introduction SoftUni Team Technical Trainers Software University
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
JavaScript Applications Course Introduction 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
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
Programming for Beginners Course Introduction SoftUni Team Technical Trainers Software University
Sets, Dictionaries SoftUni Team Technical Trainers Software University
PHP Basics Course Introduction Svetlin Nakov Technical Trainer Software University
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer 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
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
Classes, Properties, Constructors, Objects, Namespaces
Repeating Code Multiple Times
Extending functionality using Collections
First-Class Functions
Subroutines in Computer Programming
Using Classes and Objects
Presentation transcript:

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

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  The "JavaScript Basics" course is NOT for absolute beginners  Take the "C# Basics" course at SoftUni first:  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

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

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

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

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

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  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 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(a + b, c); printMax(2 + 3, 10); printMax(100, 200); printMax(oldQuantity * 1.5, quantity * 2);

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

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

Return a Value from a Function Live Demo 26

 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

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 30

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

Svetlin Nakov Technical Trainer Software University Using Objects Objects, Properties, Primitive and Reference Types

Object Types and Objects Modeling Real-world Entities with Objects

 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  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: function deposit(sum) function withdraw(sum) state (data) (functions) behavior (functions)

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

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  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  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 Object Types and Objects – Example Account ownerbalance suspend()deposit(sum)withdraw(sum) Object type ivanAccount owner = "Ivan Kolev" balance = peterAccount owner = "Peter Kirov" balance = kirilAccount owner = "Kiril Kirov" balance = 25.0 Object Object Object Attributes (properties and fields) Operations (functions)

JavaScript Objects Overview What are Objects?

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

Objects and Properties Live Demo

Object and Primitive Types Types in JavaScript 55

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

Primitive and Reference Types in JS Live Demo

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

Object Types Live Demo

JSON Objects Creating Simple objects 64

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

JSON Objects Live Demo

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

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