Home Courses Event Loop - Call Stack, Microtask Queue & Callback Queue

Event Loop - Call Stack, Microtask Queue & Callback Queue

We start by creating an array that stores user names.


let users = ["anil", "sam", "sidhu", "peter"];

This array holds multiple values in a single variable.


HTML Structure

We create input fields and a button to interact with the array.

  1. One input for position
  2. One input for value
  3. One button to update and display list
  4. One <ul> to show data

<input type="text" id="position" placeholder="enter position">
<input type="text" id="value" placeholder="enter value">
<button onclick="displayElement()">Display Items</button>

<ul id="list"></ul>


Function to Update Array and UI

We create a function that runs when the button is clicked.


function displayElement() {


Getting Input Values

We take values from input fields.


let val = document.getElementById('value').value;
let pos = document.getElementById('position').value;


Adding Element into Array

If both position and value exist, we insert data into the array.


if (pos && val) {
users.splice(pos, 0, val);
}

Meaning of splice:

  1. First parameter = position
  2. Second parameter = delete count (0 means no delete)
  3. Third parameter = value to insert


Updating UI (List Rendering)

We first clear old list:


let list = document.getElementById('list');
list.innerHTML = "";

Then we loop through the array:


for (let user of users) {
list.innerHTML += "<li>" + user + "</li>";
}

Each item is added as <li> inside <ul>.


Full Working Logic Flow

When button is clicked:

  1. Input values are taken
  2. Array is updated using splice()
  3. UI is cleared
  4. Array is looped
  5. New list is displayed on screen


Final Code Summary


let users = ["anil", "sam", "sidhu", "peter"];

function displayElement() {
let val = document.getElementById('value').value;
let pos = document.getElementById('position').value;

if (pos && val) {
users.splice(pos, 0, val);
}

let list = document.getElementById('list');
list.innerHTML = "";

for (let user of users) {
list.innerHTML += "<li>" + user + "</li>";
}
}


Share this lesson: