AP Computer Science Principles (JavaScript)
The same AP CSP course, for classrooms that teach JavaScript.
The AP Computer Science Principles course for teachers who work in JavaScript. It follows the same standards and the same order as the Python track; only the language differs.
JavaScript already runs in the browser, so there is nothing to install and no wait before the first program runs.
Free materials
Basic Datatypes
- Programs, Scripts, and console.log()A first JavaScript program with console.log(): string literals in quotes, the newline after each call, and commas that add one space.
- Variables, Assignment and Number TypesJavaScript variables declared with let and const: = assigns and === compares, camelCase names, one number type, booleans and typeof.
- Strings, Casting and User InputStrings and + concatenation in JavaScript, typeof, casting with Number(), String() and parseInt(), and why prompt() returns a string.
- Type CoercionJavaScript type coercion: + joins when either side is a string, while -, * and / turn text into numbers; NaN from Number(); == vs ===.
- Tracing Assignment and TypeTracing a JavaScript program to find its errors: values in the wrong order, the swap, a ReferenceError, and prompt() returning text.
Operations and Variables
- Arithmetic Operations and DivisionJavaScript arithmetic with one number type: / keeps the fraction, Math.floor versus Math.trunc on negatives, Math.round, and 0.1 + 0.2.
- The Modulo OperatorThe % operator returns a remainder: last digits, odd or even, Math.floor(a / b) for the quotient, negative remainders, weeks and days.
- Exponents, Precedence and Augmented AssignmentExponentiation with **, why JavaScript rejects -3 ** 2, operator precedence, augmented assignment like += and *=, and ++ and --.
- ErrorsA SyntaxError stops a JavaScript program before it starts, a run-time error stops it partway, and a logic error gives no message at all.
- NaN, Infinity and undefinedJavaScript's NaN, Infinity and undefined: values in place of a crash, NaN not equal to itself, Number.isNaN(), and undefined vs null.
- Debugging Arithmetic ExpressionsDebugging JavaScript arithmetic: logic errors, Math.floor for whole groups, % === 0 for divisibility, reading digits, Number(prompt()).
- Mixed OperationsEvaluating a long JavaScript line one operator at a time: precedence, / keeping the fraction, Math.floor on negatives, + joining text.
- Trace the VariablesTracing JavaScript variables in a table, one row per line: each line uses the current values, with augmented assignment and text joins.
Conditionals
- Comparison OperatorsJavaScript comparison operators return true or false: <, >, <=, >=, loose == and != versus strict === and !==, and = for assignment.
- Boolean OperationsJavaScript's logical operators && (and), || (or) and ! (not), their truth tables, the inclusive or, and parentheses to negate a test.
- Truthy and FalsyTruthy and falsy values in JavaScript: the six falsy values, Boolean(x), || and && handing back an operand, and the || default idiom.
- Operator PrecedenceJavaScript precedence from ** and ! through comparisons, && and || to assignment: && binds tighter than ||; !(a > b) negates a test.
- ConditionalsJavaScript if, else if and else: braces mark the block, independent ifs, the first true branch wins, nesting, and a FizzBuzz order bug.
- Debugging ConditionalsDebugging a JavaScript if-else if chain: a chained comparison, conditions never or always true, De Morgan's laws, and boundary tests.
Functions
- Defining and Calling FunctionsA JavaScript function is a named block defined with function and run only when called: parameters, flow of control, and hoisting.
- Return ValuesReturn values in JavaScript: a call equals what it returns, an unused value is lost, and a function with no return gives undefined.
- Parameters, Arguments and AbstractionJavaScript parameters and arguments matched by position, NaN from a missing argument, extra ones dropped, abstraction with Math.sqrt.
- Flow, Scope and Program StructureFlow through JavaScript function calls, local variables and ReferenceError, block scope with let versus var, globals, and program shape.
- Libraries, APIs and DocumentationLibraries such as JavaScript's Math, internal and external code, an API as a contract (Math.floor, Math.max, indexOf), documentation.
- Debugging FunctionsDebugging JavaScript functions: a wrong formula, console.log instead of return giving undefined, using the result, and storing it once.
- Reading a SpecReading a spec for a JavaScript function: its name, parameters and return value, return versus console.log, and hidden edge-case tests.
For Loops
- Iteration and For-Of LoopsIteration repeats part of an algorithm; a JavaScript for-of loop visits each value of an array or each character of a string in turn.
- The Counting for LoopThe JavaScript for loop: initialiser, condition and update, counting down or in steps, the let variable's scope, and definite iteration.
- Summing with an AccumulatorAn accumulator sums in a JavaScript for loop: let total = 0 before the loop, total += i inside, an if to add only some, return after it.
- CountingCounting with a JavaScript for loop adds 1 per match, from the factors of n to the o's in a string, where ch === "o" || "O" fails.
- Debugging For LoopsDebugging JavaScript for loops by hand tracing: a sum's starting value, a counter that adds 1, a running maximum from the first item.
- Coding Practice: LoopsWriting JavaScript loops from a spec: what to keep between passes, its starting value (0, 1, "" or the first item), and returning it.
Lists
- Lists and IndexingJavaScript arrays with .length and push, zero-based indexing, undefined past the end and at arr[-1], at(-1), and assigning to arr[i].
- Traversing and Modifying a ListTraverse a JavaScript array by value with for-of or by index up to arr.length, change items through arr[i], and build arrays with push.
- Average, Maximum and MinimumFunctions for the sum, average, maximum and minimum of a JavaScript array, and the trap of starting a running max at 0 on negative data.
- Slicing and List MethodsJavaScript slice(start, end) with end excluded, negative starts, reverse on a copy, and push, pop, shift and splice changing the array.
- Mutating vs CopyingMutating versus copying JavaScript array methods: push and sort change the array, slice and join do not, sort((a, b) => a - b), aliases.
- Debugging List TraversalsDebugging JavaScript array loops: splice(indexOf(x), 1) on a missing value, includes, removing items while looping, comparing neighbors.
While Loops, Nested Loops and Objects
- Definite vs Indefinite LoopsDefinite versus indefinite loops: JavaScript's while loop, infinite loops, do-while that runs at least once, and break and continue.
- Sentinels and Random NumbersSentinel while loops that call prompt() before the loop and at the body's end, and random integers with Math.floor(Math.random() * n).
- Nested LoopsJavaScript nested loops run the inner loop fully on each outer pass, so passes multiply; rows built as strings; inner bounds that use i.
- Objects as RecordsJavaScript objects as records of named fields: dot and bracket access, undefined for a missing field, Object.keys, const, destructuring.
- Lists of ObjectsArrays of JavaScript objects as records: booths[1].sales, then a for-of loop to total, count and keep the record with the largest field.
- Loop Conditions and Off-by-One ErrorsDebugging JavaScript while loops: a prompt() string that !== never matches to a number, decimal round-off, off-by-one errors, and flags.
Algorithms
- Algorithms and Sequential SearchSequencing, selection and iteration as the building blocks of algorithms, and a JavaScript sequential search returning an index or -1.
- Binary SearchBinary search halves a sorted array each probe with a Math.floor midpoint: about log2 n probes against n for sequential search.
- Algorithmic EfficiencyEfficiency by counting statements in JavaScript loops: loops in sequence add, nested loops multiply; reasonable versus exponential time.
- Heuristics, Undecidability and SimulationHeuristics when no efficient algorithm exists, decidable versus undecidable problems, and simulations as abstractions, like cooling tea.
- Correctness and EfficiencySpeeding up a correct JavaScript program: count the work, call once before a loop, constant time, binary search probes, reasonable time.
Creative Development: Collaboration and Program Design
- Collaboration: Perspectives, Users and TeamsCollaboration in AP CSP: diverse perspectives, consulting users, pair programming, online tools, and resolving conflicts in a team.
- The Development Process and Program DesignDeveloping a program: investigating, designing, prototyping and testing, requirements and specifications, incremental, iterative work.
- Documentation and Acknowledging CodeProgram documentation and comments: what code does and why, written during development and kept current, and crediting code by others.
Data 1: Representing Data Digitally
- Bits, Bytes and Place ValueBits, bytes and binary place value: base 2 read in base 10, comparing binary numbers without converting, how many values n bits name.
- Converting Between BasesDecimal to binary by powers of two or by repeated division with % and Math.floor, plus counting and doing arithmetic in other bases.
- Hexadecimal, Overflow and Round-OffHexadecimal four bits at a time, overflow and the largest value n bits hold, Number.MAX_SAFE_INTEGER and BigInt, round-off like 1 / 3.
- Encoding, Abstraction and AnalogEncoding text with ASCII, charCodeAt() and String.fromCharCode(), Unicode with UTF-8 and UTF-16, and sampling analog sound into data.
Data 2: Images and Compression
- The Bitmap: Pixels, Colour and ResolutionBitmap images: pixels, RGB additive colour and 24-bit colour, resolution vs colour depth, and the bytes an uncompressed image needs.
- Lossless and Lossy CompressionLossless versus lossy compression: run-length encoding, GIF and PNG versus JPEG, and why file size alone never says which kind was used.
- Formats, Metadata and Vector GraphicsImage metadata; BMP, GIF, JPEG and PNG compared on compression and alpha transparency; vector graphics such as SVG drawn from a rule.
Data 3: Extracting Information from Data
- Sequential, Parallel and Distributed ComputingSequential, parallel and distributed computing: run time, speedup as sequential over parallel time, the cap the sequential part sets.
- From Data to InformationData versus information: transforming, filtering, combining and visualising, correlation and causation, clustering, bias, and cleaning.
The Internet
- Networks, LANs and SwitchesComputer networks: computing devices and systems, LANs and WANs, clients and servers, and how a switch delivers data on a LAN.
- MAC Addresses, IP Addresses and RoutersInternet protocols, MAC addresses versus IP addresses, and switches versus routers: one works inside a network, one joins networks.
- IPv4, Private Addresses and IPv6IPv4 addresses as four 8-bit parts, network and host IDs, private addresses behind a default gateway, port numbers, and 128-bit IPv6.
- Protocols, TCP/IP and the WebIP routes packets and TCP delivers them reliably and in order, plus UDP, HTTP and the Web, and DNS turning names into IP addresses.
- Packets, Routing, Bandwidth and LatencyPackets with routing and reassembly metadata, dynamic routing, redundancy and fault tolerance, and bandwidth vs latency on a network.
Securing Data: Cryptography
- Ciphers and Symmetric EncryptionCaesar and substitution ciphers, breaking them by trying every key or by letter frequency, key length in bits, and symmetric encryption.
- Key Exchange and Diffie-HellmanDiffie-Hellman key exchange: a shared secret key agreed in the open, first with paint mixing, then with modular exponentiation.
- Public-Key CryptographyPublic-key cryptography: a public key encrypts and only the private key decrypts, the lockbox picture, and RSA.
- Hash Functions, Digital Signatures and HTTPSHash functions such as SHA-256, digital signatures made with a private key, certificate authorities, and how HTTPS checks a site.
Impact of Computing
- Computing Innovations and Their EffectsComputing innovations and their purpose, beneficial and harmful effects, unintended uses, and how fast an innovation can spread.
- The Digital Divide and Computing BiasThe digital divide in Internet access and why it raises ethical concerns, and computing bias that comes from algorithms and data.
- Crowdsourcing, Citizen Science and reCAPTCHACrowdsourcing as getting input from many people over the Internet, citizen science such as Galaxy Zoo, and how reCAPTCHA began.
- Intellectual Property, Licensing and Legal ConcernsIntellectual property, plagiarism and citing sources, Creative Commons, open source and open access, and legal and ethical concerns.
Privacy and Security
- Privacy, PII and Safe ComputingPrivacy versus security, personally identifiable information (PII), cookies and tracking, and how scattered data builds a profile.
- Social Engineering, Phishing and MalwareSocial engineering and phishing, spotting a fake link, rogue access points, keyloggers, viruses and other malware, and staying safe.
- Authentication: What You Know, Have and AreMultifactor authentication across categories: what you know, have and are, strong passwords, lockouts, security keys and biometrics.