Variables & Functions in Javascript (JS)

Destry Gustin
8 min readDec 18, 2020

--

I’ve spent the last 2–3 months learning how to teach. You can say that I’ve spent most of my life working with people and helping to educate them. I have been a lead developer, development manager, product manager, company founder, and later a mentor to several startups. None of those experiences prepared me to teach a class of 40 great individuals how Javascript treats variables, functions, and works within a browser.

THIS. IS. HARD! — not the teaching, the learning. Javascript is one of the friendliest languages for a developer; when you know how to develop. Did I correctly use the semi-colon? (that’s hard too).

We’ve spent about 25 hours in lecture/lab over the last two weeks working on Javascript. In that time these individuals have learned a variety of elements related to syntax, variables, functions, arrays, objects, working within a DOM, and Web APIs that the browser provides. (See I told you it is hard!).

In hopes this will help them and others, I’m going to summarize and provide examples to jump start/refresh the fundamental concepts of Javascript. (This is not theory from a text-book, this is a real world example of what you need to know).

Let’s start with why we use Javascript:

  1. It’s fast to write
  2. It’s performant (like really performant) and flexible
  3. It’s the single language that works throughout a full technology stack (Browser + Server + Mobile)
  4. It’s widely supported in the developer community with many, many, many improvements and libraries coming out that are built upon it.

Now for some of the foundations…

Because it’s Christmas season, I just finished making cookies, and someone recommended it as an example, we’re going to bake some cookies throughout this example.

Variable
A variable is a reference to a place in memory.

The long (and not so short explanation)

All computer programs run by storing values (like numbers and strings) in memory. We’ll use the memory type called RAM for this example.

RAM is like a hoarder, it’ll collect all kinds of values (like numbers and strings) and it starts collecting so many variables that it looses track of where that value was.

In the digram below, RAM is the memory that’s storing the recipe ingredients for our cookies. Normally, we think of a recipe as a nice list such as

  • 2 cups of flour
  • 1 cup of sugar
  • 1/2 tablespoon of baking soda
  • Lots of Butter
  • Even More Chocolate Chips

The RAM isn’t very organized (remember it’s a hoarder). So it puts that nice organized list in random places.

This doesn’t look so bad, the ingredients are there.

To make things worse, RAM also stores info from every program running on your computer so you end up with a bunch of other things in memory like names and numbers.

Everything is in RAM and it has completely lost track of my recipe ingredients

In order to help the RAM keep track of things, we as programmers volunteered to keep track of where every thing is kept in RAM. When we tell the RAM that we want it to store our list of ingredients, it returns the location of each ingredient in a format like 0x1021, 0x407, 0x4021, etc.

Using our example:

0x1021 holds the first item in the recipe = 2 cups of flour

0x407 holds the second = 1 cup of sugar

Because it’s really hard to remember what 0x1021 and 0x407 hold, we are going to create a variable that points to that specific location in memory.

For example:

Instead of saying 0x1021 = 2 cups of flour, I will make a variable named firstIngredient and assign it the value 2 cups of flour.

Instead of trying to remember that each one of the variables is in a location like 0x407, 0x1021, etc. I continue to make variables to hold each ingredient. and I name each variable something that indicates what it’s storing.

Variable Types

A variable type is a built in data structure

Javascript has 6 variable types (aka data structures), I’m going to talk about the 4 that are primarily used. If you want to dive into it more, visit the MDN website.

Boolean: A boolean variable is TRUE or FALSE. We use this variable type to compare values (more on this to come).

var myTrueBoolean = true;
var myFalseBoolean = false;

Number: A number variable type is any number including those that include decimals and negative numbers. (Technically, there’s more to a number but it’s beyond the scope of this article, if you want to know more go to MDN).

var myNumber = 1;
var myDecimalNumber = 6.57
var myNegativeNumber = -120;

String: A string is a collection of individual characters in the alphabet, special characters, and numbers. We designate a variable as a string by using “ or ‘.

var myFristString = "This is a string";
var mySecondString = 'This is also a string';
var myStringIsNotANumber = "1234";

Because I used “ around 1234, I am specifically and intentionally setting the variable myStringIsNotANumber to a string variable type with the value 1234. This means that it is not a number variable type but instead it is a string variable type.

Undefined: An undefined variable type means that I am trying to reference a location in memory that does not have a value.

var myVar;  

When you declare a variable and do not assign a value to it (as in the example above), you’re telling the RAM that you’re going to put a value in that location. If you do not assign a value, then it will be undefined.

Declaring & Using Variable Types

Remember that I said writing Javascript is fast? If not, scroll way up (but do it fastly — yep I just used a fictitious word).

One of the reasons writing Javascript is fast is because you do not have to declare a variable type.

In most languages, you have to explicitly set a variable to be a type like String, Int (a number without a decimal), Float (a number with a decimal), etc. In those languages, you are not allowed to change the type of variable, so you end up creating lots of variables.When a language requires you to declare a variable type, that language is called a strongly typed language.

