Search This Blog

2026/08/09

Javascript:Guess output of code

Guess Output of following code.

Code:
let arr=["apple", "banana", "cherry"];
let [a,...rest]=arr.reverse();
console.log(a);
console.log(rest);

Output:
cherry
[ 'banana', 'apple' ]

Explaination:
1. The array `arr` is defined with three elements: "apple", "banana", and "cherry".
2. The `reverse()` method is called on the array, which reverses the order of the
elements in the array. After reversing, the array becomes ["cherry", "banana", "apple"].
3. The destructuring assignment `[a, ...rest]` is used to extract values from the
reversed array:- `a` takes the first element of the reversed array, which is "cherry".
   - `...rest` collects the remaining elements into a new array, which
is ["banana", "apple"].
4. Finally, `console.log(a)` prints "cherry", and `console.log(rest)`
prints the array ["banana", "apple"].

Javascript:convert given asyncronous code to syncronous


Modify the code snippet 1 so that function logic  is executed synchronously.


Code Snippet 1:
function myLogic() {
    setTimeout(() => {
        console.log("Logic executed");
    }, 2000);
}

console.log("Before executing logic");
myLogic();
console.log("After executing logic");

Output:
Before executing logic
After executing logic
Logic executed


Code Snippet 2:
function myLogic() {
    new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log("Logic executed");
            resolve();
        }, 2000);
    })
}

console.log("Before executing logic");
myLogic();
console.log("After executing logic");

Output:
Before executing logic
After executing logic
Logic executed

Code Snippet 3 :Final Change
async function myLogic() {
    await new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log("Logic executed");
            resolve();
        }, 2000);
    })
}

console.log("Before executing logic");
await myLogic();
console.log("After executing logic");

Output:
Before executing logic
Logic executed
After executing logic