Collections
Working with Arrays and Objects
Arrays
A collection of things in sequence
const myArray = ["JavaScript", 100, null];Anything can go into an array
const myArray = [
"JavaScript",
100,
null,
undefined,
{ foo: "bar" },
function myFunction() {},
myVariable,
[1, 3, 5]
];string
number
object
function
variables
another array
Index
the position in an array, starting with 0
const myArray = ["JavaScript", "Python", "Java"];
0
1
2
Accessing
a value in an array
const languages = ["JavaScript", "Python", "Java"];
console.log(language[0]); // "JavaScript"
console.log(language[1]); // "Python"
console.log(language[2]); // "Java"const item = ["T-Shirt", "yellow", "M"];
const item = item[0]; // "T-Shirt"
let color = item[1]); // "yellow"
let size = item[2]; // "M"Unpacking values from an array with
Destructuring
const myArray = ["JavaScript", 100, null];
// Without destructuring
let language = myArray[0];
let num = myArray[1];
console.log(language); // JavaScript
console.log(num); // 100const myArray = ["JavaScript", 100, null];
// Destructuring
let [ language, num ] = myArray;
console.log(language); // JavaScript
console.log(num); // 100Without destructuring
With destructuring
Gets the position of an item in an array
array.indexOf()
const skills = ["JavaScript", "React", "CSS"];
console.log(skills.indexOf("React")); // 1const skills = ["JavaScript", "CSS", "HTML"];
const position = skills.indexOf("React"); // -1
if (position > -1) {
// This does not print to the screen
console.log("You do not know React!");
}
If a value is not found, then indexOf returns -1
Determing if an array contains a value
Array.includes()
const winningLotteryNums = [5367, 1249, 3468, 1134];
const isWinner = winningLotteryNums.includes(1249);
console.log(isWinner); // true
console.log(
winningLotteryNums.includes(7790)
); // false
Breaking up strings into arrays
string.split(splitter);
NOTE: if you want to split on every character, the splitter should be an empty string e.g. string.split("");
const skillsString = "JavaScript,React,CSS";
const newSkillsArray = skillsString.split(",");
console.log(newSkillsArray);
// [ "JavaScript", "React", "CSS" ];
Combing array values into a string
array.join(separator);
const skillsArray = ["JavaScript", "React", "CSS"];
const newSkillsString = skillsArray.join(", ");
console.log(newSkillsString);
// "JavaScript, React, CSS";
Changing
a value in an array
let languages = ["JavaScript", "Python", "Java"];
languages[1] = "C++";
console.log(languages);
// ["JavaScript", "C++", "Java"]Adding a value to the end of an array with
array.push()
let myArray = ["JavaScript", 100, null];
myArray.push("Push it!");
console.log(myArray);
// ["JavaScript", 100, null, "Push it!"]
Copying and combing arrays with the
Spread Operator
const statuses = [ "danger", "success" ];
const newStatuses = [...statuses, "warning" ];
console.log(newStatuses);
// [ "danger", "success", "warning" ];
Sorting items in an array
array.sort();
const skills = ["JavaScript", "React", "CSS"];
skills.sort();
console.log(skills);
// ["CSS", "JavaScript", "React"]See how to perform custom sorts with a comparison function:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Getting the length of an array
Array.length()
const languages = ["JavaScript", "Python", "CSS"];
console.log( languages.length ); // 3While Loop
Runs a block of code a specified number of times
let counter = 0;while (counter < 10) {
// This below says "Hello World" 10 times
console.log("Hello World"); counter++; // OR counter = counter + 1;
}Step 1 Create a counter
Step 2 Create a condition of when to stop
What is inside of the { } repeats
Step 3 Update the counter
Functions
reusable blocks of code
Functions are resuable blocks of code that we can create when we need to do something more than once.