Javascript is called a loosely typed language because it does not require the programmer to declare what type of variable it is. This has positives and negatives associated with it. Mostly it’s that we can unintentionally assign a variable value to something we don’t intend to.

For example, it’s common to assign a variable the value of a string when you meant to assign a number.

var myNumber = "123";

Also, you encounter challenges where you mean to add a number to another number but the one of them is a string. When this happens, you would expect that the two numbers sum. Instead you end up with a string that has the two values concatenated.

var myNumber = "123";
var anotherNumber = 234;
myNumber + anotherNumber will create a string "123234"

To ensure that we don’t do this, we will use a built in function to convert a string to a number.

var myNumber = parseInt("123");  // sets myNumber = 123
var anotherNumber = 234;
myNumber + anotherNumber will sum the numbers to result in 357

Breath, stretch, go take a break (please come back)

Functions

A function is like a machine that has an input and an output.

Back to baking cookies…

When you bake cookies, you do the following tasks:

  • Combine ingredients
  • Scoop ingredients onto a baking sheet
  • Bake in an oven
  • Eat them for dinner (true story)

Each one of these tasks are functions that occur to make a cookie. If we had an assembly line to make cookies, we could have one machine that combines ingredients, one machine to put the combined ingredients onto baking sheets, one machine (an oven) that bakes the cookies, and a bunch of happy workers that eat the cookies. — Sorry machines, no cookies for you.

We write a function using special syntax that indicates you are declaring a function and assign it a name. Believe it or not, this function actually gets stored in RAM (like a variable does), so we name it to keep track of where the hoarder put it.

function combineIngredients() = {
//do some stuff to combine the ingredients
}

Parameters

Parameters are inputs to a function

Because a function has inputs and outputs (like ingredients and cookie batter). We tell functions what those inputs are by declaring parameters. Parameters are really just variables (or more specifically, the name of a place in memory like 0x407).

function combineIngredients(ingredient1, ingredient2, ingredient3){
// the parameters in this function are ingredient1, ingredient2,
// and ingredient 3
}

When we pass in parameters to a function, we are telling the function to use the value in the memory location (0x407, 0x1021, 0x3587).

For example, we declared some variables earlier firstIngredient, secondIngredient, thirdIngredient, etc… we can now pass those variables into the function so that the machine can combine them.

combineIngredients(firstIngredient, secondIngredient, thirdIngredient);

When I call the function combineIngredients and pass in the variable (aka the memory location), that function will use the values that are stored in memory at that specific location.

Looking at the function in relation to the memory, it would be something like this:function combineIngredients( value in memory location 1, value in memory location 2, value in memory location 3){  combine the ingredient in memory location 1 with the
ingredient in memory location 2 and the
ingredient in memory location 3
}

Putting it all together…

Writing a function that actually combines ingredients and outputs something would look like this

function combineIngredients(ingredient1, ingredient2, ingredient3){
var batter = ingredient1 + ingredient2 + ingredient3;

return batter;
}

When I call the function using the variables we defined earlier using

combineIngredients(firstIngredient, secondIngredient, thirdIngredient);

The function performs the action to combine the ingredients that are stored in memory as we defined early.

combine the 2 cups of flour with the   <-- firstIngredient
1 cup of sugar and the <-- secondIngredient
half of tbsp of baking soda <-- thirdIngredient

The way the function does this, is by creating a new variable that is specific to the function and then executing the operations within the function.

var ingredient1 = firstIngredient;
var ingredient2 = secondIngredient;
var ingredient3 = thirdIngredient;
//do something to combine the ingredients such as
var batter = ingredient1 + ingredient2 + ingredient3;

Returning values from functions

Often times we want to return a value from a function (i.e. the output of the machine) so that we can use that value later.
** Note I am saying value not variable **

We do this by using the keyword return

return batter;  // returns the value that is in the memory location that the variable batter refers to - it is not returning the memory location

putting this all together, the function and execution of the function would be updated to

function combineIngredients(ingredient1, ingredient2, ingredient3){
var batter = ingredient1 + ingredient2 + ingredient3;

return batter;
}
var chocolateCookieBatter = combineIngredients(firstIngredient, secondIngredient, thirdIngredient);

Now that I have a variable defined that assigns the value of combinedIngredients, I can use that in a later function.

function combineIngredients(ingredient1, ingredient2, ingredient3){
var batter = ingredient1 + ingredient2 + ingredient3;

return batter;
}
function scoopBatter = function(theBatter){
// put batter on a tray
return tray;
}
function bakeCookies = function(aCookieTray){
//put cookies in oven
//remove cookies from oven
// cookies are now cooked, lets return them return aCookieTray;
}
var chocolateCookieBatter = combineIngredients(firstIngredient, secondIngredient, thirdIngredient);var cookieTray = scoopBatter(chocolateCookieBatter);cookieTray = bakeCookies(cookieTray); // i used the same variable cookieTray but updated it to the baked cookies

Breath, stretch, go take a break (or just listen to a solid track)

Arrays

Objects

Web APIs

--

--