Conditions & Loops
Let's explore the basic flow control structures in OneVision Scripts.
Conditional statements
In OneVision Scripts, the conditional statements are if, else if, and else. These statements allow you to execute code based on certain conditions.
Here is how they work:
- When the program reaches a conditional statement, it evaluates a boolean expression (true or false).
- If the
ifcondition is true, the code inside its block runs. - If the
ifcondition is false, the program checks anyelse ifconditions in order. If one of them is true, its block executes. - If none of the
iforelse ifconditions are true, the code inside theelseblock (if present) runs.
This structure ensures that only one block of code executes in a given conditional chain.
if (condition) {
// Code to execute if condition is true
} else if (anotherCondition) {
// Code to execute if anotherCondition is true
} else {
// Code to execute if all previous conditions are false
}
For example:
var score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else if (score >= 70) {
console.log("Grade: C");
} else {
console.log("Grade: F");
}
Loop statements
In OneVision Scripts, the loop statements are for and while. These statements allow you to repeat code multiple times.
Here is how they work:
While loop
A while loop repeatedly executes a block of code as long as a given condition is true.
- The program first checks the boolean condition.
- If the condition is true, it executes the code inside the loop.
- After executing the block, it checks the condition again.
- The loop continues until the condition becomes false.
while (condition) {
// Code to execute as long as condition is true
}
For example:
var count = 0;
while (count < 5) {
console.log("Count: " + count.toString());
count++;
}
For loop
A for loop repeats the code a specific number of times, is used when you know in advance how many times you want to repeat a block of code. In OneVision Scripts, it has three parts separated by semicolons:
- Initialization: Set the starting value.
- Condition: The loop runs as long as this is true.
- Increment: Change a value after each iteration.
for (initialization; condition; increment) {
// Code to execute each iteration
}
For example:
for (var i = 0; i < 5; i++) {
console.log("Iteration: " + i.toString());
}