{"id":42,"date":"2018-04-01T00:16:24","date_gmt":"2018-04-01T00:16:24","guid":{"rendered":"https:\/\/tinjurewp.com\/jsblog\/?p=42"},"modified":"2018-04-01T00:16:24","modified_gmt":"2018-04-01T00:16:24","slug":"understanding-javascript-functions-the-basics","status":"publish","type":"post","link":"https:\/\/learncode.tinjurewp.com\/understanding-javascript-functions-the-basics\/","title":{"rendered":"Understanding JavaScript Functions &#8211; The Basics"},"content":{"rendered":"<p class=\"note\"><em>This post is work-in-progress learning-note and still in active development and updated regularly<\/em>.<\/p>\n<p>A JS <strong>function<\/strong> is defined as reusable block of codes that are defined at one time and used later repeatedly \u00a0whenever they are needed. \u00a0This process avoids writing the same code repeatedly in different part of the program and \u00a0code repetition. \u00a0JS functions are the building blocks of the program.<\/p>\n<p>There are some common built-in functions, like <code>alert( message )<\/code>,\u00a0 <code>write(message)<\/code>, <code>prompt( ),<\/code> and <code>confirm(question)<\/code>. Often developers write their own custom reusable block of codes as functions to be called later or whenever needed.<\/p>\n<p>In this post, basic concept of function declaration, function expression &amp; arrow function are discussed. Difference been function declaration and function expression are discussed separately in another post.<\/p>\n<h5>Function Declaration<\/h5>\n<p>JS function declaration (also known as function statement, function definition) is defined using <code>function<\/code> keyword followed by name and parentheses <code>()<\/code>.<\/p>\n<ul>\n<li>The <strong>name<\/strong> after parentheses <code>( )<\/code> may contain one or more <strong>parameter<\/strong> names (separated by commas:\u00a0 <code>,<\/code> ).<\/li>\n<li>The block of codes to be executed are placed after the parentheses inside curly braces:\u00a0<code>{ }<\/code><\/li>\n<li>Naming rules for function <strong>name<\/strong> are similar to naming variables (eg. letters, digits, underscores, and dollar signs).<\/li>\n<li>For multiple words <em>camelCase<\/em> pattern is followed.<\/li>\n<li>Semicolons ( <code>;<\/code> ) after code blocks <code>{\u00a0 }<\/code> not required like conditional loop syntax construct.<\/li>\n<\/ul>\n<h6>1.Basic Syntax<\/h6>\n<pre><code class=\"language-javascript\">\/\/Initialize function\nfunction name() { \/\/no parameters\n    code block to be executed\n}\n\n\/\/invoke the function\nname(); \/\/ no arguments\n\n\/\/FUNCTION WITH PARAMETERS\n\/\/Initialize the function\nfunction name(parameter1, parameter2) {\n    code block to be executed\n}\n\n\/\/invoke the function using parameters\nname(arg1, arg2);<\/code><\/pre>\n<p>In the example above, the function is declared with <code>function<\/code> keyword followed by <strong>name<\/strong> of the function <code>name<\/code>. In this simple function, there are no parameters and arguments.<\/p>\n<pre><code class=\"language-javascript\">\/\/ Initialize function\nfunction helloWorld() { \/\/ (1) function declaration \n   console.log(&quot;Hello, World!&quot;);\/\/ (2) output message\n}\n\n\/\/ Invoke function\nhelloWorld(); \/\/ (3)\n\n\/\/OUTPUT\nHello, World<\/code><\/pre>\n<p>In the above example, a simple function helloWorld is declared (1) without any parameter. In the body of the function, a string of welcome of message is logged out (2) in the window console (this is what this function does). When the function helloWorld() is invoked, it outputs the message from (2).<\/p>\n<p>It is important to note that <code>( )<\/code> after function is important to get expected output value, otherwise it outputs function string as shown below.<\/p>\n<pre><code class=\"language-javascript\">\/\/function invocation with ()\nhelloWorld; \/\/ note no ()\n\n\/\/OUTPUT in chrome\n\u0192 helloWorld() {\n   console.log(&quot;Hello, World!&quot;);\n}<\/code><\/pre>\n<h6>2. Function with Parameters<\/h6>\n<p>Lets define a function (below) named <code>userName<\/code> with two parameters:<\/p>\n<pre><code class=\"language-javascript\">\/\/ Initialize function\nfunction userName(firstname, lastname) {\n   console.log(&#039;User fistname is &#039; + firstname);\n   console.log(&#039;User lastname is &#039; + lastname);\n}\n\n\/\/ Invoke function\nuserName(&#039;Mike&#039;, &#039;Smith&#039;);\n\n\/\/OUTPUT\nUser fistname is Mike\nUser lastname is Smith<\/code><\/pre>\n<p>In JS function, we often encounter terms <strong>parameters<\/strong> and <strong>arguments<\/strong> are being used interchangeably. But there is subtle difference between these two terms. When we define or declare a function &#8211; the function name <code>()<\/code> parentheses may contain empty (no parameters) or parameters separated by comma which act as local variables. In the above example, the <code>userName<\/code> function has two parameters <code>firstname<\/code> and <code>lastname<\/code>.<\/p>\n<p>Functions <strong>arguments<\/strong> on the hand, are values the parameters receive when a function is is called (or invoked). In the above example, <code>Mike<\/code> and <code>Smith<\/code> are arguments passed the calling function <code>userName()<\/code>.<\/p>\n<h6>3. Function Invocation<\/h6>\n<p>By defining a function does not return a value, it simply names the function with blocks of codes for action when it is invoked. The function invocation is also called <em>execution<\/em>, <em>calling<\/em>, or <em>applying <\/em>it. A function is invoked using function name followed by: <code>( )<\/code> The codes inside the code block (<em>eg<\/em>. inside curly braces: <code>{ }<\/code> ) is invoked or executed by JS code or self-invoking functions (eg. <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Glossary\/IIFE\" target=\"_blank\" rel=\"noopener\">IIFE<\/a>), automatically.<\/p>\n<pre><code class=\"language-javascript\">\/\/initialize function\nfunction userName(name) {\n  console.log( name );\n}\n\n\/\/invoke (call) function\nuserName(&#039;Dave&#039;); \n\n\/\/OUTPUT\nDave<\/code><\/pre>\n<p>In this example a <code>userName<\/code> function is defined to with a single parameter variable <code>name<\/code>. When the function <code>userName<\/code> was invoked with an argument pass on value of <code>&#039;Dave&#039;<\/code> as <code>username(&#039;Dave&#039;);<\/code> the function was executed and its value was printed in the browser console.<\/p>\n<h6>4. Invoking of Function with Parameters<\/h6>\n<p>When a function with parameters is invoked, arguments values corresponding to the defined function parameters are passed (or copied) to the function parameters (also called local variables). Then the function executes based on those passed on values.<\/p>\n<p>Function parameters and function arguments are different. <strong>Parameters<\/strong> are variables listed in the function definition, whereas <strong>arguments<\/strong> are values passed to the function during function invocation.<\/p>\n<pre><code class=\"language-javascript\">\/\/ Initialize of function \nfunction multiply(a, b, c) \n  { return a * b * c; } \n\n\/\/ Invoke function with missing argument \nmultiply(5, 3);\n\n\/\/Output\nNaN\n\n\/\/ Invoke function extra argument \nmultiply(5, 3, 4, 5);\n\n\/\/Output\n60  \/\/it ignores the extra argument<\/code><\/pre>\n<p><strong>Function Arguments Rules:<\/strong><\/p>\n<ul>\n<li>Missing or unequal arguments in function call does not throw an error<\/li>\n<li>Function with missing argument (or less than define) return : undefined<\/li>\n<li>Function call with no-argument \u2013 returns : NaN<\/li>\n<li>Function call with extra arguments than the defined parameters will be ignored.<\/li>\n<\/ul>\n<h6>5. Function Return<\/h6>\n<p>The <code>&lt;strong&gt;return&lt;\/strong&gt;<\/code><strong> statement<\/strong> ends function execution and specifies a value to be returned to the function caller.<\/p>\n<ul>\n<li>A value can be constant, a <code>var<\/code> or any calculation<\/li>\n<li>Value can return by a call of function<\/li>\n<li>Function has to run to determine its value<\/li>\n<li>If a value is required in multiple places, assigning a value to a variable is more efficient (eg. function expression).<\/li>\n<\/ul>\n<p>By using <code>return<\/code> keyword, a function can be instructed what value to return. For example:<\/p>\n<pre><code class=\"language-javascript\">\/\/ Initialize function\nfunction multiply(a, b) {\n    return a * b;\n}\n\n\/\/ Invoke function \nmultiply(5, 3);\n\n\/\/OUTPUT\n15<\/code><\/pre>\n<p>In the example above, <code>return a * b;<\/code>\u00a0code block instructs to multiply the two parameters (<code>a<\/code> &amp; <code>b<\/code>) and return the value to caller function <code>multiply<\/code>. The return keyword also stops execution of function.<\/p>\n<p>In case of <em>function expression<\/em>, <code>return<\/code> keyword assign the value to a variable.<\/p>\n<h5>Function Expression<\/h5>\n<h6>1. Basic Syntax<\/h6>\n<pre><code class=\"language-javascript\">\/\/Initialize function\nvar varName = function(param1, param2, .., paramN) {\n    code block;\n}\n\n\/\/Invoke function area\nvarName(arg1, arg2, .., argN);<\/code><\/pre>\n<p>Statements involving functions which do not start with <code>function<\/code> are function expressions.<\/p>\n<pre><code class=\"language-javascript\">\/\/ Assign add function to math variable\nlet math = function add(a, b) {  \/\/ Named function\n    return a + b;\n}\n\n\/\/ Invoke function to find the math value\nmath(20, 5);\n\n\/\/OUTPUT\n25<\/code><\/pre>\n<p>In the above example, the value of <code>add()<\/code> functions were assigned to a new variable named <code>sum<\/code>. In this case the sum variable is function. This type of function declaration is called named expression.<\/p>\n<p>We can also rewrite the above example into an <strong>Anonymous Function Expression<\/strong> (below) without function name after <code>function<\/code> keyword.<\/p>\n<pre><code class=\"language-javascript\">\/\/ Assign value of the function to math variable\nlet math = function(a, b) {    \/\/ anonymous function\n    return a + b;\n}\n\n\/\/ Invoke function to find the math value\nmath(20, 100);\n\n\/\/OUTPUT\n120<\/code><\/pre>\n<p>When functions are stored in variables, as in the above example, the function is invoked using variable name (eg. math). There is no need of function name. However, having named function expression helps in debugging.<\/p>\n<h5>Arrow Function<\/h5>\n<p>Arrow Functions are similar to anonymous function expression but with shorter syntax and without names (always anonymous). Sometime they are also referred as <em>one line mini functions<\/em>. Basic explanation of the arrow functions are described below more advanced features are discussed in <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Guide\/Functions#Arrow_functions\" target=\"_blank\" rel=\"noopener\">Arrow Functions on the Mozilla Developer Network<\/a>.<\/p>\n<h6>1. Basic Syntax (<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Functions\/Arrow_functions\" target=\"_blank\" rel=\"noopener\">MDN<\/a>)<\/h6>\n<pre><code class=\"language-javascript\">(param1, param2, \u2026, paramN) =&gt; { statements } \n(param1, param2, \u2026, paramN) =&gt; expression\n\/\/ equivalent to: =&gt; { return expression; } \n\n\/\/ Parentheses are optional when there&#039;s only one parameter name:\n(singleParam) =&gt; { statements }\nsingleParam =&gt; { statements }\n\n\/\/ with no parameters should be written with a pair of parentheses.\n() =&gt; { statements }<\/code><\/pre>\n<p>Using our previous example with two parameters, lets write an arrow function as follows. In arrow function, the initialization is done using <code>=&gt;<\/code> (fat arrow) instead of <code>function<\/code> keyword. Parameters are passed in small parentheses: <code>( )<\/code><\/p>\n<pre><code class=\"language-javascript\">\/\/Initialize the function as anonymous function expression\nlet add = function (x, y) {\n  return x + y;\n}\n\n\/\/initialize as arrow function\nlet add = (x, y) =&gt; {\n  return x + y;\n}\n\n\/\/Invoke arrow function\nadd(20, 5);\n\n\/\/OUTPUT\n25<\/code><\/pre>\n<h6>2. Arrow Function with one or no parameters<\/h6>\n<p>If there is only <strong>one<\/strong> parameter, then parentheses are not required.<\/p>\n<pre><code class=\"language-javascript\">\/\/Initialize triple function\nlet triple = x =&gt; {\n  return x * 3;\n}\n\/\/initialize in a single line as follows\nlet triple = x =&gt; x * 3;\n\n\/\/Invoke function triple\ntriple(3);\n\n\/\/OUTPUT\n9<\/code><\/pre>\n<p>In case of single line curly brackets <code>{ }<\/code> and <code>return<\/code> keyword could be omitted making the function even shorter.<\/p>\n<p>If there is no parameter, there must have empty parentheses <code>( )<\/code> as shown in the following example.<\/p>\n<pre><code class=\"language-javascript\">\/\/Initialize no parameter arrow function\nlet greeting = () =&gt; console.log(&quot;Hello, World!&quot;);\n\n\/\/invoke our greeting function\ngreeting();\n\n\/\/OUTPUT\nHello, World!<\/code><\/pre>\n<p>More advanced features of arrow functions will be discussed in another post.<\/p>\n<p><strong>Resources &amp; Further Reading:<\/strong><\/p>\n<p>While preparing this post, I have referred the following references extensively. Please to refer original posts for more detailed information.<\/p>\n<ul>\n<li><a href=\"https:\/\/dmitripavlutin.com\/6-ways-to-declare-javascript-functions\/\" target=\"_blank\" rel=\"noopener\">6 ways to declare JavaScript functions<\/a> &#8211; by <em>Dmitri Pavlutin<\/em> (<a href=\"https:\/\/dmitripavlutin.com\" target=\"_blank\" rel=\"noopener\"><strong>dmitripavlutin.com<\/strong><\/a>)<\/li>\n<li><a href=\"https:\/\/javascript.info\/function-expressions-arrows#function-expression-vs-function-declaration\" target=\"_blank\" rel=\"noopener\">Function Expression vs Function Declaration<\/a> &#8211; <a href=\"https:\/\/javascript.info\/\" target=\"_blank\" rel=\"noopener\">The Modern JavaScript Tutorial<\/a><\/li>\n<li><a href=\"https:\/\/zellwk.com\/blog\/js-functions\/\" target=\"_blank\" rel=\"noopener\">Understanding JavaScript Functions<\/a> &#8211; by <em>Zell Liew<\/em> (<a href=\"https:\/\/zellwk.com\/blog\/\" target=\"_blank\" rel=\"noopener\"><strong>zellwk.com\/blog<\/strong><\/a>)<\/li>\n<li><a href=\"https:\/\/hackernoon.com\/javascript-functional-composition-for-every-day-use-22421ef65a10\" target=\"_blank\" rel=\"noopener\">Functional JavaScript: Function Composition For Every Day\u00a0Use<\/a> &#8211; by <em>Joel Thoms<\/em> (<a href=\"https:\/\/hackernoon.com\/\" target=\"_blank\" rel=\"noopener\"><strong>hackernoon.com<\/strong><\/a>)<\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>This post is work-in-progress learning-note and still in active development and updated regularly. A JS function is defined as reusable block of codes that are defined at one time and used later repeatedly \u00a0whenever they are needed. \u00a0This process avoids writing the same code repeatedly in different part of the program and \u00a0code repetition. \u00a0JS [&hellip;]<\/p>\n","protected":false},"author":3,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_crdt_document":"","footnotes":""},"categories":[41,4],"tags":[],"class_list":["post-42","post","type-post","status-publish","format-standard","hentry","category-functions","category-javascript"],"_links":{"self":[{"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/posts\/42","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/comments?post=42"}],"version-history":[{"count":0,"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/posts\/42\/revisions"}],"wp:attachment":[{"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/media?parent=42"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/categories?post=42"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/tags?post=42"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}