JavaScript Fundamentals

Variables

David Henshaw
2 min readApr 7, 2021

Variables are sort of like boxes we can store data in. Once they are in this “box” it has a name you can reference at any time. For instance, you could store a kitchen supply, fruit, vegetables, or a ball — anything.

let kitchenSupply = "knife";
let fruit = "banana";
let vegetable = "broccoli";
let ball = "soccer";

What you store in the box doesn’t even need to be related to its name. We could even use the same names and put random data in the variables:

let kitchenSupply = true; //Boolean
let fruit = 10; //Number
let vegetable = undefined;//Undefined
let ball = ["toothpaste", "bread", "apples"]; //Object

Looking at the example above, we have different data types assigned to each variable. That’s because JavaScript allows us to assign any data type to a variable.

Data Types

There are 6 main data types in JavaScript

  • Number
  • String
  • Boolean (true and false)
  • Undefined
  • BigInt
  • Symbols

Data Structures

Structural data types include

  • Objects: store collections of data
let person = { name:"Selam", age:26, favoriteColor:"purple"}
  • Functions: a set of instructions that perform a specific action
function takeOutTrash(){
console.log("I threw out the trash!");
}

How to Interact with and Access Data

Let’s start with accessing variables. Once a variable is defined, you can use it in other expressions. For instance, our first example declared our favorite fruit. What if later, we decide that our favorite fruit is actually apples? We can redefine the assigned fruit.

let fruit = "banana";
//*Traumatic experience with banana occurs*
fruit = "apple"
// Apple is now assigned as the current fruit

Since objects store data, we need a way to extract the data out of it. There are two main ways to do this: dot notation and bracket notation.

let person = { name:"Selam", age:26, favoriteColor:"purple"}
let personName = person.name; //This variable now holds "Selam"
let age = person["age"]; //This variable now holds 26

In order for the function to complete its instructions, it must be “invoked” or executed. This also takes a different form:

//First we define the function
function takeOutTrash(){
console.log("I threw out the trash!");
}
//Then we have to invoke it:takeOutTrash(); //Prints "I threw out the trash!"

Scope

Remember when we said you could access variables at any time? Yeah, sorry about that. In JavaScript there are two types of scope, global scope and local scope. Global scope can be accessed at any time while local scope can only be accessed within the block that defined it.

For example, if we had a stuffed animal named “Dola”, nobody who lives outside our house would know what its name is. But they would know what a stuffed animal is in general. We can say that the concept of a stuffed animal is global while the name “Dola” is local to our house.

--

--