DEV Community

Niladri Banerjee
Niladri Banerjee

Posted on

Day 4: Learning JavaScript by Step By Step

Intro to JS
In JavaScript, var, let, and const are keywords used to declare variables.

var:
Scope: var declarations are function-scoped or globally-scoped. This means a variable declared with var is accessible throughout the entire function it's declared in, or globally if declared outside any function.
Hoisting: var declarations are hoisted, meaning their declarations are moved to the top of their containing scope during compilation. However, their assignments are not hoisted. This can lead to unexpected behavior if you try to use a var variable before its assignment.
Reassignment and Redeclaration: var variables can be reassigned and redeclared within the same scope without error.

let:
Scope: let declarations are block-scoped. This means a variable declared with let is only accessible within the block (e.g., if statement, for loop, or any {} block) where it's defined.
Hoisting: let declarations are also hoisted, but they are in a "temporal dead zone" until their declaration line is executed. This prevents using a let variable before its declaration, leading to a Reference Error.
Reassignment and Redeclaration: let variables can be reassigned but cannot be redeclared within the same scope.

const:
Scope: const declarations are also block-scoped, similar to let.
Hoisting: Like let, const declarations are hoisted but are in a temporal dead zone until declared.
Reassignment and Redeclaration: const variables cannot be reassigned or redeclared after their initial assignment. This makes them suitable for values that should remain constant throughout the program. However, if a const variable holds an object or array, the properties or elements of that object/array can be modified, but the const variable itself cannot be reassigned to a different object or array.

Datatypes in JS

let a = 123; // number
let b = "Hello World"; // string
let c = true; // boolean
let d = null; // null
let e; // undefined
let f = { name: "Niladri", age: "26"}; // object
let g = [1,2,3,4,5]; // array

console.log("Value of a:", a, "Type of a:", typeof a);
console.log("Value of b:", b, "Type of b:", typeof b);
console.log("Value of c:", c, "Type of c:", typeof c);
console.log("Value of d:", d, "Type of d:", typeof d);
console.log("Value of e:", e, "Type of e:", typeof e);
console.log("Value of f:", f, "Type of f:", typeof f);
console.log("Value of g:", g, "Type of g:", typeof g);


let v1 = 12;
console.log("Values of v1:",v1);
console.log("Values of v1:",(v1+1));
v2 = "12";
console.log("Values of v2: ",v2);
console.log("See what happens:",(v2+1)) // concatenation occurs because v2 is a string 
console.log("Mathematical result:", (Number(v2) + 1)); // Output: 13 explisit conversion from string to number.
console.log("Mathematical result:", (parseInt(v2) + 1)); // Output: 13 explisit conversion from string to number.
console.log("Mathematical result:", (v1.toString() + 1)); // Output: "121" explicit conversion from number to string.


let a1 = "100"; // string
console.log("Type of a1:", typeof a1);
console.log("Value of the variable: ", a1);
console.log("Value of the variable: ", Number(a1)); // explicit conversion from string to number
console.log("Type after conversion:", typeof Number(a1));


let a2= "Niladri"; // string
console.log("Type of a1:", typeof a2)
console.log("Value of the variable: ", a2)
console.log("Value of the variable: ", Number(a2));// explicit conversion from string to number //NAN
// NaN stands for Not a Number because a2 is assigned by the string "Niladri" which cannot be converted to a number.
console.log("Type after conversion:", typeof Number(a2));
Enter fullscreen mode Exit fullscreen mode

Output

Value of a: 123 Type of a: number
Value of b: Hello World Type of b: string
Value of c: true Type of c: boolean
Value of d: null Type of d: object
Value of e: undefined Type of e: undefined
Value of f: { name: 'Niladri', age: '26' } Type of f: object
Value of g: [ 1, 2, 3, 4, 5 ] Type of g: object
Values of v1: 12
Values of v1: 13
Values of v2:  12
See what happens: 121
Mathematical result: 13
Mathematical result: 13
Mathematical result: 121
Type of a1: string
Value of the variable:  100
Value of the variable:  100
Type after conversion: number
Type of a1: string
Value of the variable:  Niladri
Value of the variable:  NaN
Type after conversion: number

=== Code Execution Successful ===
Enter fullscreen mode Exit fullscreen mode

Operation in JS

const a = 10;
const b = 5;

// Addition
const sum = a + b;
console.log("Addition:", sum); //15
//increment
let C = 10;
console.log("Value of C ", C);//10
console.log("Value of C++", C++); //10 // Post increment
console.log("Value of C after C++", C)// 11
console.log("Value of ++C", ++C); // 12 // Pre increment
console.log("Value of C after ++C", C); //12
//decrement
let d = 10;
console.log("Value of d ", d);//10
console.log("Value of d--", d--); //10 // Post decrement
console.log("Value of d after d--", d)// 9
console.log("Value of --d", --d); // 8 // pre increment
console.log("Value of d after --d", d); //8
//Exponantial
C = 2; d = 3;
const result = C ** d; // 2 ^ 3 = 8
console.log("Exponantial", result);
//shortcut operator
C = C + d; 
console.log("C+b = ", C); // 5
C += d;
console.log("shortcut", C); // 8

// logical operators

const g = true;
const f = true;
const result1 = g && f;
console.log("result1 :: g && f", result1); // true when both are true
const result2 = g || f;
console.log("result2 :: g || f", result2); // false when both are false
console.log(!g); // Not operator


// = Assignment
//== Equals to
// !== Not equals to
// === Strict equals
// !=== Not strict equals

let j = 5, k = "5"; // values are sae but not the datatypes

console.log("Equals ", j == k); // true because both values are same and this neglates the datatype.
console.log ("Strict Equals ",  j === k); // False because both are different datatypes.
console.log("Not Equals ", j != k); // not equals to
Enter fullscreen mode Exit fullscreen mode

Output

Addition: 15
Value of C  10
Value of C++ 10
Value of C after C++ 11
Value of ++C 12
Value of C after ++C 12
Value of d  10
Value of d-- 10
Value of d after d-- 9
Value of --d 8
Value of d after --d 8
Exponantial 8
C+b =  5
shortcut 8
result1 :: g && f true
result2 :: g || f true
false
Equals  true
Strict Equals  false
Not Equals  false

=== Code Execution Successful ===
Enter fullscreen mode Exit fullscreen mode

If-Else in JS

let candidateage = 75;

if (candidateage >= 18) {
    if (candidateage > 80) {
        console.log("This candidate is very experienced and too old to vote comfortably");
    } 
    else if (candidateage >= 60) {
        console.log("This candidate is a senior citizen");
    } 
    else {
        console.log("This is a young citizen to vote");
    }

    console.log("This candidate can vote :>");
} 
else {
    console.log("This candidate cannot vote.");
}


candidateage = 75; //nested ternary operator

console.log(
    candidateage >= 18
        ? candidateage > 80
            ? "This candidate is very experienced and too old to vote comfortably"
            : candidateage >= 60
                ? "This candidate is a senior citizen"
                : "This is a young citizen to vote"
        : "This candidate cannot vote."
);
Enter fullscreen mode Exit fullscreen mode

Output

This candidate is a senior citizen
This candidate can vote :>
This candidate is a senior citizen

=== Code Execution Successful ===
Enter fullscreen mode Exit fullscreen mode

Switch Case

let candidateage = 75;

switch (true) {
    case (candidateage < 18):
        console.log("This candidate cannot vote.");
        break;

    case (candidateage >= 18 && candidateage < 60):
        console.log("This is a young citizen to vote");
        break;

    case (candidateage >= 60 && candidateage <= 80):
        console.log("This candidate is a senior citizen");
        break;

    case (candidateage > 80):
        console.log("This candidate is very experienced and too old to vote comfortably");
        break;

    default:
        console.log("Invalid age input.");
}
Enter fullscreen mode Exit fullscreen mode

Output

``
This candidate is a senior citizen

=== Code Execution Successful ===
``

Loops in jS

for (let i = 1; i <= 5; i++) {
    console.log("For Loop Count:", i);
}

i = 1;
while (i <= 5) {
    console.log("While Loop Count:", i);
    i++;
}

let j = 1;
do {
    console.log("Do While Loop Count:", j);
    j++;
} while (j <= 5);


for (let k = 1; k <= 5; k++) {
    if (k === 3) {
        continue; // Skip 3
    }
    console.log("Continue Example:", k);
}


for (let m = 1; m <= 5; m++) {
    if (m === 3) {
        break; // Stop loop when m = 3
    }
    console.log("Break Example:", m);
}
Enter fullscreen mode Exit fullscreen mode

Output

For Loop Count: 1
For Loop Count: 2
For Loop Count: 3
For Loop Count: 4
For Loop Count: 5
While Loop Count: 1
While Loop Count: 2
While Loop Count: 3
While Loop Count: 4
While Loop Count: 5
Do While Loop Count: 1
Do While Loop Count: 2
Do While Loop Count: 3
Do While Loop Count: 4
Do While Loop Count: 5
Continue Example: 1
Continue Example: 2
Continue Example: 4
Continue Example: 5
Break Example: 1
Break Example: 2

=== Code Execution Successful ===
Enter fullscreen mode Exit fullscreen mode

*Array *

let StudentArray = ["abc", "xyz", "hjk", 123, true, function dummyfunc() {console.log ("Dummy function");}, {name: "Niladri", age: 26}]; 

console.log(StudentArray[4]);
for(let i=0; i < StudentArray.length; i++)
{
    console.log("StudentArray[",i,"] element is -> ", StudentArray[i]);
}
Enter fullscreen mode Exit fullscreen mode

output

true
StudentArray[ 0 ] element is ->  abc
StudentArray[ 1 ] element is ->  xyz
StudentArray[ 2 ] element is ->  hjk
StudentArray[ 3 ] element is ->  123
StudentArray[ 4 ] element is ->  true
StudentArray[ 5 ] element is ->  [Function: dummyfunc]
StudentArray[ 6 ] element is ->  { name: 'Niladri', age: 26 }

=== Code Execution Successful ===
Enter fullscreen mode Exit fullscreen mode
let array1= [1,2,3,4,5,6];
console.log (array1);

let array2 = array1; // only the reference will be shared.
console.log(array2);

array2[2] = 10; // change the array1 too for the reference
console.log(array2);
console.log(array1);
Enter fullscreen mode Exit fullscreen mode

output

[ 1, 2, 3, 4, 5, 6 ]
[ 1, 2, 3, 4, 5, 6 ]
[ 1, 2, 10, 4, 5, 6 ]
[ 1, 2, 10, 4, 5, 6 ]

=== Code Execution Successful ===
Enter fullscreen mode Exit fullscreen mode

console.log(array2.indexOf(10)); // indexOf(element of array) gives the exact index number.

let StudentArray = [
    "abc",
    "xyz",
    "hjk",
    123,
    true,
    function dummyfunc() {
        console.log("Dummy function");
    },
    { name: "Niladri", age: 26 }
];

console.log(StudentArray[4]);  // prints: true

for (let i = 0; i < StudentArray.length; i++) 
{
    console.log("StudentArray[", i, "] element is ->", StudentArray[i] , StudentArray.indexOf(StudentArray[i]));
}
Enter fullscreen mode Exit fullscreen mode

Output

true
StudentArray[ 0 ] element is -> abc 0
StudentArray[ 1 ] element is -> xyz 1
StudentArray[ 2 ] element is -> hjk 2
StudentArray[ 3 ] element is -> 123 3
StudentArray[ 4 ] element is -> true 4
StudentArray[ 5 ] element is -> [Function: dummyfunc] 5
StudentArray[ 6 ] element is -> { name: 'Niladri', age: 26 } 6
Enter fullscreen mode Exit fullscreen mode

Check if the element is in the array or not.
_includes() _-> This function will help to understand that the element is in the array or not.
This will return Boolean values ( True for element present, False for the element not present )

console.log(StudentArray.includes("abc"));
Enter fullscreen mode Exit fullscreen mode

Output

true

Push new element in array

StudentArray.push("Laptop"); // add data to the end of the array
console.log(StudentArray);
Enter fullscreen mode Exit fullscreen mode

Output

[
  'abc',
  'xyz',
  'hjk',
  123,
  true,
  [Function: dummyfunc],
  { name: 'Niladri', age: 26 },
  'Laptop'
]
Enter fullscreen mode Exit fullscreen mode

Now If we want to add a new element at the start of the array then we need unshift()

StudentArray.unshift("Desktop");
console.log(StudentArray);
Enter fullscreen mode Exit fullscreen mode

Output

[
  'Desktop',
  'abc',
  'xyz',
  'hjk',
  123,
  true,
  [Function: dummyfunc],
  { name: 'Niladri', age: 26 }
]
Enter fullscreen mode Exit fullscreen mode

Delete the end object of the array we have pop() function which will delete the last element.

let array = [1,2,3,4,5,6,7,8,9,10];
array.pop(); // Correctly calls pop() on 'array'
console.log(array);
Enter fullscreen mode Exit fullscreen mode

Output

[
  1, 2, 3, 4, 5, 6, 7, 8, 9
]
Enter fullscreen mode Exit fullscreen mode

Delete the first object of the array we have shift() function which will delete the first element.

let array = [1,2,3,4,5,6,7,8,9,10];
array.shift(); // Correctly calls shift() on 'array'
console.log(array);
Enter fullscreen mode Exit fullscreen mode

Output

[
  2, 3, 4,  5, 6, 7, 8, 9, 10
]
Enter fullscreen mode Exit fullscreen mode

Sort the array using sort() function,

let array = [7,8,12,45,12,334,2,678];
array.sort((a, b) => a - b); // Uses a comparison function for numerical sort
console.log(array);
Enter fullscreen mode Exit fullscreen mode

Output

[2, 7, 8, 12, 12, 45, 334, 678]
Enter fullscreen mode Exit fullscreen mode

Function

 //Function Def

function Addition (r , k) // Named function
{
    const result = r + k;
    console.log("Print result::", result);
}

//Function Call
Addition(10,12);
Enter fullscreen mode Exit fullscreen mode

// Anonymous function and the / Function expression

//Anonymous Function Def

let Addition = function  (r , k) // No proper def
{
    const result = r + k;
    console.log("Print result::", result);
    return result;
}

//Anonymous Function Call
console.log(Addition(10,12));
Enter fullscreen mode Exit fullscreen mode

Nested Function

function AddSquare (x,y)
{
    x = Square (x);
    y = Square(y);
    function Square (num)
    {
        return num * num;
    }
    return (x+y);
}

console.log(AddSquare(2,2));
Enter fullscreen mode Exit fullscreen mode

Advanced Function in Js

//Named function
function greet ()
{
    console.log("Hey everyone !!");
}
greet();

// Anonymous function
let c2 = function ()
{
    console.log ("Hello everyone!!");
}
c2();

// Arrow Function 

const c3 = ()=> 
{
    console.log("Hello Hello guys !!");
}
c3();

// Arrow function parameter

const c4 = (count) => 
{
    console.log("Hey there !!",count);
}
c4(2);


// Can write arrow function easily 

const c5 = (count) => count + 1; // automatically return
console.log(c5(5));
console.log(c5(9));
Enter fullscreen mode Exit fullscreen mode

Output
Hey everyone !!
Hello everyone!!
Hello Hello guys !!
Hey there !! 2
6
10

Function return as object

// Function that calculates sum and difference
const calculate = (a, b) => {
    const sum = a + b;
    const difference = a - b;

    // Returns a single object containing both results
    return { 
        total: sum, 
        remainder: difference 
    };
};

