Nature of JS
Chapter 15 opened my eyes to the many uses of functions in JS. Functions have three main roles: normal ( id(‘hello’) ), constructor ( new Date() ), and method ( obj.method() ). They can also be declared or combined with an expression (var id = function…). Functions can be called with any number of parameters, independent of what was initially defined. This flexibility allows you to pass additional parameters as an array but can also expose an undefined element.
You can check if a parameter is missing by comparing the optional arguments to an undefined or false value. Or by checking for a minimum length on the parameters. To alter the value of a variable from a function, the variable must be wrapped (array, hash, etc). It is important to understand param structure when using functions and methods. Named parameters via object literals can clarify function and method use.
Chapter 16 discussed variables in regard to scopes, environments, and closures. Scope is where you can call the variable (local vs. global, inner vs outer). Variables in JS are function scoped, meaning only functions can change a variable’s scope. It is important to assign a variable otherwise it becomes a global. Similar to other languages, it’s best to avoid global variables (and global objects) when possible.
The data structure that stores variable names and values is called an environment. Related, a closure is a function and that function’s scope. Closures are examples of environments that survive after the program has executed a function and its variable(s). Because of closures the scope of a variable might be maintained longer than anticipated, creating unanticipated results when using loops. This is often experienced using event handlers with loops on the DOM.
It is important to note that you can create objects without the need of a class. Also, all objects are like hashes (maps of keys to values) but also involve inheritance and other added layers of abstractions. The dot operator (ex. aaron.age) allows you to get/set/delete properties and call methods on objects. The bracket operator “” allows reference to properties through expressions ( [“person” + “name”] ).
Interestingly, every object can have another object as its prototype (creating a chain). This allows the first object to inherit properties from its prototype object. Setting a property only affects the first object where getting a property looks at all objects in the chain. You can protect an object by preventing extensions, and sealing or freezing its properties. I think of this similarly to setting permissions on a file.
A constructor function allows you create multiple objects with similar properties and is invoked using the “new” operator. JS constructors are dynamic, allowing you to return a direct instance of the object or whatever quality you desire from that object. But using an object as a map can cause problems. It’s better to use a library like StringMap.js when arbitrary keys exist.