Menu Search Sign up

JavaScript

JavaScript is the scripting language that can make your static HTML pages dynamic and interactive.

Audience

This tutorial has been prepared for the beginning to intermediate JavaScript developers to help them summarize and advance their knowledge of JavaScript. This tutorial will bring you from a beginner level to a more advanced intermediate level of expertise.

Prerequisites

You need to have good understanding of HTML before you can read and understand this tutorial. It would also help if you have some prior programming experience and even better, have already had copied, pasted, and modified some JavaScript snippets to enhance the interactivity of your HTML pages.

References

JavaScript and HTML DOM

https://www.w3schools.com/jsref/default.asp

ECMAScript tutorials

https://developer.mozilla.org/en-US/docs/Web/JavaScript

ECMAScript reference

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference

ECMAScript new features

https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/1.6

Check the above link once in a while to see what new features are added, and what features are deprecated.

Important Features

Map function

https://www.w3schools.com/jsref/jsref_map.asp

Arrow function

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions 

Promise

 
Here are 2 examples for you to play with the promise concept:
 
<!DOCTYPE html>
<html>
<head>
</head>
<body>

<script>
var promise = new Promise(function(resolve, reject) {
   //generate a random number between 1 and 10
   var x = Math.floor((Math.random() * 10) + 1);
   //call this function to display hello message after 3 seconds
   setTimeout(function(){
      console.log("Hello from myAsynchFunction!");
      if (x>5) {
         resolve("Stuff worked! "+x);
      }
      else {
         reject(Error("It broke "+x));
      }
   }, 3000);
   //then
});
 
console.log("before promise then");
promise.then(function(result) {
   console.log(result); // "Stuff worked!"
}, function(err) {
   console.log(err); // Error: "It broke"
});
 
console.log("after promise then");
 
</script>

<script>
function get(url) {
   // Return a new promise.
   return new Promise(function(resolve, reject) {
     
      // Do the usual XHR stuff
      var req = new XMLHttpRequest();
      console.log("before XMLHttpRequest GET");
      req.open('GET', url);
      console.log("after XMLHttpRequest GET");

      req.onload = function() {
         // This is called even on 404 etc
         // so check the status
         if (req.status == 200) {
            // Resolve the promise with the response text
            resolve(req.response);
         }
         else {
            // Otherwise reject with the status text
            // which will hopefully be a meaningful error
            reject(Error(req.statusText));
         }
      };

      // Handle network errors
      req.onerror = function() {
         reject(Error("Network Error"));
      };

      // Make the request
      req.send();
   }); //end of return new Promise
} //end of function get

get('package-lock.json').then(function(response) {
   console.log("Success!", response);
}, function(error) {
   console.error("Failed!", error);
})
</script>
</body>
</html> 

Async and Wait

https://javascript.info/async-await 

The word “async” before a function means one simple thing: a function always returns a promise. If the code has return <non-promise> in it, then JavaScript automatically wraps it into a resolved promise with that value:

async function f() {
   return 1;
}
f().then(alert); // 1 will be displayed in the popped-up alert message

We could explicitly return a promise, that would be the same:

async function g() {
   return Promise.resolve(2);
}
g().then(alert); // 2 will be displayed in the popped-up alert message

So, async ensures that the function returns a promise, and wraps non-promises in it.

The keyword await makes JavaScript wait until that promise settles and returns its result.

The keyword await can only be used within an asynch function.

Here is an example:

async function h() {
   let promise = new Promise((resolve, reject) => {
      setTimeout(() => resolve("h is done!"), 9000) //9 seconds delay
   });
   let result = await promise; // pauses javascript execution and waits till the promise resolves (*)
   alert(result); // "done!"
}
h();

In above example, the function execution “pauses” at the line (*) and resumes when the promise settles, and then shows “done!” in 9 seconds.

The keyword await literally makes JavaScript wait until the promise settles, and then go on with the result. That doesn’t cost any CPU resources, because the engine can do other jobs meanwhile: execute other scripts, handle events etc.

Now there is something tricky: if the async function is called from within a non-async function, the non-async function will call the async function to start execution of its code, and then will immediately move on to the line of code after that call. Below is an example. In the example, the alert message "i is done" will be displayed immediately, then after 9 seconds, the alert message "h is done" will be displayed.

async function h() {
   let promise = new Promise((resolve, reject) => {
      setTimeout(() => resolve("h is done!"), 9000) //9 seconds delay
   });
   let result = await promise; // pauses javascript execution and waits till the promise resolves (*)
   alert(result); // "done!"
}
function i() {
   h();
   alert("i is done");
}
i();

If that kind of behavior is not waht you want, you can fix it by adding aysnc and await to the calling function, as below, which will display "h is done" before "j is done".

async function j() {
   await h();
   alert("j is done");
}
j();

With that said, can you guess what will be the behavior in the following code? Well, the behavior will be: "i is done", then "j is done", then after 9 seconds, "h is done".

async function h() {
   let promise = new Promise((resolve, reject) => {
      setTimeout(() => resolve("h is done!"), 2000) //9 seconds delay
   });
   let result = await promise; // pauses javascript execution and waits till the promise resolves (*)
   alert(result); // "done!"
}
//h();

function i() {
   h();
   alert("i is done");
}
//i();

async function j() {
   await i();
   alert("j is done");
}
j();


Another solution to fix the problem (of waiting in non-async function for the async function to complete its execution before moving on) is by using the Promis.then syntax, as below example, which will wait for 9 seconds, then display "h is done", then display "k is done after h is ok":

function k() {
   h().then(function() {
   alert("k is done after h is ok");
}, function(error) {
   alert("k is done after h failed");
})
}
k();

Important Techniques

Removing multiple elements from an array

    var fruits = ["Banana", "Orange", "Apple", "Mango"];

    var i=0;
    var toBeRemovedIndexList = [];
    for (i=0; i<fruits.length; i++) {
        if (fruits[i]=="Orange")
            toBeRemovedIndexList.push(i);
        else if (fruits[i]=="Banana")
            toBeRemovedIndexList.push(i);
    }
    for (i=toBeRemovedIndexList.length-1; i>=0; i--) {
        fruits.splice(toBeRemovedIndexList[i],1);
    }