{"id":7748,"date":"2018-12-22T08:50:04","date_gmt":"2018-12-22T13:50:04","guid":{"rendered":"https:\/\/www.carnaghan.com\/?p=7748"},"modified":"2021-03-06T15:49:32","modified_gmt":"2021-03-06T20:49:32","slug":"javascript-functions","status":"publish","type":"post","link":"https:\/\/www.carnaghan.com\/javascript-functions\/","title":{"rendered":"JavaScript Functions"},"content":{"rendered":"\n
Functions are repeatable blocks of code. They are fundamental to most programming languages and allow you to build applications with reusable code that can be called with different arguments. The best way to explain functions is through an example. Suppose you wanted a quick way to calculate how much your bill would be with tip (assume for this example the bill amount includes tax).<\/p>\n\n\n\n
Create two files called index.html<\/strong> and script.js<\/strong> and enter the code below into each. Alternatively, if you followed along in the previous lesson, use the\u00a0existing script.js file and replace its content with code below.<\/p>\n\n\n\n To see the results: open index.html in your browser and open the console, Press Ctrl+Shift+J (Windows \/ Linux) or Cmd+Opt+J (Mac).<\/span><\/p><\/blockquote>\n\n\n\n In the above example, we have defined a new function called calculateTotalPrice<\/strong>, similar to how we have previously given variables a name. A function can also accept values that get passed into it called arguments. The calculateTotalPrice<\/strong> function accepts two arguments, bill and tip. The bill argument simply represents a bill that a customer may receive at a restaurant, while tip is the percentage the customer is willing to add. The purpose of the function is to calculate the total cost of the meal by adding the desired tip amount. With both the bill and tip, the function can then carry out its calculation to generate the total amount.<\/p>\n\n\n\n In order to call the function we simply provide the name of the function and include its arguments in parenthesis. In the example above we go one step further and store the result of the function call to a variable. Note the function is being called three different times for three different individuals who have all ordered dinner and want to calculate their final cost. You can quickly see the power behind functions is tied to their reuse without having to repeat code multiple times.<\/p>\n\n\n\n Did you notice the .toFixed() code included in the example above? JavaScript has many built in methods for formatting numeric data. The .toFixed method simply provides a quick way to define the number of digits after the decimal point (in this case we use 2 for currency).<\/p><\/blockquote>\n\n\n\n Functions are commonly written as expressions, whereby a variable is defined and set to the returning value of the function itself. This is better explained in an example.<\/p>\n\n\n\n In the above example, the function will behave in a similar manner to our function declaration above. The difference is that it is written as an expression where calculateTotalPrice has resulted in the value calculated from the function. One of the biggest differences between writing a function as a declaration or statement vs writing it as an expression is the flow of control or order in which everything is processed in your script.<\/p>\n\n\n\n Function expressions cannot be called earlier in the code before they are defined. In contrast to this, function declarations can be called anywhere regardless of ordering.<\/p><\/blockquote>\n\n\n\n Review the following examples.<\/p>\n\n\n\n Here we see the first call to calculateTotalPrice succeed and yield the correct amount. The second console.log function will fail because calculateTotalPriceExpression has not yet been defined and will result in an error similar to<\/p>\n\n\n\n Uncaught ReferenceError: calculateTotalPriceExpression is not defined<\/span><\/p>\n\n\n\n In the newer ECMAScript6 JavaScript engine, function expressions can be written in a shorter form called Arrow Functions<\/a>. Let’s take a look at a simple temperature conversion function.<\/p>\n\n\n\n In an arrow function, if there is only one line or single expression to return within the function, it can be further shortened by removing the surrounding curly braces and the return keyword. In addition to this, if only one argument is present, the surrounding parenthesis can also be removed.<\/p>\n\n\n\n Arrow functions with no arguments are written with empty parenthesis.<\/p>\n\n\n\n<!DOCTYPE html>\n<html>\n <head>\n <title>Bitesize JavaScript<\/title>\n <\/head>\n <body>\n <h1>Bitesize JavaScript<\/h1>\n <script src=\"script.js\"><\/script>\n <\/body>\n<\/html><\/code><\/pre>\n\n\n\n
\/**\n* Functions\n*\/\n\n\/\/ Define tip calculator function\nfunction calculateTotalPrice(bill, tip) {\n return bill * (tip + 1);\n}\n\n\/\/ Call tip calculator function and store in a variable\nlet jamesCost=calculateTotalPrice(22.00, .15)\nlet karenCost=calculateTotalPrice(34.87, .20)\nlet clareCost=calculateTotalPrice(28.98, .18)\n\nconsole.log(\"James owes: $\" + jamesCost.toFixed(2))\nconsole.log(\"Karen owes: $\" + karenCost.toFixed(2))\nconsole.log(\"Clare owes: $\" + clareCost.toFixed(2))<\/code><\/pre>\n\n\n\n
Function Declaration<\/h2>\n\n\n\n
Calling the Function<\/h3>\n\n\n\n
Function Expression<\/h2>\n\n\n\n
let calculateTotalPriceExpression = function(bill, tip) {\n return bill * (tip + 1);\n}; \/\/ Note: a semi-colon is required after a function expression<\/code><\/pre>\n\n\n\n
console.log (calculateTotalPrice(22.00, .15).toFixed(2)) \/\/ This code will work\nconsole.log (calculateTotalPriceExpression(34.87, .20).toFixed(2)) \/\/ This code will fail\n\n\/\/ Define tip calculator function\nfunction calculateTotalPrice(bill, tip) {\n return bill * (tip + 1);\n}\n\n\/\/ Define tip calculator function expression\nlet calculateTotalPriceExpression = function(bill, tip) {\n\treturn bill * (tip + 1);\n}<\/code><\/pre>\n\n\n\n
Arrow Functions<\/h2>\n\n\n\n
let toCelsius = (fahrenheit) => {\n return (5\/9) * (fahrenheit-32);\n};<\/code><\/pre>\n\n\n\n
let toCelsius = (fahrenheit) => (5\/9) * (fahrenheit-32);\nlet toCelsius = fahrenheit => (5\/9) * (fahrenheit-32); \/\/ Same as the function above except parenthesis can be omitted in situations where only one argument exists<\/code><\/pre>\n\n\n\n
let warninglog = () => console.log(\"warning\");<\/code><\/pre>\n\n\n\n