JavaScript: Objects

Class-Free

Objects in JavaScript are class-free, meaning that they are not created via a static class (template) as they are in object-oriented programming languages such as C# or Java. Instead, JS objects are created through a prototypal system (a topic for another post). There is a base prototype object in JavaScript from which all other objects are created.

Literal Notation

Because of this prototypal system, all custom objects are created inline in a given script. Custom JS objects are primarily created through what is called a literal notation, they are ‘literally’ written out line-by-line in the script and are ‘literally’ built in memory as the script executes line-by-line.

Mutable Key/Value Collections

Objects in JavaScript are mutable, meaning they can be altered over time as a script executes and it is used, passed around, and manipulated by the script. They are also keyed collections, meaning JS objects are pretty much dictionaries with keys indicating named properties and their associated values. Due to this, JS object properties can be accessed in two ways, the traditional ‘Dot’ notation as seen in object-oriented programming languages such as C# and Java or through array like notation utilizing index operators (square brackets).

Pass-By-Reference

JS Objects are always passed by reference, meaning as an object is passed from function to function or throughout a script it is only its reference in memory that is being passed around not the actual object. This also means that the object is also not being copied or duplicated in any way as it is being passed around.

'use strict';

// JavaScript Objects
//  1. Mutable: they can be altered at will
//  2. Keyed Collections: keys point to values, other objects, or functions
//  3. Class-free: they are never predefined, no template
//  4. Keys are strings
//  5. Quotes around key strings are optional if the string is not a JS key word and is a proper JS identifier
//  6. Objects can be embedded
//  7. Objects are always passed by reference (never copied)

var emptyObject = {};

var person = {
    first_name: "Tim",       // Quotes optional since the property name string is a valid JS Identifier
    "last-name": "Clark",    // Quotes required since property name string is invalid
    address: {
        street: "143 South Main",
        city: "Salt Lake City",
        state: "Utah",
        zip: "84111"
    }
};

// Retrieval of Object Properties
var firstName = person.first_name;  // . notation can be used due to valid JS Identifier
var lastName = person["last-name"]; // [] bracket notation required due to invalid JS Identifier

// Undefined: retrieving non-existent properties results in the Undefined value
var middleName = person.middle_name; // middleName === undefined [property does not exist]

// TypeError Exception: when retrieving a non-existent property from a non-existent property
var account = person.account;        // Undefined
var balance = person.account.balance; // TypeError
// Avoid error and get back just undefined
var account = person.account && person.account.balance; // Undefined

// Property Updates by assignment
person.first_name = "Freddy";

// Augmentation based on Non-existent Property Assignment
var middle_initial = person.middle_initial; // Undefined
person.middle_initial = "Argyle";
middle_initial = person.middle_initial; // "Argyle"

JavaScript: All About Functions

First Class Objects

Functions within the JavaScript (JS) language are said to be “First Class Objects”, this means they are comparable to objects composed from classes in C# or Java. The difference however is that classes (object templates) do not exist in the JS language. Instead, JS objects are created through the replication of already existing prototype objects provided by the language, but this is a topic for another day. Unlike C# and Java objects, JS functions can accept parameters and contain executable code, when invoked that code can then be executed. This executable behavior is similar to methods in C# or Java, the only difference is C# or Java methods must exist within an object.

Named & Anonymous

Another feature of JS functions is that they can be either named or anonymous. Named functions receive a name by which they can be referenced at the time they are defined. Anonymous Functions on the other hand are not provided names in their definitions, instead they are assigned to a variable and referenced in that manner throughout a script.

"use strict";

// JavaScript Functions: First Class Objects
//  1. All functions in JavaScript are first class Objects
//     they do not have to exist inside an object
//  2. Functions all have Function.prototype as their Prototype Object
//  3. Unlike other Objects in JavaScript, Functions can be invoked
//  4. Functions can be stored in variables, objects, and arrays

// Named Function
// (referenced via the functions actual name)
function myFirstClassFunction(param){
    return "You passed me: " + param;
}
console.log(myFirstClassFunction("a Horse"));

// Anonymous Function
// (referenced via variable to which it is assigned)
var myAnonymousFunctionReference = function(param){
    return "You passed me: " + param;
};
console.log(myAnonymousFunctionReference("a Pillow"));

Passed as Arguments & Returned by Function

Because JS functions are objects and can be referenced they can also be passed around by reference. This means that JavaScript allows functions to be passed around a script as parameters to other functions to be used and executed by the receiving function’s executable code. Also, functions can be defined and set up by a ‘parent’ function and returned by that function as its result of execution. The passing of functions as arguments and the ability to return them is a feature of JavaScript that is not found in C# or Java. The closest thing to this in either language is a delegate, which is a special class that represents a method and can therefore be passed around.

'use strict';

// Passed as Arguments & Returned by Function
//  5. Can be passed as arguments to other Functions
//  6. Can be returned from other Functions
function iAcceptFunctionsAsParameters(param, func){
    return func(param);
}
console.log(iAcceptFunctionsAsParameters("a Bus", cool_function));


function iReturnFunctions(){
    return function (param){
        return "You passed me: " + param;
    };
}
// Obtaining reference to returned function
var returnedFunctionReference = iReturnFunctions();
console.log(returnedFunctionReference("a Bird"));

State & Behavior

In conjunction, JS functions can also have their own state (variables, data) as well as behavior (methods) to support their execution or to provide additional functionality specific to the owning function. This is very similar to C# and Java objects that receive variables and methods from the class definition from which they were created.

'use strict';

// State & Behavior
//  7. Functions are Objects and can therefore have Variables & Methods (functions) of their own
var functionWithStateBehavior = function(){
    return "I am the core functionality";
};

// Add a variable to the function
functionWithStateBehavior.state = "I am a variable property on the 'functionWithStateBehavior' function.";

// Add a method to the function
functionWithStateBehavior.behaviorMethod = function(){
    return "I am the extra Method on a Function";
};

console.log(functionWithStateBehavior());
console.log(functionWithStateBehavior.state);
console.log(functionWithStateBehavior.behaviorMethod());