Author-avater

Nebeolisa Samson


THE NON-TAUGHT OF JAVASCRIPT

JavaScript-image

JavaScript is the programming language of the web, it is the world's most popular programming language and is serves as a great first language for anyone brand new to coding.

The topics in javaScript are quite numerous, it will be hard to cover all parts of the language in an Online tutorial. Recently, developers tends to learn from Youtube, BootCamps, Online Courses and or Private Tutorials. However the topics taught in these medias are only based on what the tutors feel are the basic part of the language and what the tutors understand well.

As a developer moving forward with javaScript, a time will come when you will be in search of a particular syntax to either solve a problem you encountered or to fix a bug, then it's likely that you will find a solution but the syntax used in the code snippet is not a syntax you are familiar with, but it is still a javaScript syntax. Don't be puzzled when you come across this type of situation, because just like the other syntax and formula you have learned from you tutors, the javaScript syntaxes used in the code you are seeing are as useful as the other part that you can easily come across but it is left for you to go and do some research on them and learn them on your own time.

In this article, we will learn five of the Non-Taught parts of JavaScript that I feel is also worth knowing.

JavaScript Recursion

As a beginner in javaScript it is likely that you will come across a function and inside the function you will notice that a function with the same name as the parent function was called. And you will be wondering if it's a mistake or a callback of a different function created somewhere else. Well it's not, it is just JavaScript Recursion.


  function recursion() {
    // ...
    recursion() // calling one's self
    // ...   
  }    
  recursion() 

Recursion - is a process of calling one's self. In javaScript a function that calls itself is called a recursive function. Generally, recursive functions are used for solving or breaking down big problems into smaller ones. It is especially good for working on things that have many possible branches and are too complex for an iterative approach . Good examples of when this can be used in a function would be searching through a file system and or quiksort.

A recursive function always calls itself until it meets some condition to stop calling itself. If no conditions are met it will call itself indefinitely. So a recursive function typically looks like :


  function recursion() {         
    if (condition) {
      // stop calling    
      // ...
    } else {
     recursion () // calling one's self
    }
  }
  recursion()  

JavaScript Recursion Function Examples

Just like a simple for loop iteration, let's try counting down numbers using a recursive function, starting from 5 down to 1.


  function countDown(myNumber) {
    console.log(myNumber);
  // calling itself and substracting each count by 1
    countDown(myNumber - 1);       
  }
  recursion(5) 

This countDown(5) will run until it exceeds its call stack and it will return the following result :

Uncaught RangeError: Maximum call stack size exceeded.

So in order to get the wanted result, using an if else condition will be an ideal choice.


  function countDown(myNumber) {
    console.log(myNumber);
    let nextNumber = myNumber - 1 // substracting each count by 1 
    // if nextNumber is greater than 0 run next code
    if (condition > 0) { 
      countDown(nextNumber) // calling one's self 
    } else {
      return "No number to count"
    }
  }
  recursion(5) 

The output of the above code will be:

5 4 3 2 1

The countDown(5) will work just as expected. So here you have it, a recursive-function is a function that calls itself until it doesn't.

JavaScript (call , Apply and bind ) function

Functions and Objects are frequently seen in any javaScript code, and its syntax is really easy to understand. If a function is not a method of a JavaScript object, it is a function of the global object. The function prototype has the call(), apply() and bind() methods. Good enough the javaScript this keyword is always taught together with javaScript objects and object methods. But you hardly hear about the call(), the apply() and the bind() method that can also be used in object method manipulation.

All the same, as a beginner in the world of javaScript you will often meet a code snippet that uses one or two of these three methods (call, Apply, Bind). Then you will start wondering what is going on, where was the function with the name "call" or "bind" created. Well with the call(), apply() and bind() methods, you can assign and call a method belonging to one object for a different object. This means that with these three methods you can be able to borrow a method that you created in one object and use it in other Objects.


  const firstObject = {
    fullName: function() {
      return this.firstName + " " + this.lastName;  
    }
  }
  const secondObject = {
    firstName: "John",
    lastName: "Doe"
  }
  // This will return "John Doe":
 firstObject.fullName.call(secondObject)

