This blog will discuss the use of a flag variable in JavaScript.
What is a Flag Variable in JavaScript?
A flag variable mainly acts as a boolean variable to have a value till a particular condition is satisfied. This variable is used to direct the execution of a function or statement and check for particular circumstances when the function is running.
Let’s move on to the following examples to get a better understanding of the stated variable.
Example 1: Utilization of Flag Variable Along With the Specified Value
In this example, a check will be applied on the flag variable based on a particular condition, including the specified value. Then, the corresponding result will be displayed accordingly:
let flagVariable = 0;
for(var i = 0; i < 5; i++) {
if(i == 2) {
flagVariable++;
}
}
if(flagVariable) {
alert("This alert is displayed with the help of the flag variable");
}
</script>
In the above code block:
- Firstly, initialize the flagVariable with “0”.
- After that, apply a “for” loop till a specified number such that upon a particular condition, the initialized flag variable is incremented by ”1” at each iteration via “if” loop.
- Lastly, based on the “for” loop and if the flag is up, i.e., “>0”, the stated message will be displayed via the “alert” dialogue box.
Output
It can be observed that, upon the satisfied condition, the stated message has been displayed.
Example 2: Utilization of Flag Variable Along With the User-defined Value
In this particular example, the “for” loop will be iterated till the number specified by the user and the corresponding outcome will be displayed:
let flagVariable = 0;
let rang = prompt('Enter the number', '')
for(var i = 0; i < rang; i++) {
if(i == 2) {
flagVariable++;
}
}
if(flagVariable) {
alert("This alert is displayed with the help of flag variable");
}
</script>
In the above code snippet:
- Likewise, initialize the flag variable with “0”.
- After that, input a number from the user that will act as an end limit for the “for” loop.
- In the next step, apply a “for” loop and iterate till the user-defined limit.
- It is such that if the user-defined number is less than “2”, the “if” condition remains false.
- In the other case, i.e., “>2”, the initialized flag variable will be incremented, and the added message will be displayed.
Output
As evident, the prompt dialogue box will appear when the input number is evaluated as greater than “2”.
Conclusion
In JavaScript, a flag variable specifies a value until a certain condition is met. The functionality of the flag variable has been discussed by iterating through a “for” loop till the specified limit or till a user-defined limit. This blog illustrated the implementation of a flag variable using JavaScript.