JavaScript Functions: Why They're Essential to Understand? | Easy Guide - Part2
Tags: javascript, beginners, functional, programming
Published: 2022-12-08 10:42:54

<!-- wp:paragraph -->
<p></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We looked at <a href="https://nerdleveltech.com/javascript-functions-why-theyre-essential-to-understand-easy-guide/" target="_blank" rel="noreferrer noopener">what functions are</a> and the different types of declarations. We also looked at parameters, scope, hosting, and creating methods. Please <a href="https://nerdleveltech.com/javascript-functions-why-theyre-essential-to-understand-easy-guide/" target="_blank" rel="noreferrer noopener">refer back to JavaScript Functions part one</a> for any of the above topics and more if you want to understand this blog post better.</p>
<!-- /wp:paragraph -->

<!-- wp:spacer -->
<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->

<!-- wp:heading {"level":3} -->
<h3>Table of Content:</h3>
<!-- /wp:heading -->

<!-- wp:html -->
<div class="toc">

<ul>

<li><a rel="noopener" href="#Arrow">Arrow Functions</a></li>

<li><a rel="noopener" href="#Constructors">Constructors</a></li>

<li><a rel="noopener" href="#Modules">Modules</a></li>

<li><a rel="noopener" href="#Closures">Closures </a></li>

<li><a rel="noopener" href="#Recursion">Recursion</a></li>

<li><a rel="noopener" href="#Asynchronous">Asynchronous Functions</a></li>

<li><a rel="noopener" href="#Conclusion"> Conclusion </a></li>

</ul>

</div>
<!-- /wp:html -->

<!-- wp:spacer -->
<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->

<!-- wp:image {"align":"center","id":885,"sizeSlug":"full","linkDestination":"none"} -->
<figure class="wp-block-image aligncenter size-full"><img src="https://nerdleveltech.com/wp-content/uploads/nick-fewings-zF_pTLx_Dkg-unsplash.webp" alt="Arrow to the right" class="wp-image-885"/><figcaption class="wp-element-caption">Arrow to the right</figcaption></figure>
<!-- /wp:image -->

<!-- wp:heading -->
<h2 id="Arrow">Arrow Functions</h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3>What are arrow functions?</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Arrow functions are a different way of writing a function expression, and a shortcut to writing an anonymous <a href="https://nerdleveltech.com/javascript-foreach-is-not-a-function-and-what-to-do/" target="_blank" rel="noreferrer noopener">function</a>. For the next example, we'll have an expression function and convert it to an arrow function:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>let nerd = function(level) {

  return level + " level"

}

console.log(nerd("nerd"))

//output: nerd level

Now by converting it to an arrow, notice what we will do in the next lines:

let nerd = (level) =&gt; {

  return level + " level"

}

console.log(nerd("nerd"))

//output: nerd level</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>We rid of the keyword function and we could also rid of the parentheses if the parameters only one parameter and if the function only returns one statement you can get rid of the keyword return and the <strong><em>Curly brackets</em></strong> like:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>let nerd = (level) =&gt; level + " level"

console.log(nerd("nerd"))

// output: nerd level</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Because you can’t use this keyword with an arrow function, still you can shorthand the function inside an object. Basically, you get rid of the “:“ and <a href="https://nerdleveltech.com/a-guide-to-convert-strings-to-arrays-and-vice-versa-in-javascript/" target="_blank" rel="noreferrer noopener">function</a> keyword.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>const nerdsInfo = {

  social: {

    blog: "nerdleveltech.com",

    twitter: "twitter.com/NerdLevelTech",

    reddit: "www.reddit.com/user/NerdLevelTech"

    },

      printSocial () {

      console.log(`Social links: 

      ${this.social.blog} 

      ${this.social.twitter}

      ${this.social.reddit}`)

    } 

}

nerdsInfo.printSocial()

// output: Social links: 

//     nerdleveltech.com 

//     twitter.com/NerdLevelTech

//     www.reddit.com/user/NerdLevelTech</code></pre>
<!-- /wp:code -->

<!-- wp:spacer {"height":"20px"} -->
<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->

<!-- wp:paragraph -->
<p><strong>Things to keep in mind regarding arrow functions:</strong></p>
<!-- /wp:paragraph -->

<!-- wp:list {"fontSize":"medium"} -->
<ul class="has-medium-font-size"><!-- wp:list-item -->
<li>The arrow functions do not have their own binding to the “this“ keyword</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>The Arguments array-like object is not available with the arrow function</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>You can use the “rest“ operator to get to the arguments</li>
<!-- /wp:list-item --></ul>
<!-- /wp:list -->

