Skip to content
Catalina edited this page Feb 13, 2018 · 4 revisions

JavaScript

var

The variable statement declares a variable, optionally initializing it to a value.

Syntax: var nameOfMyVariable;

We can assign an initial value to our variable:

  • var amount = 500;
  • var currency = 'GBP';
  • var borderlessAccount = true;

Object

An object can be created with figure brackets {…} with an optional list of properties. A property is a “key: value” pair, where key is a string (also called a “property name”), and value can be anything.

var user = {}; // Creating an empty object
user.name = 'Bill';
user.phoneCountryCode = 44;

Arrays

Ordered collection, list of elements

var currencies = ['GBP', 'EUR', 'AUD'];

How to access a value of:

  • Object: objectName.PROPERTY -> user.currency
  • Array: arrayName[ELEMENT_POSITION] -> currencies[2]

How to add more properties to an Object:

objectName.NEW_PROPERTY = MY_VALUE(any type) -> user.country = 'United Kingdom';

How to add more elements to an Array:

currencies.push('USD'); // Adds to the end

currencies.unshift('BRL'); // Adds to the front

Let's add this array to our user object:

user.currencies = currencies;

How to loop over an Array:

for (var i = 0; i < currencies.length; i++) {
  // Overwrite all the items for their lower case version
  // and assign back to the variable:
  currencies[i] = currencies[i].toLowerCase();
}

or

currencies.forEach(function(currency, index) {
  currencies[index] = currency.toLowerCase();
});

References:

Clone this wiki locally