DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Mehul Lakhanpal
Mehul Lakhanpal

Posted on • Originally published at codedrops.tech

What's the order of execution?

setTimeout(() => console.log('1'), 0);

Promise.resolve().then(() => console.log('2'));

console.log('3');
Enter fullscreen mode Exit fullscreen mode

Thanks for reading πŸ’™

Follow @codedrops.tech for daily posts.

Instagram ● Twitter ● Facebook

Micro-Learning ● Web Development ● Javascript ● MERN stack ● Javascript

codedrops.tech

Top comments (2)

Collapse
 
alexkhismatulin profile image
Alex Khismatulin

That's going to be 3, 2, 1. Why:
Start execution. Put setTimeout's callback into the task queue. Since a promise is already resolved, put then's callback into the microtask queue. Execute console.log('3');. Then we execute the microtask(then's callback) and its console.log(2); because microtasks are executed before regular tasks whenever the call stack empties. Then the task(setTimeout's callback) executed and console.log(1); in it.

Collapse
 
ml318097 profile image
Mehul Lakhanpal

Awesome πŸ”₯πŸ˜„

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!