JavaScript Functions (PDF)
Document Details
Uploaded by MagnanimousCloisonnism
Vilnius University
Justina Balsė
Tags
Summary
This document provides a tutorial on JavaScript functions. It covers various aspects of functions, including function declarations, expressions, local variables, scope chain, and default arguments. The document likely serves as instructional material within an educational course on modern JavaScript programming.
Full Transcript
Programavimo pagrindai (Functions) Justina Balsė Turinys Function declaration Function expression Local variables Scope chain Naming a function *Default arguments *Arrow function expression 2 Functions A function definitio...
Programavimo pagrindai (Functions) Justina Balsė Turinys Function declaration Function expression Local variables Scope chain Naming a function *Default arguments *Arrow function expression 2 Functions A function definition (also called a function declaration, or function statement) consists of the function keyword, followed by: The name of the function. A list of parameters to the function, enclosed in parentheses and separated by commas. The JavaScript statements that define the function, enclosed in curly brackets, {...}. Justina Balsė Functions | Example function square(number) { The function square takes one return number * number; parameter, called number. The } function consists of one statement that says to return the parameter of the function (that is, number) multiplied by itself. The statement return specifies the value returned by the function. 4 Functions | Example 5 Functions | Example 6 Functions Function declaration Function expression function add(num1, num2) { let add = function (num1, num2) { return num1 + num2; return num1 + num2; } }; add(5, 6); add(5, 6); Justina Balsė Functions console.log(subtract(7, 4)); console.log(subtract(7, 4)); function subtract(n1, n2) { var subtract = function (n1, n2){ return n1-n2; return n1-n2; } } // 3 // TypeError: subtract is not a function Justina Balsė Functions | Function expression let square = function (num) { let result = num * num; return result; } let value = square(3); let otherValue = square(10); console.log(value); console.log(otherValue); Justina Balsė Local variables function showMessage() { // local variable A variable declared inside a let message = "Hello, I'm JavaScript!"; function is only visible inside that alert( message ); function. } // Hello, I'm JavaScript! showMessage(); // Error! The variable is local to the function alert( message ); 10 Outer variables | 1 let userName = 'Tom'; A function can access an function showMessage() { outer variable. let message = 'Hello, ' + userName; alert(message); } // Hello, Tom showMessage(); 11 Outer variables | 2 let userName = 'John'; The function has full function showMessage() { // (1) changed the outer variable access to the outer userName = "Bob"; let message = 'Hello, ' + userName; variable. It can modify it. alert(message); } // John before the function call alert( userName ); showMessage(); // Bob, the value was modified by the function alert( userName ); 12 Scope chain | 1 const a = 10; When a variable is used in JavaScript, the JavaScript engine function myFunction() { will try to find the variable’s function innerFunction() { value in the current scope. If it console.log(a); could not find the variable, it will } innerFunction(); look into the outer scope and will } continue to do so until it finds the variable or reaches global scope. myFunction(); 13 Scope chain | 2 let a; // 1 1. a is declared in the global scope. function myFunction() { let a; // 3 2. myFunction() is called. a = 15; // 4 3. a is declared in the function console.log(a); // 5 scope. } 4. Is a declared in function scope? YES! Assign value 15. myFunction(); // 2 5. a has value 15. 6. a has value undefined in console.log(a); // 6 global scope. 14 Scope chain | 3 let a; let b; function myFunction() { let a; a = -100; b = true; console.log(a); // 1 - ? } myFunction(); console.log(a); // 2 - ? console.log(b); // 3 - ? 15 Scope chain | 4 function myFunction() { b = true; console.log(b); // 1 - ? } myFunction(); console.log(b); // 2 - ? 16 Kas bus atspausdinta konsolėje? | 1 function myFunction(a, b){ console.log(a); console.log(b); } myFunction(5, 10); // ? myFunction(true, null); // ? myFunction(); // ? myFunction("abc"); // ? 17 Kas bus atspausdinta konsolėje? | 2 function myFunction(a, b){ return a+b; } myFunction(5, 10); // ? myFunction(); // ? myFunction("abc"); // ? 18 Kas bus atspausdinta konsolėje? | 3 function myFunction(a, b){ return a+b; } console.log(myFunction(5, 10)); // ? console.log(myFunction()); // ? console.log(myFunction("abc")); // ? 19 Kas bus atspausdinta konsolėje? | 4 function myFunction(a, b){ function myNextFunction(e){ return e * e; } let c = a + b; let d = myNextFunction(c); return d; } console.log(myFunction(5, 10)); // ? console.log(myFunction()); // ? console.log(myFunction("abc")); // ? 20 Naming a function // shows a message Function starting with… showMessage(..) // returns the age (gets it somehow) getAge(..) // calculates a sum and returns the result "get…" – return a value, calcSum(..) "calc…" – calculate something, // creates a form (and usually returns it) createForm(..) "create…" – create something, // checks a permission, returns true/false "check…" – check something and checkPermission(..) return a boolean, etc. 21 Make code readable for other developers a = "John"; let personName = "John"; b = "London"; let personCity = "London"; function test(x, y){ function greet(personName, personCity){ d = "Hello " + x + " from " + y; let greetPerson = "Hello " + personName + " from " + personCity; return d; return greetPerson; } } var a, b, d; console.log(greet(personName, personCity)); console.log(test(a, b)); 22 Praktika Uždavinių sprendimas konsolėje. 05 - 1 Funkcijos 05 - 2 Funkcijos 05 - 3 Funkcijos 23 Functions Function declaration Function expression function add(num1, num2) { let add = function (num1, num2) { return num1 + num2; return num1 + num2; } }; add(5, 6); add(5, 6); Justina Balsė *Function expression example | 1 setTimeout( function(){ The global setTimeout() method console.log("Labas"); sets a timer which executes a }, 1000 ); function or specified piece of code once the timer expires. setTimeout ( x, y ): x - function() {} y - 1000 25 *Function expression example | 2 let i = 1; The setInterval() method, setInterval( function(){ repeatedly calls a function or console.log("Labas " + i); executes a code snippet, with a i = i + 1; fixed time delay between each }, 1000); call. 26 *Callback functions Callback functions are derived from a programming paradigm known as functional programming. Functional programming specifies the use of functions as arguments. A callback function is essentially a pattern. 27 *Functions | Default arguments let getScoreText = function (name = "Anonymous", score = 0) { return "Name: " + name + " - Score: " + score; } let scoreText1 = getScoreText(); console.log(scoreText1); let scoreText2 = getScoreText("Tom", 33); console.log(scoreText2); let scoreText3 = getScoreText(undefined, 99); console.log(scoreText3); 28 *Rest parameters function sum(...theArgs) { The rest parameter syntax allows a let sum = 0; for(let i=0; i expression An arrow function expression // ES5 has a shorter syntax than a var multiplyES5 = function(x, y) { function expression. return x * y; }; // ES6 let multiplyES6 = (x, y) => { return x * y }; Justina Balsė 31 *Arrow function expression Specifying parameters: – () => {... } // no parameter – x => {... } // one parameter – (x, y) => {... } // several parameters Specifying a body: – x => { return x * x } // block – x => x * x // expression, equivalent to previous line Justina Balsė 32 *Arrow function expression const myFunc = function() { const myVar = "value"; return myVar; } const myFunc = () => { const myVar = "value"; return myVar; } const myFunc = () => "value"; 33 Variables var - this syntax can be used to declare both local and global variables. let - this syntax can be used to declare a block-scope local variable. const - is used to assign a constant value to the variable. 34 Variables Some developers prefer to assign all their variables using const by default, unless they know they will need to reassign the value. Only in that case, they use let. 35 var // global var a = 10; var variables are function scope. It means they are only available function myF(){ inside the function they’re // function scope var a = 15; created in, or if not created inside return a; a function, they are globally } scoped. console.log(a); console.log(myF()); 36 let and const { // block scope let and const are block scope. let a = 10; Block scope is within curly const b = true; brackets. } console.log(a); // a is not defined console.log(b); // b is not defined for(let i = 2; i