Just like most of the javaScript functions/methods, these three methods can take in Arguments:


  functionName.call(thisArg, arg1, arg2, ...);
  functionName.apply(thisArg, argsArray);
  functionName.bind(thisArg, arg1, ... , argN); 

Difference between Call() and apply()

Although the apply method and the call method are similar it the way they work, here are the differences between them:

The call() method takes arguments separately.

The apply() method takes arguments as an array.

Exampe: call()


  const firstObject = {
    fullName: function() {
      return this.firstName + " " + this.lastName + "," +  city + "," + country;
    }
  }
  const secondObject = {
    firstName: "John",
    lastName: "Doe"
  }
  firstObject.fullName.call(secondObject, "Shanghai", "China"); 

Exampe: Apply()


  const firstObject = {
    fullName: function() {
      return this.firstName + " " + this.lastName + "," +  city + "," + country;
    }
  }
  const secondObject = {
    firstName: "John",
    lastName: "Doe"
  }
firstObject.fullName.apply(secondObject, ["Shanghai", "China"]); 

The apply() method, on the other hand can also be used to append an array to another array array concatenation and it can also work well with some javaScript built in functions : the Math.max and Math.min.

As we already know, one can easily add items to an array using the push(). Sometimes we have an array of items and we want to push just the items of that array to a different array, but we end up with an array inside an array instead.


  const myFirstArray = ["a", "b", "c"];
  const mySecondArray = ["1", "2", "3"];
  myFirstArray.push(mySecondArray);
  console.log(myFirstArray); 
  // ["a", "b", "c", ["1", "2", "3"]]  

In this case the aplly() method can rescue you!


  myFirstArray.push.apply(myFirstArray, mySecondArray);
  console.log(myFirstArray); 
  // ["a", "b", "c", "1", "2", "3"] 

Getting the highest or the lowest number from a list of numbers can be achieved by the use of Math.max() or Math.min() methods. But Sometimes you will be working with an array and javaScript arrays do not have the Math.max() or Math.min() method. So here applying the method you want to use will return the result you expect.


  // Will return 9
  Math.max.apply(null, [3,6,9]); 

The bind() method is mainly used to preserve the this value of a function/method. Functions tend to lose the value of this when it's being called as a callback, resulting in undefined instead. The bind() method solves this problem :


  const person = {
    firstName: "John",
    lastName: "Doe",
    display: function() {
      let x = document.getElementById("demo");
      x.innerHTML this.firstName + "" + this.lastName;
    }
  }
  let display = person.display.bind(person);
  setTimeout(display, 3000);
  // This will diplay the person name after 3 seconds 

JavaScript Hoisting

Going through code snippets we often see things like this:


  // Function execution
  fullName("John", "Doe");
  // Function declaration
  function fullName(x, y) {
    console.log(x + " " + y);
  }
  // returns "John Doe" 

What happened in the code above was that the function fullName() was used before it was declared, yet the code worked just fine.

Hoisting - in javaScript refers to the default behavior of moving declaration to the top -- W3School. One can hoist functions, variables or classes to the top of their scope, prior to execution of the code. Hoisting allows the use of variables, functions in a code before they are declared. However in javascript one can only hoists declarations, not initializations!.

Variable declaration and initialization example:


  // variable declaration
  var a; // Declare a
  a = 20; // Assign 20 to a
  // variable initialization
  var a = 10; // Initialize a 

Note : Assigning a declared variable after using it will return undefined :


  var a; // Declare a
  console.log(a); // Return undefined
  a = 20; // Assign 20 to a 

The let and const variables can not be used before they are declared.

Declaring a let variable before it is used will result in:

ReferenceError: Cannot access "a" before initialization.

