Values and variables: learn the rules of javascript!

Do you know what Harry Potter, Star Wars, the Marvel Universe and Game of Thrones all have in common? Rules and boundaries.

Yes, we can create vast imaginary, fictional realms for our minds to be entertained by - and in my earlier blog post I talked about the great storytellers of our time creating entire fantasy worlds as the setting for their tales. But that doesn’t mean those worlds don’t have strict guidelines!

The story of javascript is no different. It can do some weird and wacky things. But there are still rules people! 

You can either go on Twitter and join the multitudes complaining about how tricky and nonsensical javascript is compared to other programming languages. OR, you can simply learn the rules.

One Rule to Rule Them All

In my previous post about visualising a Javascript program, we imagined our primitive values as islands. The main takeaway:  they can be found with a set of coordinates  🗺️📍- in other words, a reference to a particular spot in the program's memory.

That’s all good and well, but it doesn’t explain how we are able to use these coordinates in our program.

If there is one rule I want you to remember above all others, it’s that we use expressions to locate values.

And by expression I mean a crazy genie with a big smiling expression on his face.

Genies are the workers in the Javascript universe. There are lots of them, and we use them EVERYWHERE in our code, whether it’s writing a string value, executing a function or accessing an object property.

The definition of an expression is code that results in a value. This is the same as asking, ‘Where can I find this value? 🙋

Every time you code a string value, the name of a variable, a function call or you access an object property, you are using an expression.

5 // is an expression.  By literally writing 5 down ( why we call them literals, right? ) you are asking the genie, 'Where is the number 5 in this javascript engine?'

'str1' === 'str2' // Where are these two strings, and are we talking about the same string - ie are they the same Locate the true or false island depending on the outcome 

myObj.title //Where is this object and does it have this property ❓ Locate the true or false island depending on the outcome 

count() // Where is the function count value so I can execute it?

Only genies can answer these questions. Using the value island’s coordinates, they find the value you’re looking for and POINT at it.

Whenever you write code which references values, or results in a value, you are asking a genie to find the value for you  🧞‍♂️. 

Genies as variables

The problem is, everytime you want to find a value you have to ask a new genie, and explain to him what it is you’re looking for. Very inefficient. Wouldn’t it be easier to ask for the same genie each time?

What we can do instead is kindly ask a genie to point at a particular value, and we give that genie a name we choose - like count.

let count = 0;

Now, all we need to do is ask for count when we’re looking for the value 0; 

There is a special term for this process: ASSIGNMENT.

When this happens, the genie flies down to the chosen island. If you recall (which you should, it’s almost impossible to forget), value islands all come with a toilet and microphone. Yes I did say it’s because value stands for Voice Activated Loo. But the REAL reason is do with assignment.

When we name a genie, he flies down to the island. And he sits on the loo seat. ‘This is now MY island’ he thinks, while trying to forget his throne is a toilet.

How does this help us remember the term, ‘Assignment’? The first 3 letters should imprint it in your memory forever.

Take a look at all these named genies - the kind of genie variables we would keep in an app:

var data = {};
const errorMessage = 'The form is broken. Darn!';
let count = 0;
let x = 10;
const endpoint = '/myApi';

Now you might be thinking of the different ways to name a genie, or in javascript terms, declare a variable, like let and const var. This is to do with scope, and for the moment it is out of scope of this post (see what I did there?).

Genies in ships

We now know how we can find individual value islands. But what about a collection of values? For that, we use objects, and objects are flying ships!

These structures do not keep values in them. They keep pointers! These pointers might have a name (keys, in objects) or a number (index, in arrays). 

The pointers can be imagined as the crew members in the flying ships. If you take a closer look, you will see they are genies! They are each responsible for finding a specific value.

How do we, as the programmer, access a property of an object? We don’t ask the genie crew member directly. That would be breaking the rules!

Instead we ask the ship captain. This well dressed fellow doesn’t represent anything visible in our code. Instead, he is a representation of the internal process of accessing an object property.

There are 2 ways the captain will carry out our instructions, when we're looking for a specific object property.

Dot notation

In code this looks like:

const developer  = {
  name: 'Sarah'
}
developer.name // 'Sarah'

In The Great Sync, this represents the captain leaning over the railing and pointing his gun down at a genie crew member.  From the genie's perspective, it would be like looking into the barrel of a gun (a giant dot).

Square bracket notation

In code this looks like:

developer['name'];

Notice the speech marks in ['name']. This is because the captain is shouting the name of the genie through the deck hatch [ ], to the crew members below.

When either dot or square bracket notation is used, we are asking for a genie to shine his light down on the value we want - and it’s the captain’s job to instruct the appropriate crew member.

Missing crew member 😱

It’s the captain’s worst nightmare. There’s a missing genie crew member on board the object ship. He only realises this when we, as the programmer, ask for a genie who is not there. Take this example:

const blog = {
  title: 'Learning Object Properties'
}

blog.content;  // ??

What happens? Does the captain panic? Does he crash the ship, terminating the entire program?

Of course not. He has a job to do - find us a value. If there’s no crew member ready to get us the value we need, he calmly instructs the closest genie to point his spotlight down at the undefined island.

Why undefined? It’s just so easy to find! This volcanic, molten island is always present and easy to locate with its large plume of smoke.

This way, the captain does his job and our program keeps running. We receive a value back - even if its not the one we intended.

The gaping hole in our mental model

Objects, arrays and functions are not primitive values. They are not natural islands, with a set of coordinates. They live in The Heap Multiverse, which is an invisible parallel realm. If this is so, how can genies find them?

const myObj  = {};  

How is the above line even possible, if there is no island with a loo for the genie to be assigned to?

We need another layer in our mental model. But no, genies won’t suddenly get special goggles to see into the Heap. That would be like Harry Potter sending his owl Hedwig to fetch the horcruxes, or Frodo travelling to Mordor by car. It’s not that easy.

Stick to the rules, people! 😜

Looking forward to addressing this topic in the next post.


© 2021 The Great Sync - All Rights Reservedkylo@thegreatsync.com