Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is order of evaluation sequential in Javascript?

Tags:

javascript

At a job interview, I was perplexed to hear "javascript can evaluate statements out of order." To what degree is this true? I can imagine a hundred ways to explicitly evaluate statements out of order -- such as in a time-sharing operating system. But he seemed to say that if I evaluate

console.log('a')
console.log('b')

that the Javascript spec somehow doesn't require that the output would be a first then b. I can imagine that the evaluator might try to evaluate the second statement if the IO of the first is blocking if the statements are functionally pure, i.e. no side effects, but side effects must always occur in sequence, correct? And of course IO is one big side effect.

To what extent can spec-compliant Javascript evaluate out of order? Or was this a case of miscommunication?

like image 436
Cuadue Avatar asked Jan 31 '13 20:01

Cuadue


1 Answers

JavaScript is single threaded (web workers aside). Period. ECMA-262 Language Specification Edition 5.1 says nothing about out-of-order execution. In your simple example these two statements are guaranteed to be executed in the same order.

Moreover, single block of JavaScript code will never be interrupted by any other block of code, e.g. event handler. That's why long running blocks of code cause UI to freeze:

for(var i = 0; i < 1000000000; ++i) {
    console.log(i);
}

It's guaranteed that the block of code above will never be interrupted or reordered. As long as the loop is running, all event handlers and timeouts wait for single thread. And of course, numbers will appear in correct order.

What might be executed out-of-order is an asynchronous timeout:

setTimeout(function() {
    console.log('a');
}, 1);
setTimeout(function() {
    console.log('b');
}, 1);

Here you might expect a to be printed first, but it's possible that JS engine will reorder these events. After all you schedule these calls to execute at almost the same point in time.

like image 95
Tomasz Nurkiewicz Avatar answered Sep 22 '22 01:09

Tomasz Nurkiewicz