And declaring a const variable before it is used will result in:

Uncaught SyntaxError: Missing initializer in const declaration.

However using a variable before declaration is not a good practice, and is not generally recommended as it can lead to unexpected errors. Always Declare your variables at the top.

JavaScript Closures

Locally declared javaScript variables can not be shared between two functions. Often in javascript code it is easy to create a function inside other functions nested functions, either as a callback function or as a totally different purpose function as in the setTimeout() function.

Closures - in javascript means that an inner function always has access to the locally declared variable of its parent/outer function, even after the parent function has returned or closed. In a closure the inner function can only reference the parent function but does not have a fixed state as the parent function. The value of the locally declared variable in the parent function can be changed using the inner function.

Example: Closure


  function parentFunction() {
    let count = 0;
    function innerFunction() {
      return (count += 1);
    };
    return innerFunction;
  };
  let counter = parentFunction();
  counter(); // 1
  counter(); // 2
  counter(); // 3 

In the above example, the parentFunction() returns the innerFunction() on each call, and the innerFunction() increases the locally declared variable count by one on each call.

JavaScript Object Accessors

JavaScript object properties as we often see can be accessed by the use of dot notation or bracket notation. These are called Object Accessors

Nevertheless, the Getter and Setter functions introduced in ECMAScript 5 can be used to get and set object values. Although many developers prefer the usual dot and bracket notation or other E6 similar syntax, the getter and setter function also allow for defining javascript object accessors.

Reason to use the getters and setters function

  • Easy and simpler syntax
  • Useful for doing things behind-the-scenes
  • Equal syntax for both methods and properties
  • Secures better data quality

Syntax:

{ get prop() { ... } } { set prop() { ... } }

JavaScript Getter - makes use of the get keyword to return values from an object property. The get syntax is used to bind an object property to a function that will be called when that property is looked up.

Exaple: getter


  const person = {
    firstName: "John",
    lastName: "Doe",
    get fullName() {
      return this.firstName + " "  + this.lastName;
    }
  };
  alert(person.fullName); // "John Doe" 

JavaScript Setter - makes use of the set keyword to store values in object properties. The set syntax binds an object property to a function to be called when there is an attempt to set that property. -- Mozilla.

Exaple: setter


  const person = {
    firstName: " ",
    lastName: "Doe",
    set fullName(name) {
      this.firstName = name.toUpperCase();
    }
  };
  //set an object proerty using a setter  
  person.fullName = "John";
  alert(person.firstName); // alert data will return "JOHN" 

The getter and setter can also be used in object.defineProperty() method to define a new property directly on an object, or modify an existing property on an object, and return the object.

Example: object.defineProperty


  // Create an Object
  const person = {
    firstName: "John", lastName: "Doe", country: " "
  };
  // Define a getter
  Object.defineProperty(person, "fullName", {
    get: function() {
      return this.firstName + " " + this.lastName
    }
  });
  // Define a setter
  Object.defineProperty(person, "add", {
    set: function(value) {
      return this.country += value 
      }
  });
  alert(person.fullName); // This alert "John Doe" 
  person.add = "Nigeria";  // Assign property to the country 
  alert(person.country); // This alert "Nigeria"  

By default, values added using Object.defineProperty() are immutable and not enumerable. To modify a property, the object's writable property has to be true, else it won't modify and throw errors in strict mode. To be able to pick the property of the object using Object.assign() or spread operator set the enumerable property attribute to true.

Summary

There are tons of javaScript syntax out there, Some might work differently from the ones you already know, some might help you get the result you are looking for faster and with a non complex code. As a developer it is never a must to know or understand all the javaScript syntax, but it's actually good to know that something you want to do is possible. My advice is to not only watch online videos, but also try as much as you can to read documentations.


Tags: JavaScript Functions

Author-avater
Nebeolisa Samson

I create awesome websites you will love. Working with you from start till end to make sure your goals are met and you are happy with the outcome is my number one priority.