Object-Oriented JavaScript — Arrays and Conditionals

Image for post
Image for post
Photo by Jen Theodore 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 arrays and conditionals.


An array is a sequence of values.

It’s an object type.

It can have anything in them, including primitive values and objects.

We can define an empty array with:

And we can put values in them by writing:

Array index is the position of the item. Arrays start with 0 as its index.

So the first item has index 0.

We can access any element using square brackets:

then we get 1.

Adding/Updating Array Elements

We can add a value to an array by assigning a value to it.

For instance, we can write:

Then we get:

We can write:

Then we get:

We can have gaps in an array.

Gaps are filled with undefined .

Assignment can also be used to update an element.

Arrays of Arrays

We can have an array of arrays.

For instance, we can write:

Then we can access entry by writing:

We return the first entry of th first array in a ,. so we get 1.

We can also use the square brackets to get a character from a string, so we can write:

And we get:

which is 'f' .

Conditions and Loops

Conditional statements include the if and switch statements.

They let us run code depending on the condition given.

Loops include the while , do...while , for , for...in , and for...of loops.

Code Blocks

A code block is a part of a piece of code that’s separated from the outside.

For instance, we can write:

to create a block.

let lets us create variables that are only available within the block.

Blocks can be nested, so we can write:

We have blocks that are nested in other blocks.

if condition

We can use the if block to run something given a condition.

To do that, we can write:

then the body is only run when a is bigger than 3.

We can have any logical expression between the parentheses.

else Clause

The else clause can be added to an if condition if we need to run something if the if condition is false .

For example, we can write:

They can be nested like any other blocks.

The if condition is handy for checking if a variable exists.

For instance, we can write:

Then we check if foo is initialized by checking if it’s undefined .

Image for post
Image for post
Photo by Markus Spiske on Unsplash


Arrays are a sequence of values.

The if statement lets us run code conditionally.

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