Learning Javascript with Object Graphs
One of the secrets to being a super effective JavaScript developer is to truly understand the semantics of the language. This article will explain the basic elemental parts of JavaScript using easy to follow diagrams.
What exactly is a variable?
A variable in JavaScript is simply a label that references a value in memory somewhere. These values can be primitives like strings, numbers, and booleans. They can also be objects or functions.
Local Variables
In the following example, we will create three local variables in the top-level scope and point them to some primitive values:
// Let's create some local variables in the top scope
var name = "Tim Caswell";
var age = 28;
var isProgrammer = true;
var likesJavaScript = true;
// Test to see if the two variables reference the same value
isProgrammer === likesJavaScript;- Output
- => true
Notice that the two boolean variables point to the same value in memory. This is because primitives are immutable and so the VM can optimize and share a single instance for all references to that particular value.
In the code snippet we checked to see if the two references pointed to the same value using === and the result was true.
The orange box represents the outermost closure scope. These variables are top-level local variables, not to be confused with properties of the global/window object.
Objects
// Create a parent object
var tim = {
name: "Tim Caswell",
age: 28,
isProgrammer: true,
likesJavaScript: true
}
// Create a child object
var jack = Object.create(tim);
// Override some properties locally
jack.name = "Jack Caswell";
jack.age = 4;
// Look up stuff through the prototype chain
jack.likesJavaScript;- Output
- => true
Global Variables
If you leave off the var statement from
View the discussion thread.blog comments powered byDisqus
