- Published on
How javascript is different than other languages
- Authors
- Name
- Jignesh Sanghani
- @jignesh19961020
Being a newbie in JavaScript community may be it sucks you while your code stuck between sync/async process. Because the way javascript act is different than other languages. So here I’ll try to give you a basic understanding of javascript's behavior. First, we understand how javascript is different than another language. Let’s take an example:
JavaScript code:
console.log('run task1');
function task4() {
jQuery.get("https://jsonplaceholder.typicode.com/todos", function(data, status){
console.log(data);
});
}
console.log('run ' + task4());
Output:
run task1
run undefined
After some time it returns JSON in the console of a browser.
PHP code:
print_r('run task1');
$url = 'https://jsonplaceholder.typicode.com/todos';
$data = http_build_query( array( 'name' => 'value' ) );
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded",
'method' => 'POST',
'content' => $data,
),
);
$context = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
print_r($result);
Output:
run task1
{ "name": "value", "id": 201 }
Now you see the difference between javascript and other languages. As you know javascript is single threaded language. JavaScript execution maintained by three component while executing code. Call Stack(LIFO), Event Loop, Callback Queue(FIFO)
Call Stack It’s a data structure which records the function calls, basically, wherein the program we are. If we call a function to execute, we push something on to the stack, and when we return from a function, we pop off the top of the stack. Call stack is use LIFO(Last in first out) mechanism. Look at below example
Web APIs A script is a program code that doesn't need pre-processing (e.g. compiling) before being run. In the context of a Web browser, scripting usually refers to program code written in JavaScript that is executed by the browser when a page is downloaded, or in response to an event triggered by the user.
Callback Queue JavaScript runtimes contain a message queue which stores a list of messages to be processed and their associated callback functions. These messages are queued in response to external events (such as a mouse being clicked or receiving the response to an HTTP request) given a callback function has been provided
Event Loop The Event Loop is a queue of callback functions. When an async function executes, the callback function is pushed into the queue. The JavaScript engine doesn't start processing the event loop until the code after an async function has executed. remember one thing event loop run when a stack is empty, so our call back function will be executed after task stack empty
js event loopLook at the above example:
The first line goes to call stack and print on console The second line goes to call stack. This line says wait for 500ms call stack push this process to web API since the setTimeout function is web APIs function. After completion, this function goes to the task queue. At there event loop wait till stack empty, if the call stack empty event loop push task queue first task to call stack and executed. The third line went to call stack before second line output. Now you understand how javascript asynchronous code works. While in other languages like PHP, Python, Java .. all statement execute in blocking manner means synchronously. Code wait till above code executed successfully.
This behavior of javascript helps us to make our web apps faster. But what is the problem using asynchronous everywhere in js? Let’s look at another example which will help us to understand some cases where we don’t need to go js ahead of the current state of the code.
let c = new Customer();
let res = c.getCustomer();
console.log(res);
c.getCustomer() is a promise( we'll see what is promise in the later section), which will get a list of customer's details in JSON formatted. the output of above code is:
Promise { <pending> }
It means Promise pending still the code of getCustomeris running in the back and before that line console.log(res) printed. at this point, we need to be javascript act as syncronous process. but javascript behavior is asynchronous. then how we can handle this kind of behavior of javascript?
thinking how js can be like sync
We have three option, which we can use Callback function, Promise, Async/Await.