Functions and Data Structures

Making your code structured and reusable.

Alec Ortega

Front End Engineer

HubSpot

alecortega

Follow along at:

slides.com/alecortega/data-structures/live

Takeaways:

How do we organize data?

How do we manipulate data?

How do we make our code re-usable?

Functions

Functional Programming

Object-oriented Programming

What is a function?

Functions are just blocks of code that you can reuse at any time while your program is running.

Imagine someone created a machine with a start button and every time you pushed the start button it would give you a nice compliment.

giveCompliment

"You look nice today"

()

Whatever we put into the machine can be reused at any time by pressing the start button.

var giveCompliment = function () {
  
};
var giveCompliment = function () {
  console.log('You look nice today!');
};
var giveCompliment = function () {
  console.log('You look nice today!');
};

giveCompliment();
var giveCompliment = function () {
  console.log('You look nice today!');
};

giveCompliment();

I want to create a re-usable machine...

Here's the button to start the machine...

Here's what I want the machine to do...

I want to create a variable named giveCompliment and assign it a reference to the machine.

I want to get the machine that the giveCompliment variable references and press the start button.

var giveCompliment = function () {
  console.log('You look nice today!');
};

giveCompliment();
function giveCompliment () {
  console.log('You look nice today!');
};

giveCompliment();

Anonymous function

Named function

We'll go over how these two differ in a bit...

I want a machine where I can put a name in and when I push the start button it will say "Hello Alec!" instead of just "Hello!"

greetByName

"Hello Alec!"

()

greetByName

"Hello!"

()

"Alec"

"Hello Alec!"

How do we allow the machine to do things dynamically based on what we pass into it?

greetByName

()

"Hello Alec!"

(name)

"Hello" + name + "!"

Instead of thinking of it like a machine that does the same thing every time, we can think of it like a template, blue print, or recipe that does something based on what we give it.

var greet = function () {
  console.log('Hello Alec!');
};

greet();
var greet = function (name) {
  console.log('Hello' + name + '!');
};

greet('Alec');
var greet = function (name) {
  console.log('Hello' + name + '!');
};

greet('Alec');

You can think of this like a placeholder for whatever gets passed in when you push the start button.

We call these placeholders "parameters".

What we pass into the function are called "arguments"

var greet = function (name) {
  console.log('Hello' + name + '!');
};

greet('Alec');

What ever we pass into the function is what we need to be different every time it's run. 

What stays the same is what's in between the brackets.

var greet = function (name, age) {
  // ...
};

We define any number of parameters for the function by separating them with a comma.

Remember this?

console.log('one');

console.log('two');

console.log('three');

var greet = function () {
  console.log('Hello!');
};

console.log('one');

console.log('two'); 

greet();

console.log('three');

greet();

Work with the person next to you to try and draw out what the flow of this program looks like:

console.log('one');

console.log('two');

console.log('three');

console.log('Hello!');

greet()

greet()

Most of the time we don't want to just have our functions do something, we want them to give us something back.

var add = function (numberOne, numberTwo) {
  return numberOne + numberTwo;
};
var add = function (numberOne, numberTwo) {
  return numberOne + numberTwo;
};

console.log(add(1, 2));

We call functions that don't do anything other than return values "pure" functions. Meaning they have no side effects. The return will always be the same given the same input.

var add = function (numberOne, numberTwo) {
  return numberOne + numberTwo;
};

console.log(add(1, 2));
var add = function (1, 2) {
  return numberOne + numberTwo;
};

console.log(add(1, 2));
var add = function (1, 2) {
  return 1 + 2;
};

console.log(add(1, 2));
var add = function (1, 2) {
  return 1 + 2;
};

console.log(3);
var add = function (numberOne, numberTwo) {
  return numberOne + numberTwo;
};

console.log(add(1, 2));

You'll also notice that the function name clearly explains what it does. The function only serves a single purpose and the name reflects that. This is known as the single responsibility principle. You only want your functions to do one thing.

var add = function (numberOne, numberTwo) {
  numberOne + numberTwo;
};

console.log(add(1, 2));

What will this log?

=> undefined
var add = function (numberOne, numberTwo) {
  numberOne + numberTwo;
};

console.log(add(1, 2));

You see it like this:

var add = function (numberOne, numberTwo) {
  numberOne + numberTwo;
  return undefined;
};

console.log(add(1, 2));

The computer sees it like this:

When you don't specify a return for a function, the interpreter will always return undefined. 

Check-in

Questions?

Function Scope

Function scope in JavaScript is a lot like citizenship. I am a citizen of Boston, of Massachusetts, and the United States.

Someone from California has access to the same benefits of living in the United States as I do since we are both citizens.

 

But that doesn't mean that I have access to the benefits of living in California and vise versa. 

var greeting = 'Hello!';
var greeting = 'Hello!';

var greet = function () {
  console.log(greeting);
};

greet();

What will this log?

=> "Hello!"
var greeting = 'Hello!';

var greet = function () {
  console.log(greeting);
};

greet();
var greet = function () {
  var greeting = 'Hello!';
  console.log(greeting);
};

greet();

What about this?

