Javascript Advanced Crash Course 2022

Hello there folks! in this tutorial, I will cover the most sort of the Javascript advanced topics you need to know in 2022 and these are…

The Dom

Javascript Array Methods

Async JS - Promises, Async/Await
  1. DOM – Document object model

We can access all objects inside an HTML document using Javascript.

This means when a web page is loaded we can modify the page since the browser creates a Document Object Model(DOM) of the page.

Let’s look at an example of the DOM:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Javascript</title>
</head>
<body>
 <h1 style="text-align:center">Javascript DOM</h1>
  <p id="myapp"></p>
</body>
</html>

Now, this is a simple document representing the DOM and we can manipulate it however we want to. For an instance take an example of the following code that manipulates the document.

Ex:1

document.getElementById("myapp").innerHTML = "Welcome to My App!";

// Welcome to My App!

We use the getElementById to find the element in our case “id = myapp” and innerHTML to find the content

For example the HTML and body.

Ex:2

document.getElementById("myapp").style.color = "red";

// Welcome to My App! changed to red

The only difference here is that we are using CSS to style the HTML element.

Ex:3

document.body.style.background = 'blue'; 

// make the background blue

The document.body is an object that represents the tag and we have used style.background to change the background colour of the document.

Let’s look at more examples to get the hang of this…

a) Create a TextNode

A text node is one of the ways to create DOM nodes in Javascript.

The Syntax:

document.createTextNode(text)

In this example, we will create a text node with three different texts.

Ex:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Javascript</title>
</head>
<body>
 <h1 style="text-align:center">Javascript DOM</h1>
  <p id="myapp"></p>
  <div id="demo1"></div>
  <div id="demo2"></div>
  <div id="demo3"></div>
</body>
</html>
<script>
  let text1 = 'I like Javascript!';
  let text2 = 'Javascript is amazing!';
  let text3 = 'Every Programmer must learn Javascript!';

  demo1.append(document.createTextNode(text1));
  demo2.innerHTML = text2;
  demo3.textContent = text3;
</script>

output:

Welcome to My App!

I like Javascript!
Javascript is amazing!
Every Programmer must learn Javascript!

b) Create a To-Do List

<h1>To Do list</h1>
  <script>
    let ul = document.createElement('ul');
    document.body.append(ul);

    while (true) {
      let data = prompt("Enter the to do list", "");

      if (!data) {
        break;
      }

      let li = document.createElement('li');
      li.textContent = data;
      ul.append(li);
    }
  </script>

output:

To-Do list

  • play piano
  • program
  • watch a movie
  • go to church

In this example, we are creating a to-do list from the user input. So am creating a list item (li) and adding it to the unordered list (ul)

c) Create a tree from an Object

We are using the function createTree to create a nested ul/li list from a nested object.

Ex:

<div id="container"></div>

<script>
let data = {
    "Fruits": {
        "orange": {},
        "banana": {}
    },

    "Computers": {
        "Mainframes": {
            "zSeries": {},
            "UNIVAC series.": {}
        },
        "Minicomputers": {
            "Smartphones.": {},
            "Tablet PCs": {}
        }
    }
};

function createTree(container, obj) {
    container.append(createTreeDom(obj));
}

function createTreeDom(obj) {
    if (!Object.keys(obj).length) return;

    let ul = document.createElement('ul');

    for (let key in obj) {
        let li = document.createElement('li');
        li.innerHTML = key;

        let childrenUl = createTreeDom(obj[key]);
        if (childrenUl) {
            li.append(childrenUl);
        }

        ul.append(li);
    }

    return ul;
}


let container = document.getElementById('container');
createTree(container, data);
</script>

Output:

  • Fruits
    • orange
    • banana
  • Computers
    • Mainframes
      • zSeries
      • UNIVAC series.
    • Minicomputers
      • Smartphones.
      • Tablet PCs

d) Clear Elements

In this example, we will write a function that clears everything from the element.

Ex:

<ol id="elem">
    <li>Oranges</li>
    <li>Bananas</li>
    <li>Pineaples</li>
  </ol>
