Javascript Functions PDF
Document Details
Tags
Summary
This document provides a tutorial about JavaScript functions. It covers function syntax, how to declare functions, how to call functions, and use the return statement. It also explains how to use parameters within the function.
Full Transcript
IT2301 JAVASCRIPT FUNCTIONS Function Syntax (OpenEDG, 2023) A function in JavaScript is a separate piece of code intended to perform a specific task. It is usually assigned a specific name that is called many times in different program sections. It also encloses...
IT2301 JAVASCRIPT FUNCTIONS Function Syntax (OpenEDG, 2023) A function in JavaScript is a separate piece of code intended to perform a specific task. It is usually assigned a specific name that is called many times in different program sections. It also encloses a repeated sequence of instructions in the program to increase the code’s readability. A JavaScript function aims to divide the code into logically independent parts to make a long program that is not a sequence of instructions easier to write and understand. It also allows for easy testing of code fragments enclosed in functions independent from the rest of the program. Declaring Functions A function statement starts with the function keyword followed by the function functionName() { function name, which follows the same rule as variable names that must relate to the condition to be done. code block } It is then followed by parentheses that enclose function parameters. It is followed by the function body, which contains the code block. // getMeanTemp function declaration let temperatures; Here, getMeanTemp is the function name to let meanTemp; calculate the mean daily temperature. function getMeanTemp() { This sample also contains the sequence of instructions or code blocks that it should let sum = 0; perform, but declaring a function is only a for (let i = 0; i < temperatures.length; i++) { preparation for the program to work. sum += temperatures[i]; } For this code to execute, the function needs to be called. meanTemp = sum / temperatures.length; } Calling Functions To call a function, the function name is written followed by parentheses and the instruction it should do next. // This code follows the getMeanTemp function declaration above temperatures = [12, 12, 11, 11, 12, 13, 15, 18, 21, 24, 25, 25, 19, 17, 16]; getMeanTemp(); console.log(`mean: ${meanTemp}`); // -> mean: 16.733333333333334 temperatures = [17, 10, 10, 10, 11, 13, 14, 22, 27, 29, 24, 21, 19, 17, 16]; getMeanTemp(); console.log(`mean: ${meanTemp}`); // -> mean: 17.333333333333332 After setting up the temperature data, the getMeanTemp function declaration is called twice, performing the same operation for both sets of temperature data. Each call causes the program to jump into the function code, execute the instructions, and return to the next instruction after the function is called. 06 Handout 1 *Property of STI [email protected] Page 1 of 4 IT2301 return Statement The return keyword causes the function to end exactly wherever this word is placed in the instruction. It also allows programmers to return a given value from inside the function to the place where it was called. function showMsg() { console.log("message 1"); Here, the showMsg function contains only two console.log separated by the return keyword placed in between them. return; console.log("message 2"); It only displays the first message, and then the return interrupts the } function to display the second message. showMsg(); // -> message 1 Going back to the getMeanTemp function, the return statement can be used to shorten the code. But first, some changes need to be considered. let temperatures; let meanTemp; function getMeanTemp() { let sum = 0; let result; for (let i = 0; i < temperatures.length; i++) { sum += temperatures[i]; } result = sum / temperatures.length; return result; } temperatures = [12, 12, 11, 11, 12, 13, 15, 18, 21, 24, 25, 25, 19, 17, 16]; meanTemp = getMeanTemp(); console.log('mean: ${meanTemp}'); temperatures = [17, 10, 10, 10, 11, 13, 14, 22, 27, 29, 24, 21, 19, 17, 16]; meanTemp = getMeanTemp(); console.log('mean: ${meanTemp}'); In the sample above, a local result variable is declared to contain the calculated result, and the return statement is used to return it. The global variable meanTemp still contains the result of the function call that is the first time, 16.733333333333334, and the second time, 17.333333333333332. Side note: A local variable is only usable inside its corresponding function block, while a global variable is usable anywhere in the program. A local variable is usually declared inside a function, while a global variable is declared outside any block or function. 06 Handout 1 *Property of STI [email protected] Page 2 of 4 IT2301 The result variable is only used to temporarily store the value to be returned so the function code can still be simplified. The result variable can be skipped by replacing it with the appropriate operation directly after return. function getMeanTemp() { let sum = 0; for (let i = 0; i < temperatures.length; i++) { sum += temperatures[i]; } return sum / temperatures.length; } The use of meanTemp becomes redundant, but it can be simplified by placing the getMeanTemp function call directly in console.log without using the meanTemp variable. let temperatures; function getMeanTemp() { let sum = 0; for (let i = 0; i < temperatures.length; i++) { sum += temperatures[i]; } return sum / temperatures.length; } temperatures = [12, 12, 11, 11, 12, 13, 15, 18, 21, 24, 25, 25, 19, 17, 16]; console.log('mean: ${getMeanTemp()}'); temperatures = [17, 10, 10, 10, 11, 13, 14, 22, 27, 29, 24, 21, 19, 17, 16]; console.log('mean: ${getMeanTemp()}'); 06 Handout 1 *Property of STI [email protected] Page 3 of 4 IT2301 Parameters These are only optional to use in functions. Parameters are names separated by commas, placed inside the parenthesis after the function name, and treated as local variables. function add(first, second) { Here, the parameter is the first and second placed inside the return first + second; parentheses next to the add function. It is also important to note that the declared names for the parameters, just like for function names } and variables, should be related to their purpose. let result = add(5, 7); Recalling arguments, they refer to the values given when a function console.log(result); // -> 12 is called. Thus, since the add function is called for this operation, the first parameter has a value of 5, and the second parameter has 7. The getMeanTemp function can take one parameter for the temperatures. The global variable meanTemp will be removed, and variables day1 and day2 will be created, containing the measurement data. These data will be passed onto the function. function getMeanTemp(temperatures) { let sum = 0; for (let i = 0; i < temperatures.length; i++) { sum += temperatures[i]; } return sum / temperatures.length; } let day1 = [12, 12, 11, 11, 12, 13, 15, 18, 21, 24, 25, 25, 19, 17, 16]; console.log(`mean: ${getMeanTemp(day1)}`); 16.733333333333334 let day2 = [17, 10, 10, 10, 11, 13, 14, 22, 27, 29, 24, 21, 19, 17, 16]; console.log(`mean: ${getMeanTemp(day2)}`); // // -> mean: 17.333333333333332 The first time the getMeanTemp function is called, the day1 variable is passed on the getMeanTemp function as an argument. The calculations performed inside the function using the temperatures parameter will then be based on the values from the day1 variable. This process repeats for the parameters stored in the day2 variable when the getMeanTemp is called again. References: Carey, P., Sasha V. (2022). JavaScript for warriors: 7th edition. Cengage. OpenEDG (2023). JavaScript essentials 1: Module 5. [Online Course]. Retrieved on March 16, 2023, from https://edube.org/ Rauschamayer, A. (2022). JavaScript for impatient programmers. ExploringJS. 06 Handout 1 *Property of STI [email protected] Page 4 of 4