I'm sure you heard of 'AJAX', and if you are a beginner, wondering what does it means and how it is used in JavaScript?
AJAX = Asynchronous JavaScript and XML. XML(Extensible Markup Language) is a format, lightweight that is used to send data from browser to server and server to browser. The most common way of sending data nowadays is a JSON (JavaScript Object Notation).
Yes, JavaScript is a synchronous language. Which means only one operation can be carried out at a time. Thatβs where AJAX comes into play. Using asynchronous JavaScript (such as callbacks, promises, and async/await), you can perform long network requests without blocking the main thread.
Synchronous code is executed one after the other. This means each statement has to wait for the previous one to finish executing.
const second = () => {
console.log('Second');
}
const first = () => {
console.log('Hey there');
second();
console.log('The end');
}
first();
// Hey there
// Second
// The End
Asynchronous code takes statements outside of the main program flow, allowing the code after the asynchronous call to be executed immediately without waiting. I will add setTimeout function, which is a timer in JavaScript, that allows us to write code that will be executed later.
const second = () => {
setTimeout(() => {
console.log('Hey There Async')
}, 2000)
}
const first = () => {
console.log('Hey there');
second();
console.log('The End');
}
first();
// Hey there
// The End
// Hey There Async (this will appear after 2 seconds)
setTimeout does not pause the execution of the code. It only schedules something to happen in the future, and then immediately continues to the next line.
Top comments (0)