Fundamentals of Values and Variables in JavaScript

Fundamentals of Values and Variables in JavaScript

Introduction

To begin with, what can you say about this piece of code?

let pet = “Lion”

let animal = pet

pet= “dog”

You probably would ask what do we want to achieve with this simple code? because you already know what values and variables are, you’ve been coding for years, or even as a beginner, you’ve learned something about values and variable that you could simply say the answer to the code above. Yes you are right, that is why this article is not actually to teach you what values and variables are, rather about what runs through your mind when you are working with values and variables. Let see what goes through your mind when reading the code above, pay attention to every step you take to arrive at your conclusion.

Maybe you interpreted the code as, declare a variable called pet, set it to the string 'lion', then declare a variable called animal, set it to variable pet and finally re-set the variable pet to the string 'dog', maybe you say assign instead of set, maybe you interpreted it as store the string 'lion' into the variable pet, and store the variable pet into another variable animal, then restore the string 'dog' into the variable pet. Maybe what runs through your mind is in a slightly different order. And you eventually arrived at the answer that animal = 'lion', pet = 'dog'. Whatever it is that runs through you mind to arrive at the answer, that’s exactly what this article is all about, to reveal the big picture of your code before your eyes.

What happens when you say declare a variable? What does it mean to set a value? What can you do with different kind of value? Why do you sometimes get undefined, and sometime crash? Why are some values are immutable and some are mutable? Why does it seem contradicting when re-assigning immutable values? These are among other question that confuse not only the beginner software developers but also the developers with several years of experience. I struggle with this understanding for long before I could figure out the right mental model to deal with values and variables. In this article you will learn the exact mental process of handling variable and value without ambiguity.

By the way, if your answer to the code above is;

animal = “lion”, and pet = “dog” ,

then you are right.

Let's get started with mental model.

What is mental model?

Consider walking in your room with your eyes closed, and you want to switch on the light switch in the corner of your room, or take a bottle of cold water in the fridge, you will notice your legs and hands moving according to the picture of your room in your mind, guiding your steps within the room with a clear mental picture, you know what to do and why you have to do so. That’s is mental model. The picture of how something works that is been painted in your head is known as mental model.

Many fundamental concept in javascript like variable and the operation on it has some rooted manner that you’ve learned them. Many of us learned to imagine a variable like a box in which we can store values, or like a space in the memory of a computer where you store values and we carry this imagination all through our coding experience, and when we get to a certain point this seem to be contradicting. nothing is contradicting, it is just our mental model that need to be aligned with the right way the people that developed javascript had defined these concepts.

What is a value?

A value is a fundamental concept in JavaScript that can’t be defined through other terms, just as you can’t define a letter in the English alphabet by other terms, rather you can give an example of it. So in javascript, Number and String are values, likewise Objects and Functions.

Just as in the English alphabet that we have vowel and consonant letters, similarly in javascript we have primitive and non-primitive values.

Checking the Type of a Value

You can get what type a value is by using a predefined method in javascript called typeof() method. Open your developer console and pass a value into the bracket, then hit enter, you get the answer.

Let's see examples

console.log(typeof(“goat”)) // ‘string’

console.log(typeof(undefined)) // ‘undefined’

console.log(typeof(null)) // ‘object’

console.log(typeof(10)) //  ‘number’

console.log(typeof(true)) // ‘boolean’

console.log(typeof({})) // ‘object’ etc.

Primitive values

These values can’t be created or changed, they already exist in javascript, we can only point to them. We have seven types of primitive values just as we have six types of vowel letters in the English alphabet.

  1. Undefined - this is use for unintentionally missed value and it is the only value of this type.
let a = 2.

console.log(a) // 2
console.log(b) // undefined.  This is because you do not set be to any value.
  1. Null - thus is use for an intentionally omitted value. Null is the only value that lies about its type. It gives object whereas it is not an object.

Take for example

let a = null

console.log(a) // null
  1. Number - This is used for math calculation.

Numbers in javascript do not behave as mathematical numbers do.

Take for example

console.log(0.3 + 0.4 === 0.7) // true

console.log(0.3 + 0.4 === 0.700000004) // false

Special numbers are NaN, infinity and -0.

Note: NaN stands for not a number.

Take for example

let mark = 0;

let a = 1/mark //infinity

let b = 0/mark // NaN

let c = 1/-a // -0
  1. BigInts - big integers are number with variable such as in algebra for Example 2n, 3n, 4n etc. the “n” at the end makes it a big number, and as such it can’t be represented by regular number with precision. .

  2. String - in javascript string represent text. It can be written in any of these three ways.

I. With single quate e.g ‘string’

Ii. With double quotes e.g “string”

Iii. With back-ticks e.g `string`

Note: an empty string is a string as well

Take for example

console.log(“ “) // ‘string’

Property of a string

All string has some built in properties like length and index. This doesn’t mean strings are objects, in fact their properties are different from object property.

let place = “London”

console.log(London.lenght) // 6

console.log(London[0]) // L

Unlike in array that you can change the items, you can’t change anything in string despite the fact that you can use the same properties as in object and array. This is called Immutability.

  1. Symbol - this helps you hide some information in an object and control which part of the code can access it.

Note: JavaScript won’t allow you to set any property on primitive values, be it number, string, boolean or others.

Take for example

let twenty = 20;

