Foundations reference

JavaScript Reference

Variables through algorithms, with the Python equivalent noted beside each idea.

Getting started

JavaScript runs in every browser and, through Node, on servers too. Everything below runs in the editor on any lesson page.

Output

console.log prints a value so you can see it. It is how you check what your program is actually doing.

console.log("Sankofa Code");
console.log(52 * 7);
  • Python writes print() instead.
  • Quotes make text. No quotes means evaluate it first.

Variables

A name for a value, so the program can refer to it later instead of repeating it.

let score = 10;
score = 25;              // reassigned

const NAME = "Amara";    // cannot be reassigned
  • Use const by default, let only when the value genuinely changes.
  • Avoid var. It behaves differently in ways that surprise people.
  • Python has no keyword at all: score = 10

Comments

Notes for humans that the machine ignores.

// a single line

/* several
   lines */
  • Python uses a hash for single lines.

Data types

The types you use daily

Numbers, strings, booleans, and the two ways of saying nothing.

42            // number
3.14          // also number, no separate float
"text"        // string
true / false  // boolean
null          // deliberately empty
undefined     // never given a value
  • JavaScript has one number type. Python separates int and float.
  • Python writes True and False with capitals, and has only None.

Strings

Text. Template literals with backticks let you drop values straight in.

const name = "Amara";
const greeting = `Hello, ${name}`;

name.length          // 5
name.toUpperCase()   // "AMARA"
name[0]              // "A"
"  hi  ".trim()      // "hi"
"a,b,c".split(",")   // ["a", "b", "c"]
  • Python uses f-strings: f"Hello, {name}", and len(name) rather than .length.

Converting between types

Input arrives as text. Convert before doing arithmetic with it.

Number("42")      // 42
String(42)        // "42"
parseInt("42px")  // 42

"7" + 3           // "73"  string joined
Number("7") + 3   // 10    numbers added
  • That third line is the most common beginner bug there is.
  • Python uses int(), float() and str().

Collections

Arrays

An ordered list. Python calls the same idea a list.

const names = ["Ama", "Kofi", "Zuri"];

names[0]              // "Ama"
names.length          // 3
names.push("Nia")     // add to the end
names.includes("Ama") // true
names.slice(0, 2)     // a copy of the first two
  • Assigning an array to another name shares it. Use [...names] to copy.

Objects

Named fields. Python calls the same idea a dictionary.

const member = { name: "Ama", hours: 40 };

member.name        // "Ama"
member["hours"]    // 40
member.city = "Atlanta";
Object.keys(member);
  • Python writes {"name": "Ama"} and reads it as member["name"].

Array methods worth knowing

Filtering, transforming and reducing, without writing the loop yourself.

const n = [1, 2, 3, 4];

n.filter(x => x % 2 === 0)     // [2, 4]
n.map(x => x * 10)             // [10, 20, 30, 40]
n.reduce((a, b) => a + b, 0)   // 10
n.find(x => x > 2)             // 3
[...n].sort((a, b) => a - b)   // numeric sort
  • Plain .sort() compares as text, so 10 lands before 9. Always pass a comparator for numbers.

Control flow

Conditionals

Ordered tests. The first true branch wins, so put the most specific first.

if (score >= 90) {
  grade = "A";
} else if (score >= 80) {
  grade = "B";
} else {
  grade = "Keep going";
}
  • Use === not ==. Loose equality converts types first, so "5" == 5 is true.
  • Python writes elif and uses indentation instead of braces.

Loops

Repeat until something is done. for...of walks a collection directly.

for (const n of numbers) {
  total += n;
}

for (let i = 0; i < 5; i++) { }

while (balance < goal) {
  balance += 75;
}
  • A while loop needs something inside it to change, or it never ends.
  • Python writes for n in numbers, and range(5) for the counted form.

Errors

Wrap risky work, handle the failure, and let finally clean up either way.

try {
  const data = JSON.parse(text);
} catch (err) {
  console.log("Could not parse");
} finally {
  console.log("Always runs");
}

throw new Error("empty list");
  • Python uses try, except and raise.

Functions

Declaring and returning

A named, reusable operation. Returning hands the value back; printing throws it away.

function total(items) {
  let sum = 0;
  for (const i of items) sum += i;
  return sum;
}

const double = (n) => n * 2;   // arrow form

function greet(name = "friend") { }  // default
  • A function that prints instead of returning cannot be used as a building block.
  • Python writes def total(items): with a colon.

Scope

A variable created inside a function does not exist outside it.

let count = 10;

function change() {
  let count = 99;   // a different variable
}
change();
// count is still 10
  • let and const are block scoped, so they also stop existing at the closing brace.

Algorithms and complexity

The patterns that cover most problems

Counting, accumulating, searching, filtering, mapping and finding extremes.

// running maximum
let biggest = numbers[0];
for (const n of numbers) if (n > biggest) biggest = n;

// duplicates in one pass
const seen = new Set();
for (const x of items) {
  if (seen.has(x)) return true;
  seen.add(x);
}
  • Start a maximum from the first real element, never from 0, or an all-negative list returns 0.

Complexity

How the work grows as the input grows. Sequence adds, nesting multiplies.

O(1)       indexing
O(log n)   binary search
O(n)       one loop
O(n log n) a good sort
O(n^2)     nested loops
  • Swapping a nested search for a Set lookup turns O(n squared) into O(n).
  • Make it correct first, measure, then optimise.

Edge cases worth testing every time

The six that catch the overwhelming majority of real defects.

[]          // empty
[x]         // one item
[x, x, x]   // all identical
            // answer first
            // answer last
[-3, -9]    // negatives
0           // zero

Want to learn how to build with this?

A reference tells you what exists. The course teaches you when to reach for it, and has you build something real while you learn.