A property is like a variable that is bundled in the object. It has its own name and value, with some properties being read-only and others able to be reassigned. To access an object's properties, you use a "dot" notation. That is, you start with the object name, then a dot
., then the name of the property.
let objectProperty = object.property;
Some properties are themselves objects, with their own properties and methods. You can chain property objects together with dot notation, digging deeper and deeper with each dot.
let subProperty = object1.propertyObj.property;
Where a property is like a variable, a method is like a function. You use the same dot notation to call an object's method, and you may pass the method parameters inside parentheses. Methods may return a value as well.
let methodReturn = object.method(param1, param2);
In most cases, you can create a new object using the
new keyword and assign it to a variable name. This keyword calls the
constructor method of the object type. For some objects, including the basic data types we talked about last time, you can use a shorthand of just the value. This is called a "literal constructor." In the following code, both lines create a new string:
let strA = new String("String A");
let strB = "String B";
An array is an ordered collection of other objects or values. Think of an array as a row of filing cabinets, with each one containing one element. Each element in an array has an index, a number that refers to its place in the array. You reference an element with the name of the array followed by the element's index in square brackets
. Array indexes start at 0 and count up.
let element1 = arr; // first element of array
An array is an object, so you can create it using
new Array(). You can also create an array using a literal constructor by just assigning a list of values inside square brackets to a variable name. In the following code, both lines create identical arrays:
let arrA = new Array(1,2,3);
let arrB = [1,2,3];
One of the most important properties of an array is the
length property. This holds the number of elements in the array, and it changes whenever an element is added or removed.
As an object, every array also has a number of default methods. You can add an element to the end of an array with the push() method, for example. Some of the methods of an array allow for very powerful data manipulation tricks, but that's a topic for the future.