<script>
 function clear(elem) {
   for (let i=0; i < elem.childNodes.length; i++) {
     elem.childNodes[i].remove();
        i-=1;
      }
}
clear(elem); // clears the list
</script>

e) Clone Nodes

We can clone nodes in the DOM.

Ex:

<div id="elem">I like</div>
<script>
elem.append(document.createTextNode('Javascript'));
let div2 = elem.cloneNode(true);
elem.after(div2);
</script>

output:
I likeJavascript
I likeJavascript

f) Insert HTML in the list

We can insert HTML in a list using the following method

insertAdjacentHTML

Ex:


 <ul id="ul">
    <li id="one">Oranges</li>
    <li id="two">Bananas</li>
  </ul>
  • Oranges
  • Bananas

<script>
one.insertAdjacentHTML('afterend', '<li>Pineapples</li><li>Avocado</li>');
</script>
  • Oranges
  • Pineapples
  • Bananas

2. Async JS – Promises, Async/Await

a) Promises

A Promise represents a real-life analogy of things we often use in the programming environment. It has a Producing code that

does something and it takes time. A consuming code that wants the result of the producing code once it’s ready.

So a promise is a Javascript object that links the producing code and the consuming code together. Think of the

subscribers in the YouTube environment.

The producing code takes whatever time it needs to produce the promised result, and the promise makes that result

available to all of the subscribed codes when it’s ready.

The syntax:

let promise = new Promise(function(resolve, reject) {
  // the producing code, (may take some time)
});

When the producing code obtains the result, it should call one of these callbacks:

resolve(value) — if the job is finished successfully

reject(error) — if an error has occurred

Ex: State -> resolve


 let promise = new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(['oranges', 'bananas', 'pineaples']);
        }, 1000);
    });
 
promise.then(values => {
   alert(values[0]);
})

output:oranges

From the above example, the state is fulfilled and the result(value) is returned from the array which is oranges.

What happens is that if the state is pending the result becomes undefined and if the state is fulfilled the result

returns a value. When the state is rejected the result is an error.

Ex: State -> resolve or reject

function CheckAge(mydemo) {
  document.getElementById("demo").innerHTML = mydemo;
}

let promise = new Promise(function(resolve, reject) {
let age = 25;

  if (age == 20) {
    setTimeout(() => resolve("This is your age!"), 1000);
  } else {
    setTimeout(() => reject (new Error("This is not your age!")), 1000);
  }
});

promise.then(
  function(value) {CheckAge(value);},
  function(error) {CheckAge(error);}
);

output: Error: This is not your age!

This example returns success or failure depending on the number you place on the variable age. The set timeout is there to return the result after 1 second.

The first argument of .then is a function that runs when the promise is resolved and receives the result.

The second argument of .then is a function that runs when the promise is rejected and receives the error.

b) Async/Await

The Async keyword is placed before a function. What is does it makes a function to return a promise.

The syntax:

async function myfunction() {
  return 1;
}

The Await keyword works inside Async functions. What it does it makes a function wait for a promise.

The syntax:

let value = await promise;

Ex:

class HttpError extends Error { // making an http request
  constructor(response) { 
    super(`${response.status} for ${response.url}`);
    this.name = 'HttpError';
    this.response = response;
  }
}

async function loadJson(url) {
  let response = await fetch(url);
  if (response.status == 200) {
    return response.json();
  } else {
    throw new HttpError(response);
  }
}

// Ask for a user name until github returns a valid user
async function GithubUser() {

  let user;
  while(true) {
    let name = prompt("Enter a name?", "BrianMwengi");

    try {
      user = await loadJson(`https://api.github.com/users/${name}`);
      break; // no error, exit loop
    } catch(err) {
      if (err instanceof HttpError && err.response.status == 404) {
        // loop continues after the alert
        alert("No such user, please reenter.");
      } else {
        // unknown error, rethrow
        throw err;
      }
    }
  }


  alert(`Full name: ${user.name}.`);
  return user;
}

GithubUser();



Sign up for free tutorials in your inbox.

We don’t spam! Read our privacy policy for more info.

Leave a Comment

Your email address will not be published. Required fields are marked *