JavaScript Callback function

In JavaScript, we can pass a function to another function as an argument. By definition, a callback is a function that we pass into another function as an argument for executing later.

We are going to focus on Asynchronous callbacks. An asynchronous callback is executed after the execution of the high-order function that uses the callback.

Asynchronicity means that if JavaScript has to wait for an operation to complete, it will execute the rest of the code while waiting.

Here is an example of Asynchronous callback;

Suppose that you need to develop a script that downloads a picture from a remote server and process it after the download completes:

function download(url) {
    // ...
}

function process(picture) {
    // ...
}

download(url);
process(picture);

However, downloading a picture from a remote server takes time depending on the network speed and the size of the picture.

The following download() function uses the setTimeout() function to simulate the network request:

function download(url) {
    setTimeout(() => {
        // script to download the picture here
        console.log(`Downloading ${url} ...`);
    },1000);
}

And this code emulates the process() function:

function process(picture) {
    console.log(`Processing ${picture}`);
}

When we execute the following code:

let url = 'https://www.foot.net/pic.jpg';

download(url);
process(url);

we will get the following output:

Processing https://foo.net/pic.jpg
Downloading https://foo.net/pic.jpg ...

This is not what we expected because the process() function executes before the download() function. The correct sequence should be:

  • Download the picture and wait for the download completes.
  • Process the picture.

To resolve this issue, we can pass the process() function to the download() function and execute the process() function inside the download() function once the download completes, like this:

function download(url, callback) {
    setTimeout(() => {
        // script to download the picture here
        console.log(`Downloading ${url} ...`);
        
        // process the picture once it is completed
        callback(url);
    }, 1000);
}

function process(picture) {
    console.log(`Processing ${picture}`);
}

let url = 'https://wwww.javascripttutorial.net/pic.jpg';
download(url, process);

Output:

Downloading https://www.foo.net/pic.jpg ...
Processing https://www.foo.net/pic.jpg

Now, it works as expected.

In this example, the process() is a callback passed into an asynchronous function.

When we use a callback to continue code execution after an asynchronous operation, the callback is called an asynchronous callback.

To make the code more concise, we can define the process() function as an anonymous function:

function download(url, callback) {
    setTimeout(() => {
        // script to download the picture here
        console.log(`Downloading ${url} ...`);
        // process the picture once it is completed
        callback(url);

    }, 1000);
}

let url = 'https://www.javascripttutorial.net/pic.jpg';
download(url, function(picture) {
    console.log(`Processing ${picture}`);
}); 

Handling errors

The download() function assumes that everything works fine and does not consider any exceptions. The following code introduces two callbacks: success and failure to handle the success and failure cases respectively:

function download(url, success, failure) {
  setTimeout(() => {
    console.log(`Downloading the picture from ${url} ...`);
    !url ? failure(url) : success(url);
  }, 1000);
}

download(
  '',
  (url) => console.log(`Processing the picture ${url}`),
  (url) => console.log(`The '${url}' is not valid`)
);

Nesting callbacks and the Pyramid of Doom

How do we download three pictures and process them sequentially? A typical approach is to call the download() function inside the callback function, like this:

function download(url, callback) {
  setTimeout(() => {
    console.log(`Downloading ${url} ...`);
    callback(url);
  }, 1000);
}

const url1 = 'https://www.foo.net/pic1.jpg';
const url2 = 'https://www.foo.net/pic2.jpg';
const url3 = 'https://www.foo.net/pic3.jpg';

download(url1, function (url) {
  console.log(`Processing ${url}`);
  download(url2, function (url) {
    console.log(`Processing ${url}`);
    download(url3, function (url) {
      console.log(`Processing ${url}`);
    });
  });
});

Output:

Downloading https://www.foo.net/pic1.jpg ...
Processing https://www.foo.net/pic1.jpg
Downloading https://www.foo.net/pic2.jpg ...
Processing https://www.foo.net/pic2.jpg
Downloading https://www.foo.net/pic3.jpg ...
Processing https://www.foo.net/pic3.jpg

The script works perfectly fine.

However, this callback strategy does not scale well when the complexity grows significantly.

Nesting many asynchronous functions inside callbacks is known as the pyramid of doom or the callback hell:

asyncFunction(function(){
    asyncFunction(function(){
        asyncFunction(function(){
            asyncFunction(function(){
                asyncFunction(function(){
                    ....
                });
            });
        });
    });
});

To avoid the pyramid of doom, we use promises or async / await functions.

How single page application works

Single page applications use hash-based or pushState navigation to support back/forward gestures and bookmarking. The best known example probably is Gmail but now there are other too. If you’re not familiar with how that technique works, here is a brief explanation;