You have been using functions all along. Methods, such as the log in console.log, are functions.
console.log("Hello World!");function
Arrow Syntax
Arrow syntax is a newer way of creating functions. On the Internet, you may find functions start with the word function. Avoid declaring functions with the word function, because it is bug prone. (We will explain why in detail later.)
const functionName = () => {};The anatomy of a function declaration
(arrow syntax)
const greet = () => {
console.log("Hello World");
};function name
The code you write inside { } is the reusable block of code that will be executed.
function identifier
const greet = () => {
console.log("Hello World");
};
greet(); // Hello World
greet(); // Hello World
Functions are in standby until you call or invoke them. You can invoke a function as many times as you need to.
Declaring a function (creating a reusable block of code)
Invoking or calling on a function
(executes a block of code)
You can think of a function like a factory
INPUT
OUTPUT
How can I make this block of code reusable for every person's name?
const greet = () => {
console.log("Hello Barbara Walters");
// Hello Barbara Walters
};
greet();
INPUT
OUTPUT
Input what should be different each time.
Inputs
const greet = (firstName, lastName) => {
console.log("Hello", firstName, lastName);
};
greet("Barbara", "Walters"); // Hello Barbara Walters
parameters:
the inputs
arguments:
variables that represent inputs in a function
Your Turn!
- Create a function that has two or more parameters (inputs)
- Use the parameters inside of the function in some way
- Invoke the function by passing arguments (inputs)
What will the parameters be if you don't pass in any arguments?
const displayError = (status, message) => {
console.log(status);
console.log(message);
};
displayError();
const displayError = (status, message) => {
console.log(status);
console.log(message);
};
displayError();
Default Parameters
const displayError = (status = "error", message = "Oops! Something went wrong.") => {
console.log(status); // warning
console.log(message); // Oops! Something went wrong.
};
displayError("warning");
const multiplyTen = (num) => {
console.log(10 * num);
};
let product = multiplyTen(2);
let sum = product + 5;
console.log(sum); // What is this?
I want to use the result of multiplyTen here to calculate the sum. How can I do that?
const multiplyTen = (num) => {
console.log(10 * num);
};
let product = multiplyTen(2);
let sum = product + 5;
console.log(sum); // NaN
INPUT
OUTPUT
Output (and usually store in a variable) what you need to remember for what comes next.
Output
Return Value
const multiplyTen = (num) => {
return 10 * num;
};const multiplyTen = (num) => {
return 10 * num;
};
console.log( multiplyTen(3) ); // 30
// Rembering by storing in a variable
const myNewNumber = multiplyTen(4);
console.log(myNewNumber); // 40
Return values can be anything.
const greet = (firstName, lastName) => {
return `Hello ${firstName} ${lastName}`;
};Strings
const isPositiveNumber = (num) => {
return num > 0;
};Booleans
const add = (a, b) => {
return a + b;
};Numbers
const greetLater = () => {
return () => {
console.log("Hello");
};
};Another function
Your Turn!
- Create a function that returns a value
- Invoke the function and store the results of the function inside of a constant. E.g. const myConstant = myFunction(/* ... */);
Your Turn
What will this be ?
const greet = () => {
console.log("Hello World");
};
const greeting = greet();
console.log(greeting); // What is this?
const greet = () => {
console.log("Hello World");
};
const greeting = greet();
console.log(greeting); // undefined
A function returns undefined when there isn't a return statement.
const myFunction = () => {
console.log("I will execute"); // I will execute
return;
console.log("But not me");
};
myFunction();
When a return statement is reached, the execution of the current function stops.
const displayCost = (cost, currency) => {
if (currency) {
return currency + cost.toFixed(2); // Execution stops if currency
}
return cost.toFixed(2);
};
console.log( displayCost(4.30, "$") ); // $4.30
console.log( displayCost(4.30) ); // 4.30
Note that there are many ways to declare a function. We will revisit some of these in detail later.
function greet(){
// code here
}let greet = () => { // or var
// code here
};window.setTimeout( () => {
// () => above is anonymous
// code here
}, 500);Functional Declaration
Anonymous Function:
Variable Declaration
Anonymous Function:
As an Argument
( () => {
// code here
})();Immediately Invoked Function Expression (IIFE)
Objects and Equality
Objects
A collection of things with key and value pairs
key
value
const myObject = { name: "John Adams" };
(like a label)
const ingredients = ["Beef", "Potatoes", "Carrots"];Arrays
Each item belongs to a list of things (that usually have something in common)
const recipe = {
title: "Beef stew",
ingredients: ["Beef", "Potatoes", "Carrots"],
rating: 4.0
};Object Literals
A list of different characteristics that describe a thing
vs.
Anything can go into an object.
string
number
another object
function
variables
arrays
const myObject = {
language: "JavaScript",
myAge: 100,
"money in bank account": null,
"#howIAmFeeling": undefined,
luckyNumbers: [1, 2, 3],
doSomething: () => {},
referenceSomething: myVariable,
name: { first: "John", last: 'Adams' }
};Unlike arrays, order does not matter with objects.
let item = {
name: "chocolate syrup",
name: "chocolate sauce",
cost: 4.95
};
console.log(item); // What will this be?
let item = {
name: "chocolate syrup",
name: "chocolate sauce",
cost: 4.95
};
console.log(item);
/**
* {
* name: "chocolate sauce",
* cost: 4.95
* }
*/
Object keys must be unique.
| Arrays | Objects Literals |
|---|---|
| Each item belongs to a list of things. (Usually, the things have something in common.) | A list of different properties (characteristics) that describe a thing. |
| Items in sequence | Key value pair |
| Order matters and is gaurenteed. | Order does not matter and is not gaurenteed. |
| Items can occur more than once. | Keys must be unique. Values do not have to be unique. |
Assigning Values
with constants and variables
const name = "T-Shirt";
const size = "M";
const item = {
name: name,
size: size
};
console.log(item);
// { name: "T-Shirt", size: "M" }
Assigning Values
with constants and variables
const name = "T-Shirt";
const size = "M";
const item = {
name,
size
};
console.log(item);
// { name: "T-Shirt", size: "M" }
This will only work if the key has the same name as the variable
Object keys are strings
const myObject = {
1: "12345",
true: "false",
undefined: "this is crazy"
};
console.log(Object.keys(myObject));
// ["1", "true", "undefined"]
const myObject = {
language: "JavaScript",
myAge: 100,
"money in bank account": null,
"#howIAmFeeling": undefined,
luckyNumbers: [1, 2, 3],
doSomething: function() {},
referenceSomething: myVariable,
name: { first: "John", last: 'Adams' }
};Note that you need to put " " around keys when the key has spaces or special characters.
"money in bank account": null,
"#howIAmFeeling": undefined,Method 1 - Dot Syntax
Accessing a Value
const person = {
firstName: "John",
lastName: "Adams"
};Method 2 - Bracket Syntax
console.log( person.firstName ); // "John"
console.log( person["firstName"] ); // "John"
With bracket syntax, you can access values with constants and variables.
const person = {
firstName: "John",
lastName: "Adams"
};
const typeOfName = "firstName";
console.log(person[ typeOfName ]);
// "John"
With bracket syntax, you can access values with the result of a function or expression.
const person = {
firstName: "John",
lastName: "Adams"
};
const type = "first";
console.log(person[ type + "Name" ]);
// "John"
Adding a New Property
let person = {
firstName: "John",
lastName: "Adams"
};
person.title = "Mr.";
// or
person["title"] = "Mr.";
console.log(person);
// { firstName: "John", lastName: "Adams", title: "Mr." }
Copying objects with the
Spread Operator
const originalFlight = {
airline: "United",
departure: "Albany",
destination: "Chicago"
};
const newFlight = { ...originalFlight, airline: "Delta", checkedLuggage: 0 };
console.log(newFlight);
/**
* {
* airline: "Delta",
* departure: "Albany",
* destination: "Chicago",
* checkedLuggage: 0
* }
*/
Week 6
By Jamal Taylor
Week 6
- 219