{"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

\u2192 Try it out<\/strong><\/h2>\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

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

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

Function Declaration<\/h2>\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

Calling the Function<\/h3>\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

Function Expression<\/h2>\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

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

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

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

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

Arrow Functions<\/h2>\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

let toCelsius = (fahrenheit) => {\n  return (5\/9) * (fahrenheit-32);\n};<\/code><\/pre>\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

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

Arrow functions with no arguments are written with empty parenthesis.<\/p>\n\n\n\n

let warninglog = () => console.log(\"warning\");<\/code><\/pre>\n\n\n\n

For more on Arrow functions see ECMAScript6 New Features<\/a>.<\/p><\/blockquote>\n\n\n\n

In JavaScript you have three ways to write functions, declarations, expressions, and arrow functions. How you write your own functions will depend on your own projects, however for the remainder of these introductory lessons, we will be sticking mostly to function declarations. You should now have a good understanding of functions within JavaScript and the different ways they can be defined.<\/p>\n","protected":false},"excerpt":{"rendered":"

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 […]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[24],"tags":[11499,8212,7349],"post_series":[7348],"class_list":["post-7748","post","type-post","status-publish","format-standard","hentry","category-coding","tag-bitesize-javascript","tag-cmst-388","tag-javascript","post_series-bitesize-javascript"],"yoast_head":"\nJavaScript Functions - Ian Carnaghan<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.carnaghan.com\/javascript-functions\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"JavaScript Functions - Ian Carnaghan\" \/>\n<meta property=\"og:description\" content=\"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 […]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.carnaghan.com\/javascript-functions\/\" \/>\n<meta property=\"og:site_name\" content=\"Ian Carnaghan\" \/>\n<meta property=\"article:published_time\" content=\"2018-12-22T13:50:04+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2021-03-06T20:49:32+00:00\" \/>\n<meta name=\"author\" content=\"Ian Carnaghan\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@icarnaghan\" \/>\n<meta name=\"twitter:site\" content=\"@icarnaghan\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Ian Carnaghan\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/www.carnaghan.com\/javascript-functions\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.carnaghan.com\/javascript-functions\/\"},\"author\":{\"name\":\"Ian Carnaghan\",\"@id\":\"https:\/\/www.carnaghan.com\/#\/schema\/person\/c689c24d516c51968a88b628860740a5\"},\"headline\":\"JavaScript Functions\",\"datePublished\":\"2018-12-22T13:50:04+00:00\",\"dateModified\":\"2021-03-06T20:49:32+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.carnaghan.com\/javascript-functions\/\"},\"wordCount\":713,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/www.carnaghan.com\/#\/schema\/person\/c689c24d516c51968a88b628860740a5\"},\"keywords\":[\"Bitesize JavaScript\",\"CMST 388\",\"JavaScript\"],\"articleSection\":[\"Coding\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/www.carnaghan.com\/javascript-functions\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.carnaghan.com\/javascript-functions\/\",\"url\":\"https:\/\/www.carnaghan.com\/javascript-functions\/\",\"name\":\"JavaScript Functions - Ian Carnaghan\",\"isPartOf\":{\"@id\":\"https:\/\/www.carnaghan.com\/#website\"},\"datePublished\":\"2018-12-22T13:50:04+00:00\",\"dateModified\":\"2021-03-06T20:49:32+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/www.carnaghan.com\/javascript-functions\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.carnaghan.com\/javascript-functions\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.carnaghan.com\/javascript-functions\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.carnaghan.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"JavaScript Functions\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.carnaghan.com\/#website\",\"url\":\"https:\/\/www.carnaghan.com\/\",\"name\":\"Ian Carnaghan\",\"description\":\"Software Developer, Blogger, Educator\",\"publisher\":{\"@id\":\"https:\/\/www.carnaghan.com\/#\/schema\/person\/c689c24d516c51968a88b628860740a5\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.carnaghan.com\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\/\/www.carnaghan.com\/#\/schema\/person\/c689c24d516c51968a88b628860740a5\",\"name\":\"Ian Carnaghan\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.carnaghan.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/f2aa5baca80c2be728de43a975185d91?s=96&d=retro&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/f2aa5baca80c2be728de43a975185d91?s=96&d=retro&r=g\",\"caption\":\"Ian Carnaghan\"},\"logo\":{\"@id\":\"https:\/\/www.carnaghan.com\/#\/schema\/person\/image\/\"},\"description\":\"I am a software developer and online educator who likes to keep up with all the latest in technology. I also manage cloud infrastructure, continuous monitoring, DevOps processes, security, and continuous integration and deployment.\",\"sameAs\":[\"http:\/\/www.carnaghan.com\",\"https:\/\/x.com\/icarnaghan\"],\"url\":\"https:\/\/www.carnaghan.com\/author\/icarnaghan\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"JavaScript Functions - Ian Carnaghan","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.carnaghan.com\/javascript-functions\/","og_locale":"en_US","og_type":"article","og_title":"JavaScript Functions - Ian Carnaghan","og_description":"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 […]","og_url":"https:\/\/www.carnaghan.com\/javascript-functions\/","og_site_name":"Ian Carnaghan","article_published_time":"2018-12-22T13:50:04+00:00","article_modified_time":"2021-03-06T20:49:32+00:00","author":"Ian Carnaghan","twitter_card":"summary_large_image","twitter_creator":"@icarnaghan","twitter_site":"@icarnaghan","twitter_misc":{"Written by":"Ian Carnaghan","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.carnaghan.com\/javascript-functions\/#article","isPartOf":{"@id":"https:\/\/www.carnaghan.com\/javascript-functions\/"},"author":{"name":"Ian Carnaghan","@id":"https:\/\/www.carnaghan.com\/#\/schema\/person\/c689c24d516c51968a88b628860740a5"},"headline":"JavaScript Functions","datePublished":"2018-12-22T13:50:04+00:00","dateModified":"2021-03-06T20:49:32+00:00","mainEntityOfPage":{"@id":"https:\/\/www.carnaghan.com\/javascript-functions\/"},"wordCount":713,"commentCount":0,"publisher":{"@id":"https:\/\/www.carnaghan.com\/#\/schema\/person\/c689c24d516c51968a88b628860740a5"},"keywords":["Bitesize JavaScript","CMST 388","JavaScript"],"articleSection":["Coding"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.carnaghan.com\/javascript-functions\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.carnaghan.com\/javascript-functions\/","url":"https:\/\/www.carnaghan.com\/javascript-functions\/","name":"JavaScript Functions - Ian Carnaghan","isPartOf":{"@id":"https:\/\/www.carnaghan.com\/#website"},"datePublished":"2018-12-22T13:50:04+00:00","dateModified":"2021-03-06T20:49:32+00:00","breadcrumb":{"@id":"https:\/\/www.carnaghan.com\/javascript-functions\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.carnaghan.com\/javascript-functions\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.carnaghan.com\/javascript-functions\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.carnaghan.com\/"},{"@type":"ListItem","position":2,"name":"JavaScript Functions"}]},{"@type":"WebSite","@id":"https:\/\/www.carnaghan.com\/#website","url":"https:\/\/www.carnaghan.com\/","name":"Ian Carnaghan","description":"Software Developer, Blogger, Educator","publisher":{"@id":"https:\/\/www.carnaghan.com\/#\/schema\/person\/c689c24d516c51968a88b628860740a5"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.carnaghan.com\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/www.carnaghan.com\/#\/schema\/person\/c689c24d516c51968a88b628860740a5","name":"Ian Carnaghan","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.carnaghan.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/f2aa5baca80c2be728de43a975185d91?s=96&d=retro&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/f2aa5baca80c2be728de43a975185d91?s=96&d=retro&r=g","caption":"Ian Carnaghan"},"logo":{"@id":"https:\/\/www.carnaghan.com\/#\/schema\/person\/image\/"},"description":"I am a software developer and online educator who likes to keep up with all the latest in technology. I also manage cloud infrastructure, continuous monitoring, DevOps processes, security, and continuous integration and deployment.","sameAs":["http:\/\/www.carnaghan.com","https:\/\/x.com\/icarnaghan"],"url":"https:\/\/www.carnaghan.com\/author\/icarnaghan\/"}]}},"views":307,"_links":{"self":[{"href":"https:\/\/www.carnaghan.com\/wp-json\/wp\/v2\/posts\/7748"}],"collection":[{"href":"https:\/\/www.carnaghan.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.carnaghan.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.carnaghan.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.carnaghan.com\/wp-json\/wp\/v2\/comments?post=7748"}],"version-history":[{"count":0,"href":"https:\/\/www.carnaghan.com\/wp-json\/wp\/v2\/posts\/7748\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.carnaghan.com\/wp-json\/wp\/v2\/media?parent=7748"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.carnaghan.com\/wp-json\/wp\/v2\/categories?post=7748"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.carnaghan.com\/wp-json\/wp\/v2\/tags?post=7748"},{"taxonomy":"post_series","embeddable":true,"href":"https:\/\/www.carnaghan.com\/wp-json\/wp\/v2\/post_series?post=7748"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}