-1
var identifier = '0';
var serviceCodes = parseServiceCodes(identifier);
console.log(serviceCodes);

function parseServiceCodes(id){
  var serviceCodes = id + 'HYJSIXNS';
  return serviceCodes
}

0HYJSIXNS is returned in the console. But I thought that since JavaScript is asynchronous, the variable would be assigned before the function is returned, making it null.

3 Answers3

0

Javascript isn't asynchronous by default, and code is executed in order unless you specify that it shouldn't be. You're never making a call to an external resource, so there's nothing to be async here.

Bricky
  • 2,572
  • 14
  • 30
0

JS, like any interpreted language, is run line-by-line. In your example, at the parseServiceCodes callsite, execution goes from line 2 (the callsite) to line 6 (the function body).

Async behavior is introduced for time consuming operations, like HTTP requests. In this case, the expensive function either takes a callback parameter (code to run once the expensive operation is over) or returns a Promise which "resolves" with the computed data when ready.

To illustrate the first case, let's say we have a function getFromServer which needs a URI and a callback:

function getFromServer(uri, callback){ // ...

It doesn't matter exactly what happens under the hood, just that execution is given back to the main program after invocation. This means the program isn't blocked for the duration of this expensive operation. When getFromServer is done, it will come back and call callback with some data.

To learn more about the second case, Promises, I encourage you to read the documentation I linked to earlier in this response.

wbadart
  • 2,583
  • 1
  • 13
  • 27
0

You seem to misunderstand what it means to say that "JavaScript is asynchronous".

JavaScript is asynchronous because it supports and benefits from usage of asynchronicity, which is considered a common design pattern throughout the language by using features such as asynchronous callbacks, promises and even async/await, but this does not mean that all code is asynchronous.

You can easily write synchronous code, as you just demonstrated in your question, and there is no issue specifying a return value that is not a Promise.

This is because the code invoking it expects the return value to contain a string, which it then assigns to serviceCodes and uses that in the same tick.

If any of these terms above confuse you, please refer to their respective documentation and usage I've provided the links for.

Community
  • 1
  • 1
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153