JavaScript Tutorial
Make pages interactive. The language of the web.
Getting started5 lessons
- 1JavaScript IntroductionWhat JavaScript does and how to print output.
- 2Where to Put JavaScriptInline scripts, script tags and external files.
- 3JavaScript OutputShowing results in the console and on the page.
- 4JavaScript SyntaxStatements, values, identifiers and case.
- 5JavaScript CommentsNotes for humans.
Basics18 lessons
- 6VariablesStoring values with let and const.
- 7ScopeWhere a variable can be used.
- 8HoistingDeclarations are processed before code runs.
- 9Data TypesStrings, numbers, booleans and more.
- 10Type ConversionTurning one type into another.
- 11OperatorsMaths, comparison and logic.
- 12Logical, Ternary and Nullish Operators&&, ||, ??, ?: and ?. for short and safe code.
- 13Booleans and Truthinesstrue, false and values that act like them.
- 14JavaScript StatementsA program is a list of statements.
- 15Keywords and IdentifiersKeywords such as let, const, if and function are reserved.
- 16let, const and varUse const by default, let when the value changes and avoid var.
- 17The typeof Operatortypeof returns the type of a value as a string: number, string, boolean, undefined, object.
- 18null and undefinedundefined means no value was assigned.
- 19== versus ===== converts types before comparing and gives surprises.
- 20Truthy and Falsy ValuesFalsy values are false, 0, "", null, undefined, NaN and 0n.
- 21Operator Precedence and AssignmentOperators have precedence, like in maths: * before +, && before ||.
- 22Increment, Decrement and Bitwise++ and -- add or subtract one, before or after use.
- 23Exponent, Modulo and Integer Division** raises to a power and % gives the remainder.
Strings and numbers18 lessons
- 24StringsWorking with text values.
- 25String MethodsSearching, slicing and changing text.
- 26Template LiteralsBacktick strings with embedded values.
- 27NumbersIntegers, decimals and special values.
- 28Number MethodsFormatting and checking numbers.
- 29The Math ObjectRounding, powers and more.
- 30Random NumbersMath.random and useful recipes.
- 31String BasicsStrings use single, double or backtick quotes.
- 32slice, substring and substrslice(start, end) extracts a part and supports negative indexes.
- 33Searching StringsindexOf and lastIndexOf find a position, includes tests presence, startsWith and endsWith .
- 34replace, replaceAll, split and joinreplace changes the first match, replaceAll all of them.
- 35Trim, Pad, Repeat and Casetrim removes spaces at the ends, padStart and padEnd fill to a length, repeat repeats and .
- 36Unicode, Emoji and localeCompareStrings are UTF-16, so some characters use two units.
- 37Parsing NumbersparseInt and parseFloat read numbers from the start of a string.
- 38Formatting NumberstoFixed rounds to a number of decimals and returns a string.
- 39More Math FunctionsMath has round, floor, ceil, trunc, abs, min, max, pow, sqrt, sign, hypot and trig functio.
- 40Random Numbers in PracticeMath.random gives a number from 0 up to but not including 1.
- 41Number Limits and PrecisionMAX_SAFE_INTEGER is 2^53 - 1.
Control flow8 lessons
- 42ConditionsMaking decisions with if and else.
- 43The switch StatementChoosing between many fixed values.
- 44LoopsRepeating work.
- 45for...of and for...inLooping over values and keys.
- 46while, do...while, break and continueLoops that depend on a condition.
- 47if, else if and elseUse if to run code when a condition is true, else if for more checks and else for the defa.
- 48Ternary and switchThe ternary operator picks between two values in one expression.
- 49Loop Control: break, continue and labelsbreak leaves a loop and continue skips to the next round.
Functions12 lessons
- 50FunctionsReusable blocks of code.
- 51Function ParametersDefaults, rest parameters and named options.
- 52Arrow FunctionsA shorter way to write functions.
- 53Callbacks and Higher-Order FunctionsPassing functions to other functions.
- 54ClosuresFunctions that remember their surroundings.
- 55RecursionA function that calls itself.
- 56Declarations, Expressions and HoistingA function declaration is hoisted and can be called before it appears.
- 57Default and Rest ParametersDefault values fill missing arguments.
- 58Arrow Functions and thisArrow functions do not have their own this, they use the one around them.
- 59IIFE and Higher Order FunctionsAn IIFE runs immediately and keeps variables private.
- 60call, apply and bindcall and apply run a function with a chosen this.
- 61Recursion PatternsRecursion solves a problem by calling itself on a smaller one.
Objects and classes15 lessons
- 62ObjectsGrouping related data with keys.
- 63Object Methods and thisFunctions stored on objects.
- 64DestructuringUnpacking arrays and objects.
- 65Spread and RestCopying and merging with three dots.
- 66ClassesBlueprints for objects.
- 67Class InheritanceBuilding one class on another.
- 68JSONSending and storing data as text.
- 69Objects: Properties and MethodsObjects store key value pairs.
- 70Object.keys, values, entries and assignObject.keys, values and entries list properties.
- 71Optional Chaining and Defaults?.
- 72Freeze, Seal and Property DescriptorsObject.freeze stops all changes, seal stops adding or removing, preventExtensions stops ad.
- 73Classes: Constructors and MethodsA class describes objects.
- 74Inheritance with extends and superextends makes a subclass.
- 75Getters, Setters and Static in Classesget and set make computed or validated properties.
- 76JSON in PracticeJSON.stringify turns values into text and JSON.parse reads it.
Arrays and collections15 lessons
- 77ArraysLists of values.
- 78Array MethodsAdding, removing, searching and slicing.
- 79map, filter and reduceTransforming lists without loops.
- 80Sorting Arrayssort, reverse and comparison functions.
- 81SetsCollections of unique values.
- 82MapsKey and value pairs with any key type.
- 83Array BasicsArrays hold ordered values.
- 84slice, splice and concatslice copies a part without changing the array.
- 85Finding Items in Arraysfind returns the first match, findIndex its position, includes tests presence, some and ev.
- 86Looping Over ArraysUse for...of for values, forEach for side effects, entries() for index and value and a cla.
- 87reduce in Practicereduce folds an array into a single value with an accumulator.
- 88Sorting Arrays Correctlysort converts items to strings by default, so numbers sort wrongly.
- 89Set and Map in PracticeSet stores unique values and Map stores key value pairs with any key type.
- 90Array Destructuring and SpreadDestructuring unpacks arrays into variables.
- 91Array.from, Array.of and fillArray.from builds arrays from iterables or length objects with a map function.
Dates and patterns4 lessons
Errors and debugging4 lessons
- 96Errors and try...catchHandling things that go wrong.
- 97DebuggingFinding and fixing bugs.
- 98try, catch and finallytry runs risky code, catch handles an error and finally always runs, which is good for cle.
- 99Debugging with the Consoleconsole.log, table, warn, error, group and time help you see what code does.
The DOM16 lessons
- 100The DOMChanging the page from JavaScript.
- 101Selecting ElementsgetElementById and querySelector.
- 102Changing Content and AttributestextContent, innerHTML and setAttribute.
- 103Changing Stylesstyle and classList.
- 104Creating and Removing ElementscreateElement, append and remove.
- 105EventsReacting to clicks and typing.
- 106Event ListenersClick, input, keydown and the event object.
- 107Forms and User InputReading values and handling submit.
- 108Navigating the DOMMove around with parentElement, children, firstElementChild, nextElementSibling and closes.
- 109Attributes, Classes and DatasetgetAttribute and setAttribute read and write attributes.
- 110Event DelegationAttach one listener to a parent and check event.target.
- 111Forms and Validation in JavaScriptListen to the submit event, call preventDefault and read values with FormData or element.v.
- 112localStorage, sessionStorage and CookieslocalStorage keeps strings until cleared.
- 113Intersection and Resize ObserversIntersectionObserver reports when elements enter the viewport, great for lazy loading and .
- 114Window, Location and Historywindow is the global object of the browser.
- 115Fetch in Practicefetch returns a promise.
Asynchronous JavaScriptPremium5 lessons
Projects3 lessons
AdvancedPremium4 lessons
Advanced JavaScriptPremium18 lessons
- 128Iterators and the for...of ProtocolAn iterable has a [Symbol.iterator]() method that returns an iterator with next().
- 129Generator FunctionsA function* returns a generator.
- 130SymbolsA Symbol is a unique value, often used as a hidden property key that never clashes.
- 131Getters, Setters and definePropertyAccessor properties run code when read or written.
- 132Prototypes and the Prototype ChainEvery object links to a prototype.
- 133Private Fields and Static MembersFields starting with # are private to the class.
- 134Tagged Template LiteralsA tag function receives the string pieces and the values of a template literal.
- 135Proxy and ReflectA Proxy wraps an object and intercepts operations such as get, set and has.
- 136WeakMap, WeakSet and WeakRefWeakMap and WeakSet hold objects without preventing garbage collection.
- 137Modern Array MethodsNewer methods are non destructive: toSorted, toReversed, with, at, flat, flatMap, findLast.
- 138Internationalisation with IntlIntl formats numbers, currencies, dates, lists and plurals for any locale without librarie.
- 139BigInt and Numeric PrecisionNumbers are 64 bit floats and lose accuracy past 2^53.
- 140Typed Arrays and ArrayBufferTyped arrays such as Uint8Array and Float32Array hold fixed type numbers in raw memory.
- 141Promise CombinatorsPromise.all waits for all and fails fast.
- 142Async Iterators and for awaitAsync generators produce values over time.
- 143Cancelling with AbortControllerAbortController cancels async work.
- 144The Event Loop in DepthJavaScript runs one task at a time.
- 145Custom Events and Pub SubCustomEvent lets you create your own events with data.
JavaScript in practicePremium10 lessons
- 146Debounce and ThrottleDebounce waits until activity stops, ideal for search boxes.
- 147Memoization and CachingMemoization stores results by arguments, so repeated calls are instant.
- 148Currying and Function CompositionCurrying turns f(a, b) into f(a)(b).
- 149Immutable Data and FreezingImmutable updates create new objects instead of changing old ones, which prevents surprisi.
- 150Custom Errors and Error Handling PatternsCreate error classes with names and extra data, and use error.cause to keep the original f.
- 151Security: XSS and Safe DOM UpdatesCross site scripting happens when user input becomes HTML or code.
- 152Testing JavaScriptWrite small pure functions and test them with assertions.
- 153Measuring PerformanceMeasure before optimising.
- 154Modelling State with a State MachineA state machine lists the states and the allowed transitions, which prevents impossible co.
- 155Project: To Do ListCombine events, the DOM, arrays and localStorage into a small app.