Object-Oriented JavaScript — Conditionals and Loops

Image for post
Image for post
Photo by Tine Ivanič on Unsplash

JavaScript is partly an object-oriented language.

To learn JavaScript, we got to learn the object-oriented parts of JavaScript.

In this article, we’ll look at conditionals and loops.

Ternary Operator

The ternary operator is a shorter version of the if-else syntax.

For instance, instead of writing:

We can write:

The ternary expression can be added with the ? and : symbols.

a === 3 is the conditional expression.

And the strings are what we return.

Switch

If we have lots of if conditions and else...if parts, then we can use the switch statements to write them,

For instance, we can write:

We have a switch statement with case clauses inside.

The case clause value is compared against a and the correct clause would be run based on the match.

We need the break keyword so that we can stop at the end of the clause.

The default clause is run when none of the other cases match.

Loops

Loops let us run code repeatedly.

JavaScript has the following loops:

  • while loops
  • do-while loops
  • for loops
  • for-in loops
  • for-of loops

The while loop takes a condition and runs some code.

For instance, we can write:

The code runs the while loop which increments i by 1 until it reaches 10.

The parentheses surrounds the condition to run the loop.

As long as the condition is true , it’ll be run.

The do...while loop is a slight variation of the while loop.

It’s different from the while loop in that the first iteration is always run.

We can use it by writing:

i is always incremented once.

Then the whether more iterations are run are determined by the condition inside the parentheses.

The for loop is the most widely used kind of loop.

It has the initialization clause which initializes the variable which we want to iterate.

The increment clause updates the variable.

The ending condition is also added so it can end.

For instance, we can write:

We keep incrementing i until it reaches 100.

We can vary this by moving the body to the loop heading:

But it doesn’t make much sense to do that.

Loops can be nested within each other.

For instance, we can write:

We have one loop nested in another loop.

Image for post
Image for post
Photo by Johannes Krupinski on Unsplash

Conclusion

The ternary operator lets us write if...else statements in a shorter way.

And we can create loops in various ways.

Written by

Web developer. Subscribe to my email list now at http://jauyeung.net/subscribe/. Email me at hohanga@gmail.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store