=> "Hello!"
var greet = function () {
  var greeting = 'Hello!';
  console.log(greeting);
};

greet();
var greet = function () {
  var greeting = 'Hello!';
};

greet();
console.log(greeting);

And what about this?

=> undefined

Every variable within a function cannot be accessed or is not "visible" outside of that function.

The only thing that creates a new scope, is a function. Not if statements, not an object.

var human = 'hello';
var dog = 'woof';
var cow = 'moo';

function greet () {
  console.log(human);
};

function bark () {
  console.log(dog);
};

function moo () {
  console.log(cow);
};

Variables that aren't contained within the scope of any function are considered within the...

Global Scope

Workshop One

Work in groups of 3-4

Write a function "createAdder" that takes a number and returns a function. The returned function should take a number and when called add that number to the one specified in the call to "createAdder"

var addToThree = createAdder(3);

console.log(addToThree(4));

=> 7;
var createAdder = function (numberToStayConstant) {
  return function (numberToAdd) {
    return numberToStayConstant + numberToAdd;
  };
}

Higher Order Functions

Functions that operate on other functions, either by taking them as arguments or by returning them are called...

var createAdder = function (numberToStayConstant) {
  return function (numberToAdd) {
    return numberToStayConstant + numberToAdd;
  };
}

When you break down a function that takes multiple arguments into a series of functions that take part of the arguments it's called...

Currying

I don't and your future employers won't expect you to remember 100% of this off the bat.

 

My hope is that this helps give you context and help you recognize patterns so that you know what to Google for later.

Google:

What is "hoisting" in JavaScript? How does it affect these two functions differently?

var giveCompliment = function () {
  console.log('You look nice today!');
};

giveCompliment();
function giveCompliment () {
  console.log('You look nice today!');
};

giveCompliment();
var greet = function (isNight) {
  var nightGreeting = 'good night!';

  if(isNight) {
    console.log(nightGreeting);
  }

  var dayGreeting = 'good day!';

  console.log(dayGreeting);
}
var greet = function (isNight) {
  var nightGreeting;
  var dayGreeting;

  nightGreeting = 'good night!';

  if(isNight) {
    console.log(nightGreeting);
  }

  dayGreeting = 'good day!';

  console.log(dayGreeting);
}

Check-in

Questions?

10 min break

Data Structures

Data Creation

Arrays

Let's first think about how we organize things in the real world.

If you go to the grocery store, how would you organize what you need to get?

Using only what we learned in the last class how would we organize this?

itemOne

itemTwo

milk

bread

Variable

Value

In the real world we use lists to organize these kinds of things.

 

Using only what we have now, it would be like using a new piece of paper for every item that we need to buy

var itemOne = 'milk';

var itemTwo = 'bread';
var items = ['milk', 'bread'];

Arrays are created using "[" and "]"

var items = [10, 'word', true, null];

You can put anything into an array, it's really just a list of different things.

var itemOne = 'milk';

var itemTwo = 'bread';

How did we access the values that these variables referenced before?

var itemOne = 'milk';

var itemTwo = 'bread';

console.log(itemOne);
var items = ['milk', 'bread'];

So how do we access these ones?

Meaning how do I get a specific item from this array?

var items = ['milk', 'bread'];

Instead of asking for a specific value we ask the computer "What is the second value in the array?"

var items = ['milk', 'bread'];
var items = ['milk', 'bread'];

console.log(items);
var items = ['milk', 'bread'];

console.log(items);

console.log(items[1])

If we're asking for the second item in the array, why is this number "1" and not "2"?

var items = ['milk', 'bread'];

Computer don't start counting at "1" they start counting at "0".

0

1

Index

What index is the value "pear" at?

var fruits = ['grapes', 'orange', 'lemon', 'pear'];

Objects

Say you're at the grocery store again and you need to know how many of each item you actually want to buy. Using only what we know how would we do this?

var itemOneName = 'milk';

var itemOneQuantity = 1;

var itemTwoName = 'bread';

var itemTwoQuantity = 2;
var itemNames = ['milk', 'bread'];

var itemQuantities = [1, 2];
var items = {
  milk: 1,
  bread: 2
};
var items = {
  milk: 1,
  bread: 2
};

Objects allow us to set keys that reference values in a single structure that a single variable can reference.

var items = {
  milk: 1,
  bread: 2
};

So how do we access values in objects?

var items = {
  milk: 1,
  bread: 2
};

console.log(items.milk);

We use a "." followed by the name of the key that we created to get the value that the key references.

var items = {
  milk: 1,
  bread: 2
};

console.log(items['milk']);

We can also use the "[]" syntax like we did with arrays and pass in the key as a string.

var items = {
  'milk': 1,
  'bread': 2
};

console.log(items['milk']);

Even though you don't have quotes around the keys when creating the object the interpreter will look at it as if you did which is why it will match the string.

var items = {
  'milk': 1,
  'tasty bread': 2
};

What if I asked you to get the value that the second key in this object references?

var item = {
  'milk': 1,
  'tasty bread': 2
};

console.log(items.tasty bread)

Is this valid JavaScript? How will the interpreter read this?