// Use object destructuring to unpack the results
const { total, remainder } = calculate(10, 4);

console.log(`Sum is: ${total}`); // Output: Sum is: 14
console.log(`Difference is: ${remainder}`); // Output: Difference is: 6
Enter fullscreen mode Exit fullscreen mode

Output

Sum is: 14
Difference is: 6

=== Code Execution Successful ===
Enter fullscreen mode Exit fullscreen mode
Call Back function
Enter fullscreen mode Exit fullscreen mode

Using arrow method

let calculation = (a, b, operation) => 
{
    return operation (a,b);
}

console.log (calculation (2,3,(n1,n2) =>
{
    return n1 + n2;
}));
Enter fullscreen mode Exit fullscreen mode

Using Anonymous method

let calculation = (a, b, operation) => 
{
    return operation (a,b);
}

console.log (calculation (2,3, function (n1,n2)
{
    return n1 + n2;
}));
Enter fullscreen mode Exit fullscreen mode

Output
Result will be 5 for both.

/**
 * Higher-Order Function: 'calculate'
 * This function accepts two numbers (a, b) and a function (operation), 
 * and executes the 'operation' function using the numbers.
 */
const calculate = (a, b, operation) => {
    return operation(a, b);
}

// --- Method 1: Anonymous Function Callback (Addition) ---
// The function is defined directly inside the 'calculate' call.
const summation = calculate(2, 3, function(n1, n2) {
    return n1 + n2
});

console.log(`Sum (Anonymous Function): ${summation}`); // Output: 5


// --- Method 2: Named Function Callback (Subtraction) ---
// The function is defined separately with a name and then passed by reference.
function sub(a, b) {
    return a - b
}
const subtraction = calculate(2, 3, sub);

console.log(`Difference (Named Function): ${subtraction}`); // Output: -1


// --- Method 3: Arrow Function Callback (Multiplication) ---
// The function is defined using concise arrow function syntax.
const mul = (a, b) => a * b;
const multiplication = calculate(2, 3, mul);

console.log(`Product (Arrow Function): ${multiplication}`); // Output: 6


// --- Alternative: Inline Calculation (Same as Method 1) ---
// The result can also be logged directly without using an intermediate variable.
console.log(`Inline Division: ${calculate(10, 5, (x, y) => x / y)}`); // Output: 2
Enter fullscreen mode Exit fullscreen mode

Array iteration

let arr = [2,3,4,5,6,-7,-8,-9];

arr.forEach((num,index) =>
{
    console.log("Element: ", num , "Index : ", index);
});
Enter fullscreen mode Exit fullscreen mode

Output

Element:  2 Index :  0
Element:  3 Index :  1
Element:  4 Index :  2
Element:  5 Index :  3
Element:  6 Index :  4
Element:  -7 Index :  5
Element:  -8 Index :  6
Element:  -9 Index :  7

=== Code Execution Successful ===
Enter fullscreen mode Exit fullscreen mode

Call Back Hell

/**
 * Asynchronous Callback Chaining (Callback Hell Demo)
 * * This example simulates three sequential asynchronous tasks 
 * using setTimeout to delay execution. Each function takes a 
 * callback that is responsible for starting the next task.
 */

// --- 1. First Task: Get Candies ---
function getCandies(callback1) {
    // Simulate an async operation that takes 3 seconds (3000ms)
    setTimeout(() => {
        const candies = "🍬";
        console.log("In our getCandies method, received:", candies);

        // Pass the result to the next function (callback1)
        callback1(candies);

        // Note: Returning 'candies' here would not work due to setTimeout's asynchronous nature.
    }, 3000);
}

// --- 2. Second Task: Hand Over Keys ---
function handOverKeys(candies, callback2) {
    // Simulate an async operation that takes 3 seconds (3000ms)
    setTimeout(() => {
        const keys = candies + "πŸ”‘"; // Append the key to the candies
        console.log("In our handOverKeys method, received:", keys);

        // Pass the cumulative result to the next function (callback2)
        callback2(keys);
    }, 3000);
}