twenty.cent = ‘dollar’ //???
  1. Boolean - this is a logical value that result in true or false.

Take for example

console.log( 3 === “3”) // false

console.log(3 == “3”) // true

Non-Primitive Values

Non-primitive values help you create your own value. These are the two non-primitive values in JavaScript

  1. Objects - This include arrays, dates, RegExps (Regular Expressions) etc. Since Objects are not primitive value, this means they are mutable, that is they can be changed. You can access their properties with dot (.) or bracket [ ] notations.
console.log(typeof({})) // Object

console.log(typeof([])) // Object

console.log(typeof(newDate)) // Object

console.log(typeof(Math)) // Object

In javascript, you can create your own value with object literal. Any time you use ‘{ }’ object literal, you create a new object value.

Take for example

let profile = { };

let education = { };

The same is applicable to array, dates, and other objects.

  1. Functions - these are values that are defined so that we can reuse them by calling them later and run the code inside them.

Take for example

let system = function(){ return ‘process’};

console.log(system()); // process

So far you have learned how values are represented in javascript, and you must have seen some differences in the way you have pictured these values to be from the way they actually are in javascript mental model. Let’s now see variable and the link between values and variables.

What is a variable?

Variable is a pointer that points to a value. You can think of it as a rope tied to a value.

Variables are not values, rather they point to a value and as such, values live outside of them.

Now this perhaps contradict your default mental picture of variable as a container that store a value.

Note: Variable can only point to a value but not point to other variables.

Values and Variables Contradictions

As you’ve learned above, that primitive values are immutable - immutable is just a fancy greek word that means unchangeable.

let pet = ‘lion’;

pet = ‘the dog’;

console.log(pet); // ‘the dog’ 

// in this example you may think that we are contradicting string immobility by adding ‘the’. Immutability doesn’t play a role here.

Assigning a Value to a variable

You’ve learned earlier that a variable is like a rope that points to a value, this doesn’t mean different variables cannot point to the same value. you can point a variable x to 5, and you can also say you assign/set the value 5 to a variable x.

Let ’s look at some example.

let x = 5;

//you can also point the same variable x to another value 4.

x = 4;  

// what we just did is to instruct javascript that the variable x at the left hand side that we earlier point to the value 5 at the right hand side should now point to  a new value 4 at the right hand side instead of 5.

Rules of Assignment

The assignment operator has two rules that governed it usage.

  1. The left hand side of the assignment operator must be a “wire” such as the variable x in the example above. The left side can’t be a value.

Take a look at these examples.

let 50 = “fifty cent” 
console.log(50); // this will throw an error

let “money” = “happiness” 
console.log("money") // this will also throw an error.
  1. The right side of the assignment operator must be an expression. An expression will always result to a value. Expression can be something like 8, “eight” or even a complete thing like
let total = 34 + 6; 
 console.log(total);
// this is a question to JavaScript, now the variable wire “total will point to the sum value which is 40.

Reading a value of a variable

Let's say you want to log the value of this line of code;

let count = 15;

console.log(count); // 15

Contextually you will say you pass the variable ‘count’ into the log function. But in JavaScript you can’t really pass a variable into a function. We you actually did was pass the current value of the variable into the log function.

In javascript, a variable name can serve as expression. Like the ‘count’ is an expression, now, you are asking javascript, “what is the current value of ‘count’? To provide answer, javascript will trace the count wire to the value it points to to give us 15. This ‘count’ expression can give you a different value at different time.

Let’ take a look at another example

let x = 5;
y = x;

console.log(y) // 5

Here, x and y are variables, and both are pointing to the same primitive value 5. In your mind you may think y points to x, but rather y points to the value that x points to. Which can also be writing as

let x = 5;
y = 5;

console.log(y); // 5

Here, don’t think that 5 is now two, JavaScript see both 5 as the same single 5 that two variables x and y point to. This is why we said variables cannot point to other variables.

Take away

  1. Primitive Values are immutable, they cannot be created, destroy, or changed. They are already in existence and we can only point to them. For example, string is a primitive value, so we can’t set a property on it, whereas array is non primitive value, so we can set a property on it.

  2. Variables are not values, each variable points to a particular value, we can change which value a variable points to by using the assignment operator.

  3. Variables are like pointer say ‘rope’ rope is not a concept in javascript but it helps us understand variables point to values. When we do an assignment , there is always a pointed “rope” on the left that tied/point to an expression on the right, and the expression result to a value.

  4. The answer to typeof() function depends on which value the variable was pointing to when we checked the type.

Conclusion

In this article, we have examined the kind of mental model that you deployed while writing your first line of code and we have demystify the right mental model from the one you might have inherited from the first book you read or the tutorial video you saw, which might have been a big part of your thought process while writing your own code. We conclude on the big picture of how javascript values and variables work and how the understanding of the correct mental model can enable you to easily debug your code, or identify error in someone else’s code with clear confidence, because you are not guessing, this mental model is what makes you go straight to the point of error in any piece of code without thinking too deep as if you have the big picture of every nook and cranny of the code before your eye.

Wow! I am glad you read to the end, I hope you’ve learned something useful from this article. If you like what you’ve just read, you could share it with your friends, leave a comment or react on this article by tapping on every emoji on this page.

Before you go, let’s connect on

Twitter

LinkedIn