Reference and Resources

Written by Neel Kishnani, Jason Chuen, Michael, and the teaching team

Here is a collection of some of the major syntax, elements, functions, etc. we use in this course. What is mentioned below follows best practices and our recommendations; the lecture materials may discuss alternatives.

Links point to MDN Web Docs.

Contents

HTML

General Page Structure

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    ...
  </head>
  <body>
    ...
  </body>
</html>

head Elements

<title> Page title shown in browser (tab bar, history)
<meta> (leaf) Information about the page
<link rel="stylesheet" href="..."> (leaf) Include a CSS file (see link for other things that can be linked)
<script type="module" src="..."></script> Include a JS module

Common Page Elements

<h1>, <h2>, ..., <h6> Headings (smaller number = bigger text)
<a href="..."> Link to another page
<p> Paragraph
<br> (leaf) Line break (see How Whitespace is Handled)
<img src="..."> (leaf) Include an image
<strong> Make text stand out (bold)
<em> Emphasize text (italics)
<ul> and <ol> Unordered (bulleted) and ordered (numbered) list
<li> List item (wrap each item in <ul> or <ol>)
<div> Generic block element
<span> Generic inline element

Page Regions

<header> Header of hte page, or of a section/article/region
<main> The main content of the page (e.g. the part that's not part of a nav bar or footer)
<footer> Footer of the page or a region
<nav> A collection of links/buttons/etc. for moving around the page/app
<section> A section of the page (e.g. a sidebar, block of content with a heading, etc.)
<article> A section of hte page that is more independent, e.g. a blog post, announcement, event, etc.

Elements for User Interaction

<form> Wrap a collection of controls (inputs, buttons, etc.)
<input> (leaf) Accept user input (see type)
<label> Associate a label with an input (wrap <input> or use for attribute)
<button> A clickable button. Default type is submit if inside a form

Note: Elements marked "(leaf)" don't contain children and thus should not have a closing tag.


CSS

Selectors

tag Select all <tag> elements
.class Select all elements with class class
#id Select all elements with id id
type.class Select type elements with class class
s1 s2 Select s2 if s2 is a descendant of s1
s1, s2 Select s1 and s2
s1 > s2 For direct child
.box > * For universal selector (ex. selects all direct children of .box)

Font and Color Properties

font-family Type face
font-style For italics
font-weight For bold
text-decoration For underline/overline/strikethrough
color Text (foreground) color
background-color Background color
text-align Align text (left, center, right)
border Set border width [length] [style] [color]
font-size For setting the size of the font

Positioning

static (default) element is positioned according to the normal flow of the document
relative positioned relative to its normal position
absolute elements are removed from the normal flow
fixed element is positioned relative to the viewport

Layout Properties

display Override default page flow with block or inline

Spacing and Box Model

margin Add spacing between elements outside of the border. (Can set separately like margin-top
padding Add spacing to an element inside the border.

Calculations

calc() For performing calculations

Units/Size

percentage Represents a percentage value
viewport For Browser Window
em For relative unit (emphasizes text)
rem For font size of root element
height For setting height
width For setting width

Flexbox

display-flex For setting display as flex
flex-direction For specifying which direction the main axis runs
justify-content For controlling where the flex items sit on the main axis
align-items For alligning flex items in flexbox
flex-grow For specifying the flex grow factor
flex-shrink For setting the flex shrink factor of a flex item
flex-wrap For wrapping flex items

JavaScript Language

Syntax

+, -, *, /, %, etc. Arithmetic, comparison, assignment, and other operators
=== and !== Equality tests (don't use == and != except with null)
let x = ...; Declare variables
const x = ...; Declare constants (can't be reassigned)
let arr = [...]; Declare and initialize an array
let obj = { key: value, ... }; Declare and initialize an Object (key/value store)
arr[i], obj[x] Get element/value from array/object (undefined if out of bounds/key doesn't exist)
obj.x Get value of "x" (the literal key x, not the variable) in obj
"key" in obj Check if key exists in obj
delete obj.key; Remove key/value pair from obj. (Note: does not work for arrays)

Control Structures

if (...) ... else ... Conditional statement
while (...) ... Loops
for (let i = ...; ...; ...) ... Traditional (e.g. counter-based) for loops
for (let x of ...) ... Loop over the elements of an array (Note: avoid for ... in)
const fn = (arg1, arg2, ...) => ... Declare functions
return ...; Return from function
let [x, y, ...rest] = arr; "Destructure": extract first element(s), put remaining element(s) in rest (an array)
let { binky, winky, ...rest } = obj; "Destructure": extract certain key/value pairs, put remaining into rest (an Object)
`... ${...} ...` Template string (${...} can be any expression)
try { ... } catch (e) { ... } If an exception is thrown within the try, store it in e and run the catch code (otherwise skip the catch)
throw New Error(message) Throw a new exception with a message (can also have other Error classes)

Data Types

Boolean true or false
Number Integer or floating-point (real) numbers
String Unicode strings (suggest double quotes for literals)
null "Intentionally" not set
undefined Not set (uninitialized, out of bounds, etc.)
Array Indexed collection of elements
Object Collection of key/value pairs
Error Represents an exception (that can be thrown), with a message and stack trace

Array methods

arr.push(x, ...) Add element(s) to an array
arr.indexOf(x) Get index of x in arr (-1 if not found)
arr.slice(start, end) Return a subarray (also works for strings)
arr.splice(index, delCount, ins1, ...) Insert and/or remove elements at index

Object methods (called on Object itself)

Object.keys(obj) Get an array of the keys of obj
Object.values(obj) Get an array of the values of obj
Object.entries(obj) Get an array of the key/value pairs (arrays of length 2) of obj
Object.assign(target, source) Copies all enumerable own properties from one or more source objects to a target object.

Modules

export let x = ...;
export const x = ...;
Named exports
export default ...; Default export
import { x } from "./x.js"; Named import (name must match export)
import X from "./x.js"; Default import (can change name)

Classes

class X { ... } Declare a class
constructor(...) { ... } Called when instance of class created
method(...) { ... } Declare method inside class (no arrow)
new X(...); Instantiate a new object of class X
this.x, this.method(...) Refer to class instance variables and methods

Async Logic

async function Declares an async function where the await keyword is permitted within the function body.
await The await operator is used to wait for a Promise and get its fulfillment value. It can only be used inside an async function or at the top level of a module.

JavaScript in the Browser

Global variables and functions

console.log(...) Print to browser console
alert(message) Display an alert message (popup). Good for quick/testing messages
window "Global object": Store variables here to access them in console
document Access parts of the DOM and DOM manipulation functions
fetch the fetch method provides an easy, logical way to fetch resources asynchronously across the network.

Traversing the DOM tree

document.head, document.body Access the <head> and <body> elements
document.forms A Collection of the <form> elements on the page
elem.parentElement Get an element's parent
elem.children Get a Collection of an element's children
coll.length, coll[i] Access elements of a Collection via array syntax
coll[id] or coll.id Access elements of a Collection by their id attribute
document.querySelector(selector) Access the first element that matches selector, a valid CSS selector string
document.querySelectorAll(selector) Get a Collection of elements that match selector, a valid CSS selector string
elem.querySelector(...), elem.querySelectorAll(...) Same as above, but only search elements inside of elem

Manipulating DOM Elements

elem.id, elem.href, elem.src, etc. Get/set HTML attributes on an element
elem.textContent Get/set text (string) inside element. Setting to "" also removes all children
elem.style Get/set CSS properties of an element. Properties use camelCase instead of hyphens (e.g. fontSize for CSS's font-size).
elem.classList Get/modify list of CSS classes of an element

Adding/removing elements

document.createElement(tag) Create a new element of type tag (e.g. "p"). Does not add to tree
elem.cloneNode(true) Create a copy of elem and all of its children. Does not add to tree
parent.prepend(child) Add child to the tree as parent's first child. child can be an element or text (a string)
parent.append(child) Add child to the tree as parent's last child. child can be an element or text (a string)
a.after(b) Add b as a sibling immediately after a.
elem.remove() Remove elem from the tree (can still manipulate it and add it back later)

Handling Events

elem.addEventListener(type, fn) Call fn when the type event occurs on elem
event.currentTarget (event is the argument passed to handler) Get the element you added the handler to that triggered the event
this._handler = this._handler.bind(this) Add this to a class constructor for any methods you want to use as event handlers
event.preventDefault() Prevent default behavior of action from occuring (clicking link, submitting button, etc.)

Databases and MongoDB

Mongosh Shell

show dbs list all databases
use dbNameHere switching between databases
show collectionNameHere list all collections in current database
db.collectionNameHere.drop() Delete collection
db.dropDatabase() Delete the database

Collection Operations

db.collectionName.insertOne(doc) add a document (doc = javascript object) into collection
db.collectionName.insertMany(docs) add an array of documents (docs = array of javascript objects) into collection
_id each document stored in a collection requires a unique _id field; so don't confuse this with the "id" we set
db.collectionName.find({query}) retrieve all documents in collection that matches query (key/values); no query gets all documents
db.collectionName.findOne({query}) retrieve first document in collection that matches query (key/values); no gauranteed order

Query Operators

$gt Matches values that are greater than a specified value; db.groceries.find({cost: {$gt: 30} })
$lt Matches values that are less than a specified value; db.groceries.find({cost: {$lt: 100} })
$gte Matches values that are greater than or equal to a specified value; db.groceries.find({cost: {$gte: 50} })
$lte Matches values that are less than or equal to a specified value; db.groceries.find({cost: {$lte: 200} })
$in Matches element in array; db.students.find({ id: {$in: ["kashif", "michael"]} })
$regex Matches text (regular expression); db.courses.find({ code: {$regex: "^CS106"} })

Update and Delete

db.collectionName.replaceOne(query, doc) Replace first document matching query with doc; db.myCollection.replaceOne({num:133}, {num:193, binky: "pinky})
db.collectionName.deleteOne(query) Removes a single document from a collection
db.collectionName.deleteMany(query) Delete document(s) matching query
db.collectionName.updateOne(query, update) Updates a single document within the collection based on the filter
db.collectionName.updateMany(query, update) Updates all documents that match the specified filter for a collection
NOTE: don't use update when you want to replace, you will get confusing errors about not using update operators.

Update Operators

$set replaces the value of a field with the specified value

Accessing a collection

conn.db(name) Get a database object (not async)
db.collection(name) Get collection object (not async)

MongoDB in Node

Note: generally most methods are the same as in mongosh
.hasNext() or .next() to loop through (are async)
.toArray() to convert to array (is async)