2

I ran the following code in my console:

    let a3 = 100;
    setTimeout( function(){
            a3 = a3 + 1;
            console.log(a3);
        }, 4000);

     console.log( ++a3+'st'); 

I do not understand the execution sequence of the above JavaScript Code.

I expected the output to be

EXPECTED OUTPUT

101st     //since console.log(++a3+'st') executes first
101st1   //the setTimeout() function executes

But the actual output I got is

ACTUAL OUTPUT

101st
102    

I want to understand that, if a3 becomes a string "101st" after console.log( ++a3+'st'); runs, then why does the code inside setTimeout()

setTimeout( function(){
        a3 = a3 + 1;
        console.log(a3);
    }, 4000);

which runs later, give a3 as 102 and not 101st1 since "101st" + 1 = "101st1" ?

1
  • 1
    You don't set or assign a3 with 'st'. You simply increment it, string append and logs it when you do console.log( ++a3+'st'); Commented Jan 30, 2019 at 7:49

3 Answers 3

1

if a3 becomes a string "101st" after console.log( ++a3+'st'); runs

It doesn't. All that statement does for a3 is it increments it by one via the ++a3 part. That is then concatenated with st, resulting in a string which is console.logged, but not saved anywhere - a3 remains the incremented number.

For a3 to become the string, you would have to explicitly assign the result to a3:

let a3 = 100;
setTimeout(function() {
  a3 = a3 + 1;
  console.log(a3);
}, 500);

console.log(a3 = ++a3 + 'st');

(but please don't do something like that - assignments should not be parsed as expressions, it's quite a code smell)

Sign up to request clarification or add additional context in comments.

Comments

0

Lets break down the code

The following is synchronous code and will execute immediately hence writing (++100+'st')=>(101+'st')=>101st in console

 let a3 = 100;
 ...
 console.log( ++a3+'st'); 

The setTimeout is an asynchronous block of code and will execute after the synchronous code has been executed, since a3 is now 101, a3+1 will output 102

setTimeout( function(){
  a3 = a3 + 1;
  console.log(a3);
}, 4000);

hence you get the output

101st
102

Comments

0

What is actually fine. When you are calling this console.log( ++a3+'st'); It only increases it to 101 but not to 101st use this

let a3 = 100;
    setTimeout( function(){
            a3 = a3 + 1;
            console.log(a3);
        }, 4000);
a3 = (a3 + 1) + 'st'
console.log(a3); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.