Use "[]" syntax whenever the keys aren't going to be valid JavaScript when using "." notation. I.e. whenever they might be weird strings.

var mostImportantItem = 'bread';

var items = {
  'milk': 1,
  'bread': 2
};

console.log(items[mostImportantItem]);

For both arrays and objects, whatever you put in between "[]" will be evaluated. This allows you to get values dynamically. Something that you cannot do using the dot syntax.

Use "." notation when you 100% know the name of the key that you're trying to access. 

Use "[]" notation when the keys might be weird strings or when you want to get values dynamically.

Quick introduction to a new operator.

typeof 1

"typeof" will return the value's data type as a string.

So what will this return?

typeof 1

=> "number"
typeof "milk"

What about this one?

typeof "milk"

=> "string"
typeof true

What about this one?

typeof true

=> "boolean"
typeof {}

What about this one?

typeof {}

=> "object"
typeof []

What about this one?

typeof []

=> "object"

itemOne

itemTwo

milk

bread

Variable

Value

items

Object

Variable

Objects

1

2

"bread"

"milk"

Objects are essentially just a bunch of named references that point to values.

var items = {
  fruits: {
    apples: 5
  }
  milk: 1
};

Can someone draw what this would look like?

So why are arrays typeof "object"?

itemNames

Array

Variable

Arrays

"bread"

"milk"

1

0

Arrays are objects, but the names of the references are indices (Number) not strings. 

var itemNames = ['milk', 'bread'];

You think of Arrays like this

var itemNames = {
  0: 'milk',
  1: 'bread'
};

The computer thinks of Arrays like this

var items = {
  'milk': 1,
  'bread': 2
};

console.log(items['milk']);

Get the value where the name of the reference is...

var itemsNames = [ 'milk', 'bread'];

console.log(items[1]);

Get the value where the name of the reference is...

Check-in

Questions?

Data Manipulation

The way way we change existing values is similar to the way we read them, we just re-assign the reference to a new value.

var items = ['milk', 'bread'];

items[0] = 'apples';

console.log(items);
=> ['apples', 'bread']

We've arrived at the grocery store but we realized we forgot to put something on our list and need to add it.

var items = ['milk', 'bread'];

How do we add or remove items to this Array after we've created it?

var items = ['milk', 'bread'];

items.push('apples');

console.log(items);
var items = ['milk', 'bread'];
=> ['milk', 'bread', 'apples']
var items = ['milk', 'bread'];

items.push('apples');

console.log(items);

Where have we seen this syntax before?

What about this syntax? What is push?

We said that Arrays are actually Objects that the computer reads like this.

var itemNames = {
  0: 'milk',
  1: 'bread'
};

Under the hood, JavaScript also has a bunch of other keys that refer to functions that allow us to change that data.

var itemNames = {
  0: 'milk',
  1: 'bread',

  // Under the hood
  push: function (value) {
    // Add a value to the end of the array
  },
  pop: function () {
    // Remove a value from the end of the array
    return removedValue
  }
};
var items = ['milk', 'bread'];

// Add an item to the end of the array
items.push('apples');
// => ['milk', 'bread', 'apples']

// Remove an item from the front of the array
items.shift()
// => ['bread', 'apples']

items.length
// => 2

Arrays have a ton of methods that you can call on them and even properties like length that you can access.

What about Objects?

var items = {
  milk: 1,
  bread: 2
};

items.milk = 2;

console.log(items);
=> { milk: 2, bread: 2 };

Like Arrays, for existing keys we just re-assign the reference to a new value.

var items = {
  milk: 1,
  bread: 2
};

items.apples = 2;

console.log(items);
=> { milk: 2, bread: 2, apples: 2 };

We can also assign a reference to a value for a key that's not on the object to add it in.

var items = {
  milk: 1,
  bread: 2,
  apples: 2
};

delete items.apples;

console.log(items);
=> { milk: 2, bread: 2 };

We use the "delete" operator to remove a key and it's reference from an object.

Workshop Two

Write a function "createPerson" that takes a string and a number, and returns an Object.

The returned Object should have three keys: "name", "age", and "greet".

The "name", and "age" keys should reference values that correspond to the arguments you passed into "createPerson".

The "greet" key should reference a function that takes a string as the only argument that when called logs "Hello (argument)! My name is (name), I am (age)". 

Work in groups of 3-4

Workshop Three

Write a function called "giveCompliment". When called, the function should log a random compliment from a list of 3 compliments. "giveCompliment" should be the only global variable in the program.

Work in groups of 3-4

We did it!

Sometimes when you're just starting out you might be writing code and feel like there's a lot going on under the hood, it feels like magic, and you just know the syntax to make it not blow up.

Anyone can Google syntax.

 

The point of this class was to try and remove the feeling that there's magic happening and give you confidence into what you're writing.

Example:

console.log();

What data type is console?

What is log?

Why do we have access to console or Math if we never wrote it?

You can view these slides at:

slides.com/alecortega/data-structures

Eloquent JavaScript

Chapters 3 - 6

Homework:

Thanks!

Data Structures and Functions

By Alec Ortega

Data Structures and Functions

Making your code structured and reusable.

  • 535