<!-- wp:spacer -->
<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->

<!-- wp:image {"align":"center","id":886,"sizeSlug":"full","linkDestination":"none"} -->
<figure class="wp-block-image aligncenter size-full"><img src="https://nerdleveltech.com/wp-content/uploads/marcel-strauss-rxGN4Z6wN5s-unsplash.webp" alt="lego constructor" class="wp-image-886"/><figcaption class="wp-element-caption">lego constructor</figcaption></figure>
<!-- /wp:image -->

<!-- wp:heading -->
<h2 id="Constructors">Constructors</h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3>What are constructors?</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>You can create reusable objects in more than one way. So let's explore another popular pattern for creating them called the constructor pattern. The constructor is a way to write classes with JavaScript functions. We can also say the following</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Its JavaScript functions act like classes:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>let Nerd = function (){

  let level;

}

let firstNerd = new Nerd

firstNerd.level = "Vito"

console.log(firstNerd)</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>In this above example, we start the first letter big, as it’s a familiar thing with this pattern. notice also “let firstNerd = new Nerd“ that’s name an instance of the class named Nerd accessing the property inside the Nerd function that acts like a class.</p>
<!-- /wp:paragraph -->

<!-- wp:spacer {"height":"20px"} -->
<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->

<!-- wp:paragraph -->
<p>Speaking of the properties, JavaScript has an access to a very special type of property called a prototype. Using the example above but adding a value to the property prototype:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>let Nerd = function (){

  let level;

}

Nerd.prototype = {

  study: function(what) {

    return (console.log(what))

  }

}

let firstNerd = new Nerd

firstNerd.level = "Nerd"

firstNerd.study("JS")

console.log(firstNerd.level)

//output: JS Nerd</code></pre>
<!-- /wp:code -->

<!-- wp:spacer {"height":"20px"} -->
<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->

<!-- wp:paragraph -->
<p>Or we can use the prototype "sound" separately with the animal's classes example, like in the following example:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>//Now we create two pets
let sound = function(hear) {

  return (console.log(hear))

}

let Dog = function() {

  let name;

}

let Cat = function() {

  let name;

}

Dog.prototype.sound = sound
Cat.prototype.sound = sound

// let’s create the Dog instances: 

let myDog = new Dog

myDog.name = "Jojo"

myDog.sound = "woof"

// let’s create the Cat instances: 

let myCat = new Cat

myCat.name = "Gogo"

myCat.sound = "meaw"

console.log(myCat, myDog)
// output: Cat { name: 'Gogo', sound: 'meaw' } Dog { name: 'Jojo', sound: 'woof' }</code></pre>
<!-- /wp:code -->

<!-- wp:spacer {"height":"20px"} -->
<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->

<!-- wp:paragraph -->
<p><strong>Things to keep in mind with the constructors:</strong></p>
<!-- /wp:paragraph -->

<!-- wp:list {"fontSize":"medium"} -->
<ul class="has-medium-font-size"><!-- wp:list-item -->
<li>Notice that we repeated some properties like name on both functions Cat and Dog. You can consider having a higher function called pet or animal that has this name, then inherit it, so you don't repeat yourself.</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>Now that this has happened, you'll face another challenge with more extensive systems. Getting all the objects and properties right up front will complicate your design process.</li>
<!-- /wp:list-item --></ul>
<!-- /wp:list -->

<!-- wp:spacer -->
<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->

<!-- wp:image {"align":"center","id":887,"sizeSlug":"full","linkDestination":"none"} -->
<figure class="wp-block-image aligncenter size-full"><img src="https://nerdleveltech.com/wp-content/uploads/volodymyr-hryshchenko-L0oJ4Dlfyuo-unsplash.webp" alt="Multiple pieces of woods" class="wp-image-887"/><figcaption class="wp-element-caption">Multiple pieces of woods</figcaption></figure>
<!-- /wp:image -->

<!-- wp:heading -->
<h2 id="Modules">Modules</h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3>What Are modules?</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>The Modules are library code bases that let you store the function or functions you need into a file. That file can be imported and exported with your project or across different projects. Now with this imagine how organized your code will be instead of repeating your code throughout your project and all your different other projects.</p>
<!-- /wp:paragraph -->

<!-- wp:spacer {"height":"20px"} -->
<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->

