The JavaScript You Need: Variables, Functions and Modules
The pet adoption API in this module is written in JavaScript, and this lesson teaches the part of it you'll change, starting from the objects you already know from mongosh, then const and let, functions with return and template literals, arrow functions with filter and find, and import and export between files.
Apprentice · JavaScript · Updated
After this lesson you can
- Store values with const and let, and write a function that returns text built with a template literal
- Pick items out of a list with an arrow function and filter or find
- Share a function between files with export and import
Key takeaways
- A document you typed in mongosh is already a JavaScript object, and a dot reads one of its fields, such as pet.name.
- const names a value you won't replace, and let names one you will, such as a counter that goes up.
- A function takes values in its parentheses and hands its answer back with return. A template literal, in backticks, builds text with slots for values.
- An arrow function is a short function. Handed to filter it keeps every item it says yes to, and handed to find it gives back the first one, or undefined.
- export shares a function or a value from one file, and import brings it into another.
This module puts MongoDB behind a real app: an API for the Maple Street Pet Adoption Center, handed over finished and written in JavaScript. To change the file that keeps its pets, you'll need to read and write a little JavaScript, and you already know more of it than you think. This lesson teaches only the parts the API uses; JavaScript in Depth is the place to go much further.
The examples use the center's pets: Biscuit the dog, Mochi the cat and their friends.
You've been writing JavaScript all along
Here are the first lines of a small program about one pet. Look at the braces:
const pet = { name: "Biscuit", species: "dog", age: 3 };
console.log(pet.name);
console.log(pet.age + 1);
Biscuit
4
{ name: "Biscuit", species: "dog", age: 3 } is written exactly like a mongosh document, because mongosh is JavaScript: every document you've typed was a JavaScript object. A dot reads one field: pet.name is read "pet dot name". console.log(...) prints what's in its parentheses, one line each time.
To run it yourself, save the three lines as practice.js in your mongodb-course folder, and in VS Code's terminal type:
node practice.js
const and let: a name for a value
A name for a value is a variable, like the label on a kennel. const (short for "constant") makes a label you won't move to another value. Try pet = { name: "Pepper" }; after the first line, and Node stops with TypeError: Assignment to constant variable. That protects you from replacing something by accident.
let makes a label you can move. A counter that goes up needs it:
const pets = ["Biscuit", "Mochi"];
pets.push("Pepper");
let nextId = 3;
nextId = nextId + 1;
console.log(pets);
console.log(nextId);
[ 'Biscuit', 'Mochi', 'Pepper' ]
4
Square brackets make a list, an array, as in mongosh. push adds an item to the end. The list is still the same list, so const is fine: the label didn't move. nextId = nextId + 1 moves let's label to a new number. Use const unless you know the value will be replaced.
Functions: steps with a name
A function is like an adoption form: the same steps, filled in with a different pet each time. The values it needs go in its parentheses, and return hands its answer back:
function describe(pet) {
if (pet.status === "adopted") {
return `${pet.name} has found a home`;
}
return `${pet.name} the ${pet.species} is waiting for you`;
}
console.log(describe({ name: "Mochi", species: "cat", status: "available" }));
console.log(describe({ name: "Juniper", species: "cat", status: "adopted" }));
Mochi the cat is waiting for you
Juniper has found a home
Three new pieces:
===is read "is exactly equal to". It compares; a single=stores.if (...) { ... }runs the lines in its braces only when the comparison is true.returnends the function, so for Juniper the last line never runs.- Text in backticks (
`) is a template literal. Each${ }(read "dollar brace") is a slot: the value inside is written into the text.
Arrow functions with filter and find
An arrow function is a short way to write a function, and => is read "goes to": (pet) => pet.species === "cat" takes a pet and gives back true or false. With no braces, the value after the arrow is returned without the word return.
Arrow functions are usually handed to another function. An array's filter keeps every item yours says yes to, much like a filter in mongosh, and find gives back the first one:
const pets = [
{ id: "1", name: "Biscuit", species: "dog" },
{ id: "2", name: "Mochi", species: "cat" },
{ id: "5", name: "Juniper", species: "cat" },
];
const isCat = (pet) => pet.species === "cat";
const cats = pets.filter(isCat);
const mochi = pets.find((pet) => pet.id === "2");
console.log(cats.length);
console.log(mochi.name);
console.log(pets.find((pet) => pet.id === "9"));
2
Mochi
undefined
length is how many items a list holds. When nothing matches, find gives back undefined, JavaScript's word for "nothing here".
import and export: one file for each job
The API keeps its pets in one file and its routes in another. A file shares something by writing export in front of it. Save this as pets.js:
export const pets = [
{ id: "1", name: "Biscuit", species: "dog" },
{ id: "2", name: "Mochi", species: "cat" },
];
export function describe(pet) {
return `${pet.name} the ${pet.species}`;
}
Another file in the same folder brings them in with import, naming each one in braces. ./ means "in this folder". Save this as show.js, then run node show.js:
import { pets, describe } from "./pets.js";
const mochi = pets.find((pet) => pet.id === "2");
console.log(describe(mochi));
console.log(pets.length);
Mochi the cat
2
Each file is a module. The API's package.json says "type": "module", which tells Node its files use import and export.
Do it: write the adoption board's lines
The center's front desk shows a board with a line for every pet. Write the two functions it uses.
The input, pet, is one pet with four fields: name, species, age (a number) and status, which is "available" or "adopted". Biscuit, for example:
const biscuit = { name: "Biscuit", species: "dog", age: 3, status: "available" };
For Biscuit, boardLine(biscuit) returns exactly Biscuit (dog, 3), and isAvailable(biscuit) returns true.
Your job:
- Write
boardLine(pet). It returns the pet's name, then its species and age in parentheses:"Biscuit (dog, 3)". - When the pet's
statusis"adopted",boardLineadds: adoptedat the end:"Juniper (cat, 5): adopted". - Write
isAvailableas an arrow function stored in aconst. It takes a pet and returnstruewhen itsstatusis"available", andfalsewhen it's"adopted".
Practiced live on the lesson page: write the JavaScript right there and check it.
Check yourself
2 questions to try on the lesson page.
So what
Objects, const and let, a function that returns, an arrow function handed to filter or find, and import and export: that's nearly all the JavaScript in the pet API's data file, and you can read every line of it now.