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.
- One input for position
- One input for value
- One button to update and display list
- 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:
- First parameter = position
- Second parameter = delete count (0 means no delete)
- 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:
- Input values are taken
- Array is updated using
splice() - UI is cleared
- Array is looped
- 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>";
}
}