<!-- wp:heading {"level":3} -->
<h3>How to write modules?</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>The way we write modules has changed for the better with the recent JavaScript version. All you need to do is write the functions and use the keyword export before the keyword function.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>export function add (...args){

  return args.reduce(function(a,c) {

    return a + c

    })

}</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Let’s say we created a file with this above function called modTest.js</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Now we can go and import it inside another file:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>import { add } from "./modTest.js"</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>We use the destruction above, so we can import as many functions as we want from that file. Although it's only one function, you need to get used to the syntax with a non-default export function. e.g. export default function add (...args) {}</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>or</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>import addSum from "./modTest.js" notice that you named it with a different name when imported, that change should happen according to your name convention.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>or</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>import {addSum as sumAdd} from “./modTest.js“ - destructing and change the name</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>or</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>import * as funcs from “./modTest.js“ The asterisk means all the functions within the prefix of funcs, and now you could use this syntax to call the functions with it like that: “funcs.add”</p>
<!-- /wp:paragraph -->

<!-- wp:spacer {"height":"20px"} -->
<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->

<!-- wp:paragraph -->
<p><strong>Things to keep in mind about Modules:</strong></p>
<!-- /wp:paragraph -->

<!-- wp:list {"fontSize":"medium"} -->
<ul class="has-medium-font-size"><!-- wp:list-item -->
<li>With Modules, you create local variables within that code base without polluting your main code</li>
<!-- /wp:list-item --></ul>
<!-- /wp:list -->

<!-- wp:spacer -->
<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->

<!-- wp:image {"align":"center","id":877,"sizeSlug":"full","linkDestination":"none"} -->
<figure class="wp-block-image aligncenter size-full"><img src="https://nerdleveltech.com/wp-content/uploads/closure-gif.gif" alt="" class="wp-image-877"/><figcaption class="wp-element-caption">Friends show closure gif</figcaption></figure>
<!-- /wp:image -->

<!-- wp:heading -->
<h2 id="Closures">Closures</h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3>What is closure? </h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Closures use certain aspects of scope in JavaScript, remember the scope refers to the availability of variables in your code. There is a certain type of scope called lexical scope. which is an inner function that gets access to a parent's scope resources and variables.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The closure is created by JavaScript when you use a function or the keyword “function“ inside another function. Here, the child function (or any other function within the parent) can access the parent's variables and the parent's variables can remember the environment that was created and any changes that were made to its values from the child function. Have a look here at this example, it goes like that:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>function counter() {

  let num = 0

  return function() {

    console.log(num++)

  }

}

let numbers = counter()

numbers() // 0

numbers() // 1

numbers() // 2</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>That counter function has an internal function that we call (Closure) Why? because it used the keyword “function” inside it. That allows the variable to remember the value of “num”, in the parent function. Although we have increased and returned it inside another function. But JavaScript kept its value updated every time you run the function.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>In the next example. The object will have two methods. We call them methods because they are functions inside an object.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p></p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>function myCounterObj() {

  let num = 1

  return {

    show: () =&gt; console.log(num),

    increment: () =&gt; num++

  }

}

let myNum = myCounterObj() //creating instance

myNum.show() // 1

myNum.increment() // incremented by ++ 

myNum.show() // 2

myNum.increment()

myNum.show() // 3</code></pre>
<!-- /wp:code -->

<!-- wp:spacer -->
<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->

<!-- wp:image {"align":"center","id":888,"sizeSlug":"full","linkDestination":"none"} -->
<figure class="wp-block-image aligncenter size-full"><img src="https://nerdleveltech.com/wp-content/uploads/danny-howe-U7Jw_KFHG_0-unsplash.webp" alt="Neon red lights" class="wp-image-888"/><figcaption class="wp-element-caption">Neon red lights</figcaption></figure>
<!-- /wp:image -->

<!-- wp:heading -->
<h2 id="Recursion">Recursion</h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3>What is recursion?</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Recursion happens whenever a function call itself, of course, that raises the question of how we stop the function, and what if the function kept calling itself indefinitely?</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>This is when we need to put a stop condition if met the recursion stops. We call that the “base case”. Or we can pass an argument as the number limit of how the function should call itself, like in the Fibonacci example below:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>// Without a base case

function itself() {

  itself()

}</code></pre>
<!-- /wp:code -->

<!-- wp:code -->
<pre class="wp-block-code"><code>// With a base case

function increment(number, maxNumber) {

  if (number &gt; maxNumber) return

  console.log(number)

  increment(number+1, maxNumber)

}

increment(1, 10)</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>In the next example one of the most popular interview questions for functions to build a Fibonacci sequence, and will have the solution using the recursion technique:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>let fib = function(count) {

  if (count === 1) return &#91;0, 1] // the base case

  let arr = fib(count -1)

  let sum = arr&#91;arr.length -1] + arr&#91;arr.length -2]

  arr.push(sum)

  console.log(arr)

  return arr

}

fib(7) // the function will be called 7 times according to the variable “count” value.

// output: 

// Fib: 7

// Fib: 6

// Fib: 5

// Fib: 4

// Fib: 3

// Fib: 2

// Fib: 1

// arr:

// &#91; 0, 1, 1 ]

// &#91; 0, 1, 1, 2 ]

// &#91; 0, 1, 1, 2, 3 ]

// &#91; 0, 1, 1, 2, 3, 5 ]

// &#91; 0, 1, 1, 2, 3, 5, 8 ]

// &#91; 0, 1, 1,  2, 3, 5, 8, 13 ]

// So as we can see the recursion works as a backwards loop by looking at the fib value each time</code></pre>
<!-- /wp:code -->

<!-- wp:spacer -->
<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->

<!-- wp:image {"align":"center","id":889,"sizeSlug":"full","linkDestination":"none"} -->
<figure class="wp-block-image aligncenter size-full"><img src="https://nerdleveltech.com/wp-content/uploads/oscar-nord-R0kubmm8L2Q-unsplash.webp" alt="Airplanes show" class="wp-image-889"/><figcaption class="wp-element-caption">Airplanes show</figcaption></figure>
<!-- /wp:image -->

<!-- wp:heading -->
<h2 id="Asynchronous">Asynchronous Functions</h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3>What are asynchronous functions?</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Functions that wait for certain conditions or things to happen, You can build a function that only works when something else triggers it. In JavaScript, we can create this kind of function using the keywords “Async / Await“</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Another expression is called promise, which is that a certain condition needs to be done, met, or returned first to trigger the function to run or complete, we mentioned that part above.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>async function canDo() {

  return console.log("Currently doing it...")

}

canDo().then (task =&gt; {

  console.log("yes you did it!")

})

// output: 

// Currently doing it...

// yes you did it!</code></pre>
<!-- /wp:code -->

<!-- wp:code -->
<pre class="wp-block-code"><code>async function doIt() {

  return console.log("Preparing it...")

}

async function canDo() {

  await doIt()

  return console.log("Currently doing it...")

}

canDo()

// output: 

// Preparing it...

// Currently doing it...</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Although we call the canDo() function, the first string printed was the string in the doIt() function, why?</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Because we had to wait for the doIt() function to happen before we could run the rest of canDo() function’s statements and return it.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The most practical use of async/await inside JavaScript is fetching data from an external source. Once the data is fetched, the promise is fulfilled.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>async function getSocial() {

  // Once the data received then the promised fulfilled.

  const result = await fetch("https://links.socialData.json") 

  const data = await result.json() 

  return data

}

async function printSocial() {

  try{

    const social = await getSocial()  

    console.log(social)

  } catch {

    console.log("Error: the data not available")

  }  

}

printSocial()

// output:

// Error: the data not available</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>We tried to fetch from a non-existing URL to demo the try/catch statement as well. if any error happens we could see what we do with it by using try{} and catch{}.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>try{</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>// any code you want to work</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>} catch {</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>// if it didn’t work, do the following with the error you caught</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>}</p>
<!-- /wp:paragraph -->

<!-- wp:spacer -->
<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->

<!-- wp:image {"align":"center","id":890,"sizeSlug":"full","linkDestination":"none","style":{"color":{}}} -->
<figure class="wp-block-image aligncenter size-full"><img src="https://nerdleveltech.com/wp-content/uploads/pexels-ann-h-1888005.jpg" alt="Conclusion word in separate characters" class="wp-image-890"/><figcaption class="wp-element-caption">Conclusion word in separate characters</figcaption></figure>
<!-- /wp:image -->

<!-- wp:heading -->
<h2 id="Conclusion">Conclusion Why functions are essential to understand?</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Functions can be applied in a variety of ways. By writing them in these chunks of code, you're not only organizing your code, you're also saving yourself a ton of time by not repeating yourself with the same functionality in case you want it again in your project. And believe me, you will.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The more you practice and explore functions the more you achieve to write concise and clean code that can save you time and money. Take a look at these <a href="https://nerdleveltech.com/best-web-development-books-you-need-to-learn/" target="_blank" rel="noreferrer noopener">great resources</a> on functions:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><!-- wp:list-item -->
<li><a target="_blank" rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions">MDM Functions</a></li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li><a target="_blank" rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures">Closures</a></li>
<!-- /wp:list-item --></ul>
<!-- /wp:list -->