← return to Chapter 7.1

JavaScript Arrays and Objects Cheat Sheet

Arrays

There are several ways of creating arrays

x = new Array();
x = [];
x = new Array(size);
x = new Array (element1, element2, ..., elementN);
x = [element1, element2, ..., elementN)];

Access elements using varName[index] with indexes starting at 0 (no offset) up to 1 less than the size.

index = 3;
list = new Array(0, 1, 2, 3, 4, 5);
result = list[2] + list[index];
list[0] = result;

Special form of for loop for traversing an array:

let testArray = [1,2,3,4];
for (let n in testArray) {
  console.log(n);
}

Multidimensional Arrays

In JavaScript, a multidimensional array is simply an array of arrays. We create the array by having arrays inside the array, with the easiest way being:

let microSudoku = [
  [1,2, 3,4], [3,4, 1,2], [2,1, 4,3], [4,3, 2,1]
];

console.log("Multidimensional with for")
for (let row = 0; row < microSudoku.length; ++row) {
  let line = "";
  for (let col = 0; col < microSudoku[row].length; ++col) {
    line = line + microSudoku[row][col] + " ";
  }
  console.log(line);
}

Associative Arrays

Another common type of array is the associative array, which uses a key/value pair for accessing elements. These are commonly used to store items with a meaningful label then be able to access that item with the key. In JavaScript these are created and used as follows:

let associative = {"Strength": 11,
  "Intelligence": 18, "Dexterity": 14};
console.log("strength is " + associative.Strength);
console.log("Intelligence is " + associative["Intelligence"])
let dex = "Dexterity"
console.log(associative[dex]);

Classes

The old-school way of creating objects was using prototypes. Since ES6 we have had a class construct.

class Employee {
  // private instance variables
  #name;
  #empId;
  // public instance variables
  publicVariable;

  // constructor
  constructor(name, empId) {
    this.#name = name;
    this.#empId = empId
  }

  // methods
  getName() {return this.#name;}
  getEmployeeId() {return this.#empId;}

  toString() {
    return `${this.#name} (${this.#empId})`;
  }

  // static methods
  // (don't require instance, just class name)
  static isEven(n) {
    return (n % 2) === 0;
  }
}

let e1 = new Employee("Bob", 1);
console.log(e1.toString());

Inheritance

JavaScipt supports inheritance by using the extends keyword. The inherited class gains all the methods and non-private instance variables. The super can be used to call the parent version of classes, which is useful when overriding methods needs the original version. Here is an example:

class SalariedEmployee extends Employee {
  #salary;

  constructor(name, eid, salary) {
    super(name, eid);
    this.#salary = salary;
  }

  getSalary() {return this.#salary}

  toString() {
    return super.toString() +
        " Salary " + this.#salary;
  }
}

let e2 = new SalariedEmployee("Alice", 2, 120000);
console.log(e2.toString());

Polymorphism and Duck Typing (interfaces)

Due to JavaScripts' use of dynamic variables, we use duck typing to perform polymorphic operations. Because functions are treated like a variable, we can check to see if a function exists as follows:

if (myObject.myMethod) {
  // we have the desired method
  myObject.myMethod();
} else {
  // handle not having the method here
}

Binding objects

The this keyword in JavaScript works a bit different in JavaScript than in most of the other object-oriented languages. The value of this changes based on how a function is called. The value of this is not the object that was created, but by the object used to call the function. This means that if you want to use an object method as a callback, things are not going to work. to get around this java has the bind function. Can add parameters after the "this" object.

function callback(toCall) {
  console.log("callback: " + toCall());
}

// will cause exception because this bound to callback
//callback(e1.toString);

// will work as expected
callback(e1.toString.bind(e1));

// will use child data but with parent method
callback(e1.toString.bind(e2));

closures

This technique lets you hide values by using encapsulation via function scope.

function closureClass(msg) {
  let protectedMessage = msg;
  return class {
    getProtectedMessage() {
      return protectedMessage;
    }
  };
}

let closureDemo =
  new (closureClass("This is a protected message"));
console.log(closureDemo.getProtectedMessage());

JSON

JSON (JavaScript Object Notation) is a human-readable data transfer format that uses the code Java uses to create objects as the format making it easy to get data and start using it with JavaScript.

let jsonString =
  '{"name": "Alice", "age": 42}';
let obj = JSON.parse(jsonString);

console.log(obj.name); // Alice
console.log(obj.age); // 42

obj.age = 29;
jsonString = JSON.stringify(obj);
console.log(jsonString);
← return to Chapter 7.1