An Intro to JavaScript Variables, Objects, and Arrays

JavaScript is a delicate beast. It can be our best friend one moment and our worst enemy the next. This complicated relationship is a rollercoaster of emotions, but it is worth it for the exciting perks!
However, before we can reap those benefits we need to learn the fundamentals.
This week we’re learning the basics and on day one we covered the major components to data storage and manipulation.
Variables, Objects, and Arrays all provide us with unique ways to store data and later manipulate or invoke them. In order to be a successful JS developer, we need to know how to use all three.
That’s why this post will cover:
- Variables — What are they? Why do they matter? What’s a var, let and const?
- Objects — What are they? Why do they matter? The basics of getting started.
- Arrays — What are they? Why do they matter? The basics of getting started.
We got a lot of important material to cover, so let’s dive right in!
Variables
What are they and why do they matter? — Variables are containers we can use to store values. These values can be strings, numbers, booleans, or functions. Here’s an example of those in use:
// String Variable
var first = “First Variable;// Number Variable
let num = 2;//Boolean Variable
const bool = false;//Function Variable
const myFirstFunction = function(params){
console.log(params)
};
Notice the syntax we’re using for all these?
statement(var, let, const) + unqiue name(whatever we want it to be)+ assignment operator(=) + value(the value we want stored);
As long as we stick to these conventions, we can store almost anything in a variable.
We can use var, let or const
to initiate our variables, but there are best practices surrounding each. We'll dive deeper into those in our application section.
Variables are important because they allow us to begin assigning values to items. Right, we understand that but why is that important? Two reasons:
- It provides us with an organizational structure that helps make our code clean, organized, and readable for the next developer.
- We can use variables to store data so we can begin to manipulate it and start unleashing the powers of JavaScript.
Great now that we understand what a variable is and why we use them, let’s see how we can use them!
Using Variables: The importance of var, let and const.
Up to now, we’ve seen how to implement the basics of a variable. However, we need to talk about the differences between var, let and const
to get a true understanding of how to use variables.
Prior to ES6, developers relied on var
to declare all their variables. This was the norm and still functions today, but the introduction of let
and const
in ES6 has revolutionized the variable game.
Let’s go through each value, talk about their ability and list their pros/cons.
var
The var
declaration is the OG variable, we can use it to assign any unique variable a value. However, the usage of var
comes with some rules:
Mutability and Multiple Declaration:
A var
is mutable, meaning we can adjust the value of var
whenever we’d like. For example:
var name = "Matt";
name = "Tony";console.log(name): //Output: Tony
This flexibility is great, but can be dangerous! That’s because vars
can be overwritten. For example:
var name = "Matt";
var name = "Tony";console.log(name): //Output: Tony
This example might look the same as above, but notice how we’ve used the var
declaration again to reassign our value?
This might not seem like a big deal now but imagine we’ve written a program with thousands of lines of code and towards the end, we accidentally reuse a var
name. Our whole program will break when it recognizes the newly declared variable. Talk about a bad time!
Function Scoped:
When we use variables we want them to be associated with a certain aspect of our code. Whether that’s a function, a block, or globally we don’t want our variables leaking to other parts of our code. This can cause great confusion.
var
is functioned scoped, meaning their scope is contained to the function they’re declared in. For example:
function name(){
var first = "Matt";
}console.log(first) //Output: ReferenceError: first is not defined
We’re unable to access the variable outside of the function. This is good because we want our function variables to be unique to the functions we declare them in.
However, var
is not block scoped. Meaning if a block is invoked, using {}
the var
we declare is not limited to the block they’re defined in. This can cause a lot of confusion. Example:
var name = "Matt";
if(true){
var name = "Tony"
}console.log(name) //Ouput: Tony
Above we see our global variable reassigned in a block. This is super dangerous! Imagine if we needed our global variables to remain constant, but everytime a block appeared it got reassigned? Not ideal!
To Review:
var
is mutable - they can be assigned different values.- They can be overwritten — not great for big projects.
- They are function scoped not block — function scope = good; not being blocked scoped = dangerous!
let
When I think of let
, I picture the modern developer’s var
. It brings the flexibility associated with var
but has resolved some of the bigger issues.
Mutable and Multiple Declaration:
let
is great because its values are mutable and it will not allow us to overwrite it. Here’s are two examples, first is an overwrite error and the second is the proper way to adjust the value:
let name = "Matt";
let name = "Tony"; //Output: Error Message - Uncaught SyntaxError: Identifier 'name' has already been declared
JavaScript won’t run our code if we try to overwrite. That’s super useful if we accidentally reuse a variable name.
But what if we want to change the content of a let
variable? This syntax will allow you to do so:
let name = "Matt";
name = "Tony";console.log(name); //Output: Tony
As long as we don’t rewrite the whole variable, we can reassign the value by just targeting the unique variable name.
Block Scoped:
One of the great parts about let
is it’s block scoped. Unlike var
when declared inside a {}
it will not leak out: this included functions! For example:
let name = "Matt";if(true){
let name = "Tony";
}console.log(name); //Output: Matt
The block variable is totally ignored, and the global scope only responds to global variables. Same would happen in a function:
let name = "Matt";function test() {
let name = "Tony";
}console.log(name); //Output: Matt
Our variables are stuck to their scopes, which is exactly where we want them!
To Review:
lets
are mutable - providing us with the ability to reassign values.- Multiple declarations are not allowed - no fear of overwriting.
- Block Scoped - no variable leakage, everything is associated with their declared area.
const
Last but not least const
: the steady variable. const
allows us to assign a value to a variable and keep it constant no matter what. Meaning it is not mutable and it cannot be overwritten. For example:
const name = "Matt";const name = "Tony"; // Output: Uncaught SyntaxError: Identifier 'name' has already been declaredname = "Tony"; // Output: Uncaught TypeError: Assignment to constant variable.
Nothing is flying by the const
! Once we declare it, it’s here to stay.
In a similar vein, const
is block scoped, meaning that it is locked to its declared area. Example:
const name = "Matt";if(true){
const name = "Tony";
const nickname = "Bas";
}console.log(name) //Output: Matt
console.log(nickname) //Output: Uncaught ReferenceError: nickname is not defined
This power is great for variables we don’t want to be disturb and need to remain constant throughout our applications.
A rule of thumb I was gifted: declare your variables as const
for as long as possible. That way we don’t leave variables susceptible to mutability throughout our code. However, for those moments we will want mutability we should use let
.
To Review:
- Not mutable - they’re constants for a reason!
- Cannot be overwritten - reference above 😂.
- Block Scoped - no variable leakage, everything is associated with their declared area.
There we have it! A guide to using var, let and const
. Knowing when to use each will allow us to grow as developers and slide right into the JS norms.
Objects
What are they and why do they matter? — Objects are like variables, except we can assign more than one value to them.
To prove it here’s an example of an object, that’s populated with properties about me.
const me = {
firstName: "Matt",
lastName: "Basile",
age: 24,
friendly: true,
greeting: function(){
console.log(`Hello, my name is ${firstName} ${lastName}`
}
}
Looked at all the added information we can store! We’ve stored strings, a number, a boolean and a function all under one object.
This is the power of objects, we can tuck all this information away and access it from one object. However, at this moment you might be thinking, “That’s a lovely storage tool, but it means nothing if I can’t access it!”
And you’re absolutely right! This next section will introduce dot and bracket notation and methods to help you start accessing and manipulating our properties.
Accessing a Property - Dot and Bracket Notation
To access a property within an object we need to understand what our properties are made of. Each property is composed of a key and value pair.
In our example above our keys are firstName, lastName, age, friendly, and greeting
and our values are "Matt", "Basile", 24, true, and function(){console.log(Hello, my name is ${firstName} ${lastName}).
If we want to access our values, we need to target our keys. To do so we use dot or bracket notation.
Dot notation looks like this: me.firstName //Output: "Matt"
Bracket notation looks like this: me["firstName"] //Output: "Matt"
Both are totally acceptable and usable. Throughout our JS journey, we’ll find application for both. Bracket notation is particularly useful for when we use keys that might have space in them ie: first name: "Matt",
.
This is great! We can now start returning values and begin changing them. But wait if our values are stored in a const
shouldn’t it be impossible to change them?
This is true for our objects’ name. However, the values inside of them are mutable and frequently adjusted.
To alter a value in our object we can use the same syntax above but just use the assignment operator to change the value.
const me = {
firstName: "Matt"
}
me.firstName = “Tony"; //Reassigns the firstName value in object me. console.log(me.firstName) //Output: Tony
Super easy right? These objects are going to be awesome for us, but sometimes they can get confusing. Imagine having an object filled with 100s of properties? That can be overwhelming to locate the proper key and value.
Well, there are a few methods we can utilize to help traverse more complex objects.
Popular Methods
.entries()
: This method will return an array of all the properties keys and values! How great is that? We can now see everything in our object and find the perfect pair.
.keys()
: Like the entries method, it will return an array of all the keys, without the values. This is great if we need to recall a specific key to target in our code.
.values()
: You guessed it, it will return an array of all the values without the keys. This is great for targeting and understand what values are available to you.
Each method has a hyperlink to the MDN docs on itself. I encourage you to dig into the docs to learn more about implementing these methods and how to use them to target certain indexes.
Arrays
What are they and why do they matter?: Arrays are another way for us to store values. What makes them unique is their ability to store ordered values.
Arrays are important because they provide a new level of organization and functionality that we didn’t have with variables or objects. Compared to objects, arrays allow us to store values without needing to assign keys. And in comparison to variables, we can assign multiple values to a single array.
But how do we use them? The rest of this post will cover the basics to getting started.
How to build an array:
let names = ["Matt", "Tony", "Jim"];
The names
array above holds the values Matt, Tony, and Jim, but that’s not the only thing we can store. Like objects, we can store numbers, functions and even other arrays.
How to access an item :
let names = ["Matt", "Tony", "Jim"];names[0] // Value: Matt
names[1] // Value: Tony
names[2] // Value: Jim
Arrays have a 0 based indexing system. Meaning the first value in an array carries an index of 0. So in order to target the first value, we need to use the syntax arrayName[0]
. We’ve seen these brackets before with objects, but just know we can’t use dot notation here.
Important Methods:
Arrays become powerful when we can start adjusting the content within them. In order to that, we can use a few popular methods:
.pop()
: Removes the last item of an array, and returns it to us.
.push()
: Adds an element to the end of an array and returns the new length of array.
.shift()
: Like the inverse of .pop()
, it removes the first item of an array and returns it to us.
.unshift()
: Like the inverse of .push()
, it adds an element to the front of an array and returns the new length of the array.
.slice()
: Returns a portion of the array declare by to indexes. (Follow the link provided for a great example.)
For some more basic methods, check out the MDN Array Methods documentation I’ve included here. Also, you can find the individual pages next to each header.
As the week progresses we’ll begin to explore more powerful methods, but before we do that it’s important to grasp the basics first.
Wrap Up
I hope this was a good first step into Variables, Objects and Arrays. We’ll be seeing a lot more of them so please review and seek other resources to brush up!
If you want to discuss any of the topics covered at length feel free to message me here or find me on twitter! Happy Coding!