LEARN TO CODE | QUICK REFERENCE
JAVASCRIPT CHEAT SHEET
Syntax, built-in functions and popular methods at a glance. Covers all four sections of the JavaScript course.
JUMP TO A TOPIC
Examples use modern browser JavaScript. Each row is an independent snippet: read it on its own rather than pasting every row together. Use the bookmark links to find what you need.
01 | SETUP, VARIABLES AND OUTPUT
| Item | Use and example |
|---|---|
| Load a script |
Place a deferred external script in the HTML head. This is HTML, not
JavaScript.
|
| Console output |
Open the browser developer tools console to see output.
|
| let and const |
Use let when reassigning. const prevents reassignment of the binding.
|
| Comments |
Explain why code exists. Comments do not run.
|
| Data types |
Common primitive values. Arrays and plain objects are objects.
|
| Template literals |
Backticks allow interpolation and multiline strings.
|
02 | NUMBERS AND CONVERSION
| Item | Use and example |
|---|---|
| Arithmetic |
Use parentheses to control evaluation order.
|
| Updating values |
Shorthand updates the current value.
|
| Number() |
Convert a complete value to a number. Invalid text becomes NaN.
|
| parseInt / parseFloat |
Parse a numeric prefix. These can accept trailing nonnumeric text.
|
| Number checks |
Check finite numbers and integers after conversion.
|
| Math and formatting |
toFixed returns text. Math.random is not for passwords or security.
|
03 | CONDITIONS AND LOOPS
| Item | Use and example |
|---|---|
| Comparisons |
Prefer strict equality: it does not convert types.
|
| Boolean logic |
&& means AND, || means OR, ! means NOT.
|
| if / else if / else |
Only the first matching branch runs.
|
| for |
Repeat with a counter. The loop body is the code inside the braces.
|
| for...of |
Read each value in an iterable such as an array.
|
| while |
Check the condition before every repetition.
|
| break and continue |
break exits the loop; continue skips to its next iteration.
|
04 | STRING METHODS
| Item | Use and example |
|---|---|
| length and indexing |
Indexes start at 0. length is a property, not a method.
|
| slice(start, end) |
The end index is excluded; negative indexes count from the end.
|
| Case and whitespace |
Strings are immutable. Store the returned string.
|
| Searching |
Searches are case-sensitive. indexOf returns -1 if missing.
|
| Replacing |
replace changes the first string match; replaceAll changes all.
|
| split and join |
split makes an array; join combines array values into a string.
|
05 | FUNCTIONS AND SCOPE
| Item | Use and example |
|---|---|
| Declaration and return |
Parameters receive inputs. return sends a result to the caller.
|
| Default parameter |
The default is used for missing or undefined arguments.
|
| Arrow function |
A single expression can return implicitly.
|
| Block scope |
let and const are limited to their enclosing block.
|
| Debugging |
Use breakpoints in browser developer tools to pause and inspect
values.
|
06 | ARRAY BASICS
| Item | Use and example |
|---|---|
| Create and access |
Arrays use zero-based indexes and can grow.
|
| push and pop |
Both mutate the array. push returns its new length; pop returns the
removed item.
|
| unshift and shift |
Add or remove at the start. Both mutate the array.
|
| slice and splice |
slice copies a range; splice removes or inserts in the original array.
|
| includes and indexOf |
Check for a primitive value or find its first position.
|
| Copy and spread |
Spread makes a shallow copy. Nested objects remain shared.
|
07 | ARRAY TRANSFORMATIONS
| Item | Use and example |
|---|---|
| map |
Return a new array containing each transformed value.
|
| filter |
Return a new array containing values that pass the test.
|
| find and findIndex |
Return the first matching value or index. Missing: undefined or -1.
|
| some and every |
Test whether at least one value, or every value, matches.
|
| reduce |
Combine values into one result. Supply an initial accumulator.
|
| sort |
sort mutates. Supply a comparator for numeric order.
|
| forEach |
Run an action for each item. It returns undefined, not a new array.
|
08 | OBJECTS AND PROPERTIES
| Item | Use and example |
|---|---|
| Create, read and update |
Use dot notation or brackets for a computed property name.
|
| Object methods |
An object can store functions as methods.
|
| keys, values and entries |
Inspect an object or loop through its own enumerable properties.
|
| Destructuring and spread |
Extract values and make a shallow copy with an updated property.
|
| Optional chaining and defaults |
?. stops at null or undefined; ?? supplies a default for those values.
|
09 | SELECT AND CHANGE THE DOM
| Item | Use and example |
|---|---|
| Select elements |
Examples in this group require matching HTML elements. Check a single
match for null.
|
| Select many |
querySelectorAll returns a static NodeList.
|
| textContent |
Display text, including user input, without interpreting it as HTML.
|
| classList |
Use CSS classes for appearance and state.
|
| Attributes and properties |
Use properties for current input values and boolean state.
|
| Create, append and remove |
Create nodes and set text instead of building HTML from user input.
|
10 | EVENTS
| Item | Use and example |
|---|---|
| addEventListener |
Assumes a button with id start. Pass a function, not its result.
|
| Event object |
currentTarget is the element with the listener. target is where the
event began.
|
| input and change |
input reacts while editing. change reacts when a change is committed.
|
| Keyboard events |
Check event.key for the key name.
|
11 | FORMS AND VALIDATION
| Item | Use and example |
|---|---|
| Read form controls |
Assumes text input #name and checkbox #agree. value is text; checked
is boolean.
|
| Handle submit |
Assumes form #entry and input #name. Prevent the normal page
submission.
|
| Validate a number |
Reject blank input before Number(), because Number("") is 0.
|
| FormData |
Assumes form #entry. Controls need name attributes to appear in
FormData.
|
Use HTML required, type, min, max and minlength where appropriate. Browser validation helps users; a server must validate submitted data independently.
12 | JSON AND BROWSER STORAGE
| Item | Use and example |
|---|---|
| JSON.stringify and JSON.parse |
Convert supported data to JSON text and back. Invalid JSON throws.
|
| localStorage |
Stores strings for this origin across visits, subject to browser
settings.
|
| Store an array |
Check parsed data before using it. Missing keys return null.
|
| sessionStorage |
Similar API, scoped to the page session in a tab. It is not a server
login session.
|
Do not store passwords or secrets in browser storage. JSON does not preserve methods, undefined values or all JavaScript types. Validate the shape and values of restored records, not only whether they form an array.
13 | PROMISES, ASYNC AND AWAIT
| Item | Use and example |
|---|---|
| Promise |
Represents an eventual result or failure. then handles success; catch
handles failure.
|
| async / await |
async functions return promises. await pauses that function until
settlement.
|
| try / catch / finally |
Handle failure and run cleanup whether the operation succeeds or
fails.
|
| Promise.all |
Wait for all results. Rejects if one input promise rejects.
|
| Timers |
A timeout schedules a callback after at least the requested delay.
|
14 | FETCH AND ERROR HANDLING
| Item | Use and example |
|---|---|
| GET JSON |
Example expects /data.json on a local HTTP server. fetch does not
reject just because of a 404.
|
| POST JSON |
Example requires an API route that accepts JSON at /api/items.
|
| Cancel a request |
AbortController can cancel an in-progress fetch.
|
Use a local HTTP server, such as the VS Code Live Server extension, for fetch examples. Cross-origin APIs need suitable server CORS headers. mode: "no-cors" does not make a JSON response readable. Keep private API keys on a server.
15 | QUIZ PROJECT PATTERNS
| Item | Use and example |
|---|---|
| Question data |
Store the correct option index alongside each question.
|
| Read one answer |
Use radio inputs sharing name="answer", with values 0, 1, 2,
and so on.
|
| Score once |
The Set prevents the same question being scored repeatedly.
|
16 | TO-DO PROJECT PATTERNS
| Item | Use and example |
|---|---|
| Stable IDs |
A stable identifier remains useful when array positions change.
|
| Update and delete |
Return new arrays. Identify the task by ID rather than display text.
|
| Render a list |
Assumes ul #tasks. Rebuild it from application state.
|
COMMON MIX-UPS
- = assigns; === compares values without type conversion.
- String and array indexes begin at 0; slice excludes its end index.
- const prevents reassignment; its objects and arrays can still change.
- return sends a result back; console.log displays it.
- map returns an array; forEach returns undefined.
- sort mutates and needs a comparator to sort numbers numerically.
- Input values are strings. Check blanks before converting to numbers.
- Use textContent when displaying user text.
- fetch needs an explicit response.ok check for HTTP errors.
- Browser storage is not a database or a secure login system.
MDN references: