Control Structures
Iteration, conditions, nested conditions
The If Loop
the if loop is the best loop withought it you would be much harder to copare values, run things when conditions are met, and much more.
Below is an example of an If loop
let Count = 1
if (Count === 1) {
Count++
}
If loops require a condtion that is checked to allow the loop to run the code inside of it
In this example I madea count variable that is set to the value of 1 When putting your condition inside the if loop which in this case it checks if the var Count is the value of 1, it will run the code inside which inceases the Count var by 1
Conditions
== — Equal to (checks for value equality, type conversion may occur)
=== — Strictly equal to (checks for both value and type equality)
!= — Not equal to (checks if values are not equal, with type conversion)
!== — Strictly not equal to (checks if values or types are not equal)
> — Greater than
< — Less than
>= — Greater than or equal to
&& — Logical AND (returns true if both conditions are true)
|| — Logical OR (returns true if at least one condition is true)
! — Logical NOT (negates a condition, returns true if the condition is false)
Above examples from AI
Using the above conditinals you can make your if loop do whatever you want it to do!
Nested Conditions
nested conditions are very helpful but if they are too many nested conditions then debugging will be much harder
let Value = true
if (Value) {
if (Count === 2) {
Count++
}
}
In the above code is an example of a nested condition. A nested condition is when a condition is ran if another condition is met. A nested condition can be as long as you want but is not recommended to make your nested condition very long
//this is how not to do neted conditionals
let ExampleValue = true
let ExampleValue2 = true
let ExampleValue3 = true
let ExampleValue4 = true
let ExampleValue5 = true
if (ExampleValue) {
if (ExampleValue2) {
if (ExampleValue3) {
if (ExampleValue4) {
if (ExampleValue5) {
console.log("HI!")
}
}
}
}
}
insted of nesting over and over try to add a if loop at the top of the current if loop to check if a value is met and if it is not the loop will return. This makes it much more easy to see were the err happened when debugging and make the code look more clean
let IsRunning = true
let CanJump = false
function jumpCheck(){
if(IsRunning){ return;} // if the player is running the function will be exited
CanJump = true
}