For hash-based navigation, the visitor’s position in a virtual navigation space is stored in the URL hash, which is the part of the URL after a ‘hash’ symbol (e.g., /my/app/#category=shoes&page=4). Whenever the URL hash changes, the browser doesn’t issue an HTTP request to fetch a new page; instead it merely adds the new URL to its back/forward history list and exposes the updated URL hash to scripts running in the page. The script notices the new URL hash and dynamically updates the UI to display the corresponding item (e.g., page 4 of the “shoes” category).

This makes it possible to support back/forward button navigation in a single page application (e.g., pressing ‘back’ moves to the previous URL hash), and effectively makes virtual locations bookmarkable and shareable.

pushState is an HTML5 API that offers a different way to change the current URL, and thereby insert new back/forward history entries, without triggering a page load. This differs from hash-based navigation in that you’re not limited to updating the hash fragment — you can update the entire URL.

Debounce and Throttle in JavaScript

Debounce and throttle are two concepts that we can use in JavaScript to increase the control of our function executions, specially useful in event handlers.

Both techniques answer the same question “How often a certain function can be called over time?” in different ways:

  • Debounce: Think of it as “grouping multiple events in one”. Imagine that you go home, enter in the elevator, doors are closing… and suddenly your neighbor appears in the hall and tries to jump on the elevator. Be polite! and open the doors for him: you are debouncing the elevator departure. Consider that the same situation can happen again with a third person, and so on… probably delaying the departure several minutes.
  • Throttle: Think of it as a valve, it regulates the flow of the executions. We can determine the maximum number of times a function can be called in certain time. So in the elevator analogy.. you are polite enough to let people in for 10 secs, but once that delay passes, you must go!

Event handlers without debouncing or throttling are like one-person-capacity elevators: not that efficient.

Use cases for debounce

Use it to discard a number of fast-pace events until the flow slows down. Examples:

  • When typing fast in a textarea that will be processed: you don’t want to start to process the text until user stops typing.
  • When saving data to the server via AJAX: You don’t want to spam your server with dozens of calls per second.

Use cases for throttle

Same use cases than debounce, but you want to warranty that there is at least some execution of the callbacks at certain interval

  • If that user types really fast for 30 secs, maybe you want to process the input every 5 secs.
  • It makes a huge performance difference to throttle handling scroll events. A simple mouse-wheel movement can trigger dozens of events in a second. Even Twitter had once problems with scroll events, so learn from others mistake and avoid this easy pitfall.

Here is visual guide to these concepts.

Resource

https://redd.one/blog/thinking-in-functions-higher-order-functions

Hidden / Invisible Characters

Windows 98 had some tricks using ALT+some integer to add invisible characters. These are normally called  Control Characters.

The control characters U+0000–U+001F and U+007F come from ASCII. Additionally, U+0080–U+009F were used in conjunction with ISO 8859 character sets (among others). They are specified in ISO 6429 and often referred to as C0 and C1 control codes respectively. Most of these characters play no explicit role in Unicode text handling. The characters U+0000 , U+0009 (HT), U+000A (LF), U+000D (CR), and U+0085 (CR+LF) are commonly used in text processing as formatting characters.

This is how we can identify and remove them in a string;

string input; // this is your input string
string output = new string(input.Where(c => !char.IsControl(c)).ToArray());
Console.write(output.Trim());

For testing,

Excel can be used.

Click on the Cell where you want to add character. Click Insert -> Symbols;

Select “Basic Latin” in Subset and add empty space;

This will add a special character in selected cell before or after the value depending on the position.

Notepad++ is another alternative and can be used to add special characters in a string.

  1. Go to Edit > Character Panel to show the ASCII Insertion Panel.
  2. Put the cursor where you want to insert the character.
  3. Double-click the character (in the Character column) to insert.

For more info on NotePad++ special character handling, click here.

JavaScript: How to construct an array of json objects using map

What does map do ?

Answer: It creates a new array with the results of calling a function on every element in the calling array.

Example:

var numbers = [ 1, 2, 3, 4];
var multiplesOfTen = numbers.map( function(num) {
    return num * 10;
});
console.log(numbers); //prints [1, 2, 3, 4]
console.log(multiplesOfTen); //prints [10, 20, 30, 40]

How does JSON object look like?

Answer: JSON objects are written as key/ value pairs

Example:

var Person = { "name" : "Amy", "Age" : 15 }
console.log(Person.Age); //Prints 15

Let us solve a problem using map method. We have a JSON object say “orders” with lot of keys like name, description, date, status. We need an array of orders whose status is delivered. This array of orders will have information about order name and order description only.

Answer:

var orders = [ { "name" : "chain", "description" : "necklace chain", "status": "shipped"} , {"name": "pen", "description" : "ball pen", "status": "shipped"}, {"name": "book", "description" : "travel diary", "status": "delivered"},{"name": "brush", "description" : "paint brush", "status": "delivered"}];
console.log(orders); 
var orderInfo = orders.map( function(order) {
 if( order.status === "delivered"){
     var info = { "orderName": order.name,
                  "orderDesc": order.description
                 }
     return info;
 }
});
console.log(orderInfo);

Reference

https://www.w3schools.com/js/js_json_objects.asp