// --- 3. Third Task: Onboarding ---
function onboarding(keys, callback3) {
    // Simulate an async operation that takes 3 seconds (3000ms)
    setTimeout(() => {
        const onboarded = keys + "πŸ“‹"; // Append the clipboard/onboarded symbol
        console.log("In our onboarding method, received:", onboarded);

        // Pass the final result to the final callback (callback3)
        callback3(onboarded);
    }, 3000);
}


// ------------------------------------------------------------------
// --- Execution: Creating the Callback Chain (The "Pyramid") ---
// ------------------------------------------------------------------

console.log("Start of execution. All tasks will take 3 seconds each.");

getCandies((candies) => {
    // After 3 seconds (Task 1 finishes), this callback runs
    handOverKeys(candies, (keys) => {
        // After 6 seconds (Task 2 finishes), this nested callback runs
        onboarding(keys, (onboarded) => {
            // After 9 seconds (Task 3 finishes), this innermost callback runs
            console.log("-----------------------------------------");
            console.log("βœ… Final Result: Welcome to our restaurant! You have the following items:", onboarded);
            console.log("-----------------------------------------");
        })
    })
});

// The next line runs immediately, before any of the asynchronous functions
console.log("Execution queue started. Waiting for results...");

Enter fullscreen mode Exit fullscreen mode

Output

Start of execution. All tasks will take 3 seconds each.
Execution queue started. Waiting for results...
In our getCandies method, received: 🍬
In our handOverKeys method, received: πŸ¬πŸ”‘
In our onboarding method, received: πŸ¬πŸ”‘πŸ“‹
-----------------------------------------
βœ… Final Result: Welcome to our restaurant! You have the following items: πŸ¬πŸ”‘πŸ“‹
-----------------------------------------

=== Code Execution Successful ===
Enter fullscreen mode Exit fullscreen mode

Promises in Js

/**
 * Asynchronous Promise Chaining (Cleaner Code)
 * * This example refactors the previous sequential tasks to use Promises, 
 * which makes the asynchronous flow linear and much easier to read.
 * * Each function now returns a Promise that resolves when the task is complete.
 */

// --- 1. First Task: Get Candies (Returns a Promise) ---
function getCandies() {
    // Return a Promise that resolves after 3 seconds
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            const candies = "🍬";
            console.log("In our getCandies method, received:", candies);
            // On success, resolve the promise with the result
            resolve(candies);
        }, 3000);
    });
}

// --- 2. Second Task: Hand Over Keys (Returns a Promise) ---
function handOverKeys(candies) {
    // Function now takes the result from the previous step as a regular argument
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            const keys = candies + "πŸ”‘"; 
            console.log("In our handOverKeys method, received:", keys);
            // Resolve the promise with the new cumulative result
            resolve(keys);
        }, 3000);
    });
}

// --- 3. Third Task: Onboarding (Returns a Promise) ---
function onboarding(keys) {
    // Function takes the result from the previous step as a regular argument
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            const onboarded = keys + "πŸ“‹"; 
            console.log("In our onboarding method, received:", onboarded);
            // Resolve the promise with the final result
            resolve(onboarded);
        }, 3000);
    });
}


// ------------------------------------------------------------------
// --- Execution: Creating the Promise Chain (.then() structure) ---
// ------------------------------------------------------------------

console.log("Start of execution. All tasks will take 3 seconds each.");

getCandies()
    // Task 1: getCandies runs. When it resolves, the result (candies) is passed here.
    .then(candies => {
        // Start Task 2 and return its promise to continue the chain
        return handOverKeys(candies);
    })
    // Task 2: handOverKeys runs. When it resolves, the result (keys) is passed here.
    .then(keys => {
        // Start Task 3 and return its promise to continue the chain
        return onboarding(keys);
    })
    // Task 3: onboarding runs. When it resolves, the final result (onboarded) is passed here.
    .then(onboarded => {
        // Final action after all promises have successfully resolved
        console.log("-----------------------------------------");
        console.log("βœ… Final Result: Welcome to our restaurant! You have the following items:", onboarded);
        console.log("-----------------------------------------");
    })
    // Single .catch handles any error (rejection) from any step above
    .catch(error => {
        console.error("An error occurred during the process:", error);
    });


