Flag job

Report

What is the race condition in JavaScript?

Min Experience

0 years

Location

remote

JobType

full-time

About the job

Info This job is sourced from a job board

About the role

JavaScript does not support multithreading in the same way as the other programming languages do. However, there is a term race condition which means an unpleasant situation when the result of the program execution strongly depends on the order in which separate commands are performed. Generally a race condition can occur when two or more threads are trying to get access to the same variable, at least one of them is willing to change a value of this variable and the threads don't use any blocking. If these three conditions are met, the order of getting access to this variable becomes undefined which leads to various unexpected results. The question whether JavaScript can have a race condition or not is still open to debate. Arguments against the race condition in JavaScript Since JavaScript is a single-threaded language one may think that a race condition is not possible. For example, two synchronous functions in the code below are trying to access the same variable. There should be no problem since they will be executed one by one. While one operation is being performed nothing else can happen, all other actions are blocked until the current one is finished. Arguments for the race condition in JavaScript Some situations prove that not only multithreading can be a reason for the race condition. Let's create a program illustrating the possible existence of this issue. There will be a variable with the value of 0 and two functions trying to add 50 and 60 to it. To make things more interesting there will also be a promise for a random delay. If you run the whole program several times you will get different results. For example, the current amount for both functions can be 0. To avoid risky outcomes you need to make sure there is no possibility for processes to be executed at the same time. You can rewrite the previous function to make it safe as shown below. Another approach to resolving this issue is the use of Mutex. Summary Race condition is a problematic situation when several processes or threads are trying to have access to the same resource. Although some programmers insist that there is no race condition in JavaScript, you can still face some situations when resource sharing can lead to unexpected results. That's why it's very important to be careful with the flow of events in your program.

About the company

The Non-Commercial Foundation "Place for new people" is a non-commercial organization registered for the public benefit and performs only and exclusively non-commercial activities.

Skills

javascript