// This line still runs immediately, as before.
console.log("Execution queue started. Waiting for results...");
Enter fullscreen mode Exit fullscreen mode

Output

Start of execution. All tasks will take 3 seconds each.
Execution queue started. Waiting for results...
In our getCandies method, received: 🍬
In our handOverKeys method, received: πŸ¬πŸ”‘
In our onboarding method, received: πŸ¬πŸ”‘πŸ“‹
-----------------------------------------
βœ… Final Result: Welcome to our restaurant! You have the following items: πŸ¬πŸ”‘πŸ“‹
-----------------------------------------

=== Code Execution Successful ===
Enter fullscreen mode Exit fullscreen mode

*Try with Async-Await *

/**
 * Asynchronous Async/Await Chaining (Most Readable Code)
 * * This example uses the ES8 'async/await' keywords to handle the Promise 
 * chain, resulting in code that looks synchronous and is highly readable.
 */

// --- 1. First Task: Get Candies (Returns a Promise) ---
function getCandies() {
    // Return a Promise that resolves after 3 seconds
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            const candies = "🍬";
            console.log("In our getCandies method, received:", candies);
            // On success, resolve the promise with the result
            resolve(candies);
        }, 3000);
    });
}

// --- 2. Second Task: Hand Over Keys (Returns a Promise) ---
function handOverKeys(candies) {
    // Function now takes the result from the previous step as a regular argument
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            const keys = candies + "πŸ”‘"; 
            console.log("In our handOverKeys method, received:", keys);
            // Resolve the promise with the new cumulative result
            resolve(keys);
        }, 3000);
    });
}

// --- 3. Third Task: Onboarding (Returns a Promise) ---
function onboarding(keys) {
    // Function takes the result from the previous step as a regular argument
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            const onboarded = keys + "πŸ“‹"; 
            console.log("In our onboarding method, received:", onboarded);
            // Resolve the promise with the final result
            resolve(onboarded);
        }, 3000);
    });
}


// ------------------------------------------------------------------
// --- Execution: Creating the Async/Await Flow (Synchronous look) ---
// ------------------------------------------------------------------

// We define an async function to use the 'await' keyword inside it.
async function startProcess() {
    console.log("Start of execution. All tasks will take 3 seconds each.");
    console.log("Execution queue started. Waiting for results...");

    try {
        // 1. Wait for getCandies() to resolve (3 seconds)
        const candies = await getCandies(); 

        // 2. Wait for handOverKeys() to resolve (3 seconds)
        const keys = await handOverKeys(candies);

        // 3. Wait for onboarding() to resolve (3 seconds)
        const onboarded = await onboarding(keys);

        // Final action after all steps are complete (Total 9 seconds)
        console.log("-----------------------------------------");
        console.log("βœ… Final Result: Welcome to our restaurant! You have the following items:", onboarded);
        console.log("-----------------------------------------");

    } catch (error) {
        // Error handling for any rejected promise in the chain
        console.error("An error occurred during the process:", error);
    }
}

// Call the async function to start the chain
startProcess();
Enter fullscreen mode Exit fullscreen mode

Same output.

DOM MANIPULATION

DOM - Document object model

Selection: The JavaScript uses document.getElementById() to grab references to the button (incrementButton) and the text element (counterDisplay).

State: The counter variable holds the current value, which is the application's state.

Event Listener: The line button.addEventListener('click', () => { ... }); waits for the user to click the button.

Manipulation: Inside the listener, two key manipulations happen:

The state (counter) is updated: counter++.

The visual DOM is updated: display.textContent is changed to show the new value.

This pattern (Select, Listen, Manipulate) is the foundation of all web interactivity! Let me know if you'd like to add more features, like a "Reset" button!

Top comments (0)