Developer documentation
Browse HTML, CSS, JavaScript, TypeScript, Python, Java, C#, Ruby, C++, PHP, Lua and Luau syntax, explanations and code examples.
HTML documentation
HTML
HTML (HyperText Markup Language) gives web pages their structure and meaning. Start here to learn how HTML became the foundation of the Web, how browsers read it, and how it works with CSS and JavaScript.
Create your first HTML webpage
Use a plain-text editor and a browser to save, open and understand your first complete HTML file. HTML needs no language installation.
Understand an HTML document
Learn what the doctype, html, head, metadata, title and body do, then read nested headings, paragraphs and links in a complete webpage.
Set up HTML in VS Code
Open a project folder, save HTML files and use VS Code’s built-in HTML editing features without adding a compiler or required extension.
Connect HTML, CSS and JavaScript
Build a small three-file webpage and see how HTML structure, CSS appearance and JavaScript behaviour work together.
Try HTML in the Codectionary Playground
Edit and preview HTML in Codectionary’s Playground, add CSS and JavaScript files, and understand what its sandbox can and cannot do.
Debug and validate an HTML page
Use browser developer tools, a simple troubleshooting sequence and the Nu HTML Checker to find beginner HTML mistakes.
HTML Forms
HTML forms are used to collect user input and send it to a server for processing. They contain interactive controls like text fields, checkboxes, radio buttons, and submit buttons. Forms are a fundamental part of web interactivity, enabling everything from login pages and search bars to complex data entry interfaces.
<div>
The <div> element is a generic container used to group and organize content on a web page. It has no semantic meaning on its own but is essential for layout and styling. Think of it as a box that can hold other HTML elements. Divs are block-level elements, meaning they start on a new line and take up the full width available.
<span>
The <span> element is an inline container used to group and style specific portions of text or inline elements. Unlike <div>, which is block-level, <span> doesn't break the flow of content. It's perfect for applying styles or manipulating specific words or phrases within a paragraph without affecting the surrounding content.
<a>
The <a> (anchor) element creates hyperlinks that allow users to navigate between pages, sections, or external resources. Links are fundamental to the web, enabling the interconnected nature of websites. The href attribute specifies the destination, while the link text tells users what to expect when they click.
<img>
The <img> element embeds images into web pages. Images enhance visual communication and user engagement. The src attribute specifies the image source, while alt provides alternative text for accessibility and SEO. Images are inline-replaced elements, meaning they display in the flow of text but are replaced with the actual image content.
<h1> - <h6>
The heading elements <h1> through <h6> represent six levels of section headings, with <h1> being the most important and <h6> the least. Headings create a document outline that both sighted users and assistive technologies rely on to understand and navigate page structure. Search engines also use heading hierarchy to interpret content relevance. Each page should typically have exactly one <h1> describing its main topic, with subsequent headings nested logically to reflect the content hierarchy.
<p>
The <p> element represents a paragraph of text — one of the most fundamental building blocks of written content on the web. Browsers automatically add margin above and below paragraphs to visually separate them. The <p> element cannot contain other block-level elements like <div> or headings, only inline content and text. It is a block-level element, meaning it always starts on a new line.
<ul>
The <ul> element represents an unordered list of items, typically displayed with bullet points. The order of items has no semantic meaning — use <ol> instead when sequence matters. Every item inside a <ul> must be wrapped in an <li> (list item) element. Unordered lists are commonly used for navigation menus, feature lists, and any collection of related items.
<ol>
The <ol> element represents an ordered (numbered) list, where the sequence of items is meaningful. Like <ul>, every item must be wrapped in an <li> element. Browsers automatically number items starting from 1, but this can be customized using the start and reversed attributes, or a different numbering style with the type attribute. Ordered lists are ideal for step-by-step instructions, rankings, and recipes.
<table>
The <table> element displays tabular data in rows and columns. A well-structured table uses <thead> for column headers, <tbody> for the main data, <tr> for each row, <th> for header cells, and <td> for regular data cells. Tables should only be used for genuinely tabular data — never for page layout, which is what CSS Grid and Flexbox are for.
<button>
The <button> element creates a clickable button that can trigger actions like submitting a form, resetting a form, or running custom JavaScript. Unlike <input type="button">, <button> can contain other HTML content such as icons or styled text, not just plain text. Its type attribute determines its default behavior within a form.
<input>
The <input> element creates interactive form controls for collecting user data. Its behavior changes dramatically based on the type attribute — a single element can become a text field, checkbox, radio button, date picker, file uploader, and more. It is a void (self-closing) element with no closing tag or child content.
<label>
The <label> element defines a caption for a form control, improving both usability and accessibility. Clicking a label activates or focuses its associated input — useful for small targets like checkboxes and radio buttons. Labels can be associated with an input either by wrapping it, or by using a for attribute that matches the input's id.
<textarea>
The <textarea> element creates a multi-line plain-text input control, ideal for comments, messages, and any content longer than a single line. Unlike <input>, its default value is placed between the opening and closing tags rather than in a value attribute, and users can typically resize it by dragging its corner.
<select>
The <select> element creates a dropdown list of options, letting users pick one or more predefined values. Each choice is defined with an <option> element inside it. Related options can be grouped visually using <optgroup>. It is a compact way to offer a constrained set of choices without the space a list of radio buttons would need.
<header>
The <header> element represents introductory content for its nearest ancestor sectioning element, typically containing a logo, site title, navigation, or search form. A page can have multiple <header> elements — one for the page itself, and others for individual <article> or <section> elements. It has no default visual styling of its own.
<nav>
The <nav> element marks a section of major navigation links, such as a main menu, table of contents, or pagination controls. Not every group of links needs to be a <nav> — reserve it for primary navigation blocks. Screen readers can identify <nav> regions, letting users jump straight to navigation or skip past it.
<footer>
The <footer> element represents closing content for its nearest ancestor sectioning element, typically containing copyright notices, contact information, related links, or author details. Like <header>, a page can have multiple footers — one for the whole page and others scoped to individual articles or sections.
<section>
The <section> element groups related content that typically has its own heading, representing a distinct thematic section of a document — like a chapter, tab panel, or a chunk of a landing page. Unlike <div>, which carries no semantic meaning, <section> tells browsers and assistive technology that its content forms a standalone, related group. If content does not have a natural heading or is not thematically distinct, a plain <div> is usually the better choice.
Text Formatting: <strong>, <em>, <b>, <i>, <mark>, <small>
HTML provides several inline elements for formatting text with semantic and visual meaning. <strong> indicates strong importance (typically rendered bold), and <em> indicates stress emphasis (typically rendered italic) — both carry semantic weight that screen readers can announce. <b> and <i> are their purely visual counterparts, used when bold/italic styling is needed without implying importance or emphasis. <mark> highlights text as relevant to the current context, and <small> represents side comments like fine print or disclaimers.
<br>, <hr>
These are two simple void (self-closing) elements for controlling text flow. <br> inserts a single line break within text, forcing the next content onto a new line without starting a new paragraph. <hr> represents a thematic break between paragraph-level content — visually rendered as a horizontal line, but semantically indicating a shift in topic, such as a scene change in a story or a new section.
<blockquote>, <q>
HTML provides two elements for quoting content from another source. <blockquote> is used for longer, block-level quotations that are typically set apart from surrounding text with indentation. <q> is used for shorter, inline quotations within a sentence, and browsers automatically render it with quotation marks. Both support a cite attribute pointing to the source URL.
<code>, <pre>, <kbd>
These elements are especially relevant for a developer-focused site like this one. <code> marks up a short inline fragment of computer code, typically rendered in a monospace font. <pre> preserves whitespace and line breaks exactly as written, making it ideal for displaying blocks of code or formatted text. <kbd> represents user keyboard input, commonly used in tutorials to show keyboard shortcuts. <pre> and <code> are frequently combined to display multi-line, syntax-preserved code blocks.
<article>
The <article> element represents a self-contained piece of content that could theoretically be distributed or reused independently — like a blog post, news story, forum post, or product card. The key test is whether the content would still make sense if syndicated on its own, separate from the rest of the page. Articles can be nested (e.g., a blog post article containing comment articles).
<main>
The <main> element represents the dominant, unique content of the document — the content that is directly related to the page's central topic, excluding repeated elements like headers, navigation, sidebars, and footers. There must be no more than one visible <main> element per page, and it should not be nested inside <article>, <header>, <footer>, <nav>, or <aside>.
<aside>
The <aside> element represents content that is tangentially related to the surrounding content, such as a sidebar, pull quote, advertisement, or a group of related links. It can be used both as a page-level sidebar and nested inside an <article> for content that is related to, but separate from, the main article text.
<figure>, <figcaption>
The <figure> element wraps self-contained content — typically an image, illustration, diagram, code snippet, or chart — along with an optional caption provided by <figcaption>. Content in a figure is meant to be referenceable independently of the main flow; a reader should be able to move it elsewhere on the page (or even to an appendix) without breaking the document's meaning.
<video>
The <video> element embeds video content directly in a web page without needing a third-party plugin. It supports built-in playback controls, multiple source formats via nested <source> elements for browser compatibility, and various attributes for controlling autoplay, looping, and muting.
<audio>
The <audio> element embeds sound content — music, podcasts, or sound effects — directly in a page. Like <video>, it supports multiple <source> elements for format fallback and built-in playback controls, without needing Flash or other plugins.
<iframe>
The <iframe> element embeds another HTML document within the current page, creating a nested browsing context. It is commonly used for embedding maps, videos from external platforms, payment widgets, or ads. Because it loads content from potentially untrusted sources, the sandbox attribute is important for restricting what an embedded page is allowed to do.
<meta>
The <meta> element provides metadata about the HTML document that is not displayed on the page itself — used for things like character encoding, viewport configuration, page descriptions for search engines, and social media preview data. Meta tags live inside the <head> and are void (self-closing) elements.
<link>
The <link> element establishes a relationship between the current document and an external resource, most commonly a stylesheet. It lives in the <head> and is a void element. Beyond stylesheets, <link> is also used for favicons, preloading resources, and specifying alternate versions of a page.
<script>
The <script> element embeds or references executable JavaScript code within an HTML document. It can contain inline code directly between its tags, or load an external file via the src attribute. Where scripts are placed and how they load (defer, async, or neither) significantly affects page load performance and execution order.
<details>, <summary>
The <details> element creates a native, collapsible disclosure widget — content that can be toggled open or closed by the user without any JavaScript. The <summary> element inside it defines the always-visible heading that acts as the toggle control. This is the standard way to build FAQ accordions or collapsible sections without hand-rolling the interaction logic.
<dialog>
The <dialog> element represents a native modal or non-modal dialog box, such as a confirmation prompt, settings panel, or alert. It comes with built-in modal behavior (via the showModal() JavaScript method) including a backdrop and focus trapping, removing the need to hand-build accessible modal logic from scratch.
<time>
The <time> element represents a specific date, time, or duration in a machine-readable format via its datetime attribute, while displaying a human-friendly version as its content. This lets browsers, search engines, and assistive technology understand dates unambiguously, even when the visible text is casual (like "yesterday" or "3 days ago").
<address>
The <address> element provides contact information for its nearest <article> or <body> ancestor. This might be a person, organization, or the author of the page, and typically includes things like an email, physical address, or social media link. It is not meant for arbitrary postal addresses that are not related to page authorship — use a plain <p> for those.
<abbr>
The <abbr> element marks up an abbreviation or acronym, with the title attribute providing the full expansion. Browsers typically show the expansion as a tooltip on hover, and screen readers can announce it, helping readers who are unfamiliar with the shortened term.
<fieldset>, <legend>
The <fieldset> element groups related form controls together, typically rendered with a visible border. The <legend> element provides a caption for the group, describing what the enclosed fields are collectively for. This is especially useful for grouping radio buttons, related checkboxes, or sections of a longer form like "Billing Address" versus "Shipping Address".
<progress>, <meter>
These two elements display quantities visually without needing custom-built progress bars. <progress> represents the completion progress of a task, like a file upload or multi-step form. <meter> represents a scalar value within a known range, like disk usage or a rating — it is for measuring a static value, not tracking progress toward completion.
<base>
The <base> element specifies a base URL and/or target for all relative URLs in a document. It must appear inside <head>, and a document should have no more than one <base> element. Once set, every relative link, image src, and form action on the page resolves against it unless individually overridden.
<dl>, <dt>, <dd>
The description list group represents a list of term/description pairs — like a glossary or metadata list. <dl> wraps the whole list, <dt> defines each term, and <dd> defines its associated description. Unlike <ul>/<ol>, description lists are not bulleted or numbered by default.
<cite>
The <cite> element references the title of a creative work — a book, article, song, movie, or research paper — not the author's name. Browsers typically render it in italics. It is often paired with <blockquote> or <q> to credit the source of a quotation.
<ins> and <del>
The <ins> element marks text that has been inserted into a document, typically rendered underlined. The <del> element marks text that has been deleted, typically rendered with strikethrough. Together they are commonly used to show tracked changes, edit history, or price updates, and both support cite and datetime attributes to document when and why the change was made.
<picture> and <source>
The <picture> element lets the browser choose the most appropriate image from multiple <source> options based on screen size, resolution, or format support, falling back to a required <img> element if none match. This is the standard way to serve responsive, art-directed, or next-gen image formats (like WebP or AVIF) with automatic fallback.
<canvas>
The <canvas> element provides a blank, resizable bitmap surface for drawing graphics, animations, and visualizations via JavaScript — typically using the Canvas 2D API or WebGL. Unlike SVG, canvas content is pixel-based rather than made of individually addressable DOM elements, which makes it well-suited for games, charts, and pixel-level image manipulation.
<embed> and <object>
The <embed> and <object> elements embed external content — like PDFs, other HTML pages, or browser plugins — into a document. <object> is the more capable and standards-based of the two, supporting fallback content between its tags, while <embed> is simpler but has no fallback mechanism. Modern use cases increasingly favor <iframe> for HTML content and dedicated elements like <img>, <video>, or <picture> where applicable.
<map> and <area>
Image maps let different regions of a single image act as separate clickable links. The <map> element defines the map, referenced from an <img> via its usemap attribute, and each <area> inside it defines one clickable region using coordinates and a shape.
<noscript>
The <noscript> element defines content to display only when JavaScript is disabled or unsupported in the browser. It commonly contains a message explaining that the page requires JavaScript, or a fallback version of functionality that would otherwise depend on scripting.
<output>
The <output> element represents the result of a calculation performed by a script, often used within a form to show a live computed value — like the result of a slider-driven calculation. It can be associated with the form controls that influence its value via the for attribute.
<datalist>
The <datalist> element provides a list of predefined autocomplete suggestions for an <input> element, without restricting the user to only those choices — unlike <select>, users can still type a custom value. It is connected to an input via a matching list attribute and id.
<sub> and <sup>
The <sub> element renders text as subscript (lowered and smaller), and <sup> renders text as superscript (raised and smaller). They are used for their actual typographic meaning — chemical formulas, mathematical exponents, ordinal indicators, and footnote references — not for general small text styling.
<samp> and <var>
The <samp> element represents sample output from a computer program, typically rendered in monospace. The <var> element represents a variable in a mathematical expression or programming context, typically rendered in italics. Both are semantic complements to <kbd> (keyboard input) and <code> (code itself) for accurately marking up technical writing.
<track>
The <track> element specifies timed text tracks for <video> or <audio> elements — most commonly subtitles or captions in WebVTT format. Multiple tracks can be provided for different languages, and the default attribute marks which one should be enabled automatically.
<style>
The <style> element contains embedded CSS rules that apply directly to the current document, as an alternative to linking an external stylesheet with <link>. It normally lives inside <head>, though the scoped nature of modern CSS means it can technically appear in body content too.
<title>
The <title> element defines the title of the document, shown in the browser tab, bookmarks, and search engine results. Every HTML document should have exactly one <title>, placed inside <head>. It must contain only text — no nested elements.
<menu>
The <menu> element is a semantic alternative to <ul>, intended specifically for lists of commands or interactive items — like a toolbar or context menu — rather than plain content lists. Browsers currently render it identically to <ul>, but it signals different intent to assistive technology and future tooling.
<search>
The <search> element is a relatively new HTML5 semantic element that identifies a section of the page containing search or filtering controls — either for the site itself or for the current page's content. It gives assistive technology a reliable landmark to jump straight to search functionality.
<svg>
The <svg> element embeds Scalable Vector Graphics directly in HTML — vector-based images built from shapes, paths, and text rather than pixels, so they stay crisp at any size. Unlike canvas, SVG content is made of real DOM elements that can be styled with CSS and targeted with JavaScript individually, making it ideal for icons, logos, and interactive diagrams.
<s> and <u>
The <s> element represents text that is no longer accurate or relevant — like an outdated price or a crossed-out item — rendered with strikethrough. The <u> element represents text with a non-textual annotation, such as marking a misspelled word or a proper name, rendered underlined. Neither implies emphasis or importance the way <strong>/<em> do.
<body>
The <body> element contains all the visible content of an HTML document — text, images, links, forms, and everything a user actually sees and interacts with in the browser. There can only be one <body> per document, and it must come after the <head> element. Unlike <head>, which holds metadata, everything inside <body> is rendered on the page.
<head>
The <head> element contains metadata about the document — information that is not displayed directly on the page but is used by browsers, search engines, and other tools. This includes the page <title>, character encoding, linked stylesheets, scripts, and social media preview data. It must come before <body> and contains no visible content itself.
<bdi> and <bdo>
These elements handle bidirectional text — content that mixes left-to-right languages (like English) with right-to-left languages (like Arabic or Hebrew). <bdi> isolates a piece of text so its directionality does not affect surrounding text, useful for user-generated content like usernames where the language is unknown ahead of time. <bdo> explicitly overrides the natural text direction for its content.
<col> and <colgroup>
The <colgroup> element groups one or more columns in a table for the purpose of applying styles, and <col> represents a single column within that group. This lets you style an entire column — like setting a background color or width — without adding a class to every individual cell in that column.
<dfn>
The <dfn> element marks the defining instance of a term — the specific place in the text where a term is first introduced and explained. Browsers typically render it in italics. It differs from <abbr> in that dfn is about introducing a concept or vocabulary word, not expanding an abbreviation.
<hgroup>
The <hgroup> element groups a heading with one or more subheadings or taglines, treating them as a single unit in the document outline. It is commonly used to pair a main title with a subtitle, so the subtitle does not get counted as its own separate heading level by accessibility tools.
<li>
The <li> element represents an individual item within a list — <ul>, <ol>, or <menu>. Its rendering depends on its parent: inside <ol>, browsers add sequential numbering; inside <ul>, they add bullet points. The value attribute lets you override an item's number specifically within an ordered list.
<optgroup> and <option>
The <option> element defines a single choice within a <select> dropdown or a <datalist>. The <optgroup> element groups related options together under a shared label, making long dropdowns easier to scan. Each option's value attribute is what actually gets submitted with the form, while its text content is what the user sees.
<ruby>, <rt>, <rp>
Ruby annotations display small pronunciation or translation text above (or next to) East Asian characters, commonly used for showing furigana over Japanese kanji or pinyin over Chinese characters. The <ruby> element wraps the base text and its annotation, <rt> holds the annotation text itself, and <rp> provides fallback parentheses for browsers that do not support ruby rendering.
<wbr>
The <wbr> (word break opportunity) element tells the browser where it is allowed to insert a line break if needed, without forcing one. It is useful for long unbroken strings like URLs or compound words that would otherwise overflow their container without any natural spaces to break on.
<data>
The <data> element links a piece of content with a machine-readable value via its value attribute, similar in spirit to <time> but for values other than dates — like product IDs, prices, or measurements. This lets scripts and other tools programmatically access the underlying value while humans see the friendly, formatted text.
<template>
The <template> element holds HTML content that the browser parses but does not render or execute when the page loads. Its content is inert — scripts inside it will not run, and images inside it will not load — until it is cloned into the visible DOM via JavaScript. This makes it a clean way to define reusable markup fragments for dynamic UI without building HTML strings in JavaScript.
HTML template Element
The template element holds inert document fragments. Its contents are not rendered until JavaScript clones and inserts them into the document.
Declaring Document and Content Languages
The lang attribute identifies the natural language of an element and its descendants. Screen readers, spellcheckers, translation tools, and CSS language selectors can use it. Set a document default and override it where a passage changes language; lang does not translate text.
Text Direction with dir
The dir attribute declares left-to-right, right-to-left, or automatically detected text direction. It affects text layout and remains meaningful without CSS. dir="auto" is useful for user-entered text whose first strong directional character should choose the base direction.
Custom Data Attributes and dataset
Attributes beginning with data- attach application-specific string values to elements. JavaScript exposes them through dataset, converting dash-separated names to camelCase. They are useful for small UI metadata, but they are visible to visitors and do not provide secure storage.
Toggling Content with hidden
The hidden attribute marks content that is currently irrelevant and should not be rendered. The DOM node still exists and scripts can access it. For ordinary hidden content, assigning the hidden property toggles its visibility. This differs from visually hiding content while preserving it for assistive technology.
Disabling an Entire Region with inert
The inert attribute makes an element and its descendants unavailable for user interaction, sequential focus, and accessibility exposure. It is useful when an interface region must be temporarily inactive. It does not add a visual disabled style or prevent scripts from changing its content; older browsers need a fallback.
Managing Focus with tabindex
tabindex controls whether an element participates in keyboard focus navigation. Zero places an otherwise nonfocusable element in normal tab order; minus one permits programmatic focus without adding a tab stop. It does not give a generic element the keyboard behavior or semantics of a native button.
Editable Content with contenteditable
contenteditable enables editing inside an HTML element. Unlike a textarea, an editable region is not automatically a named form control. Read its content deliberately and decide how to handle pasted markup. This example treats the editor as text and displays the result with textContent.
Escaping Markup with Character References
Character references represent characters that would otherwise be interpreted as markup or attribute delimiters. Common examples are <, &, and ". Correct escaping depends on the destination context; HTML escaping alone is not a universal defense for JavaScript, CSS, or URL contexts.
DOCTYPE and Standards Mode
The modern HTML doctype requests no-quirks rendering mode. Omitting it can trigger compatibility behavior intended for old pages. The doctype is a document preamble rather than an element, and it does not select a versioned HTML schema or import a DTD.
Form Autofill with autocomplete
autocomplete tokens describe the meaning of form values so browsers can offer appropriate autofill. Tokens such as name, email, and shipping postal-code identify data purpose more precisely than an input’s visual label. Autofill availability depends on browser settings and stored user data.
Mobile Keyboard Hints: inputmode and enterkeyhint
inputmode suggests a virtual keyboard suited to the expected input, while enterkeyhint suggests the enter-key label or action icon. These are hints, not validation rules. They are particularly useful for identifiers that contain digits but should remain strings, such as one-time codes with leading zeroes.
Native Form Constraint Validation
HTML form constraints such as required, min, max, step, and pattern allow browsers to check values before ordinary submission. reportValidity() both checks constraints and requests feedback. Validation messages and UI vary across browsers; client-side checks never replace server-side validation.
Controls Outside Their Form
A form-associated element can use the form attribute to reference a form by ID even when it is not nested inside that form. This supports layouts with a separate action bar. Association is explicit per control and is not inherited from a parent fieldset.
disabled versus readonly Controls
disabled controls cannot be edited or normally focused and are omitted from form submission. readonly prevents editing on supported text-like controls but leaves their values available to submission and generally allows focus and copying. readonly does not apply to checkboxes or select elements.
Checkbox Groups and Submitted Values
Checked checkboxes contribute their name and value to form data; unchecked boxes contribute no entry. Multiple checked boxes can share a name to submit multiple values. FormData.getAll() preserves the full group, whereas get() returns only the first matching value.
Selecting Files with accept and multiple
A file input asks the user to choose local files. accept filters or hints the chooser’s file types, and multiple permits more than one selection. Neither guarantees file content or safety. Browsers intentionally do not let a page silently select arbitrary files from a visitor’s disk.
Download Links and Suggested Filenames
The download attribute suggests downloading a linked resource and optionally provides a filename. It is reliable for same-origin resources and blob/data URLs; cross-origin handling and final filenames depend on browser policy and server headers. A download hint does not guarantee a particular save dialog.
New-tab Links: noopener and noreferrer
rel="noopener" prevents a newly opened browsing context from receiving an opener relationship through the link. noreferrer also suppresses the Referer header and implies noopener. Modern browsers generally treat target="_blank" as noopener by default; explicit attributes document intent and help with older clients.
Declarative Popover Controls
The popover attribute and popovertarget buttons create a nonmodal top-layer panel without JavaScript. An auto popover supports light dismissal and Escape dismissal. It does not automatically become a menu or dialog, and older browsers may need a fallback; check support before depending on this interaction.
Slots in a Shadow DOM Component
A slot is a placeholder inside a shadow tree where a component’s light-DOM children can be presented. Named slots distribute elements whose slot attributes match; fallback content appears when no matching node is assigned. Slots require a shadow tree and have no distribution behavior in ordinary page markup.
Responsive Images with srcset and sizes
Use img srcset to offer image files at different intrinsic widths and sizes to describe how wide the image will appear at different viewport widths. The browser chooses a candidate using that display size and device pixel density; src is a fallback. This is for alternative resolutions of the same image, while picture is better when the crop or composition must change.
Native Image and Iframe Lazy Loading
The loading attribute can hint that an off-screen image or iframe should be fetched later. Use loading="lazy" for content below the initial viewport, and leave important above-the-fold content eager. Browsers decide when to fetch nearby resources; the hint does not promise an exact request time or replace correct image dimensions and alternative text.
Different Form Actions with Submit Buttons
A submit button can override its form’s action or method with formaction and formmethod. This supports actions such as previewing a draft with GET and publishing with POST from the same form. The override belongs to the clicked submitter; a plain button without overrides uses the form settings. A server must still validate input and authorise the requested action.
Controlling Translation with translate
The global translate attribute marks whether text and certain attribute values should be translated during localisation. translate="no" is useful for names, commands and other text that must stay exact. It is a hint for localisation tools, not a language selector or a command that translates the page; use lang to declare the actual content language.
Spellcheck Hints for Editable Text
The global spellcheck attribute can request spelling and grammar checking for editable text or disable it where suggestions would be distracting, such as identifiers. Use the exact values "true" or "false"; spellcheck="false" is not the same as simply adding a boolean attribute. Browser preferences, dictionaries and platform UI still affect what users actually see.
CSS documentation
Introduction to CSS
Start here to understand what CSS is, how it styles HTML, how browsers apply its rules, and why it matters for readable, responsive websites.
Create your first CSS stylesheet
Make index.html and styles.css, connect them with a relative path, and see your first CSS declarations change a webpage.
Understand CSS rules and declarations
Learn to read a CSS rule from its selector through its property-value declarations, braces, colons, semicolons and comments.
Inline, internal and external CSS
Compare the three common ways to add CSS to HTML and understand how the cascade resolves competing declarations.
CSS Inheritance and Reset Keywords
Learn why text styles often pass from parent to child while borders and margins do not, and how CSS-wide keywords change that behaviour.
Hiding Content with CSS
Compare three ways to hide an element and learn how each affects layout, interaction and accessibility.
Light and Dark Color Schemes
Build a small page that follows a light or dark preference while keeping text and browser controls readable.
Styles for Printing and PDF
Make a webpage easier to print or save as PDF with targeted print rules and realistic preview testing.
Debug CSS with Browser DevTools
Find why a CSS rule is missing or overridden using the browser’s element inspector, Styles pane and computed values.
How the CSS Cascade Chooses a Style
Follow the practical order in which CSS resolves competing declarations, from relevant rules to layers, specificity and source order.
Flexbox
Flexbox (Flexible Box Layout) is a powerful one-dimensional layout system in CSS that makes it easy to design flexible and responsive layouts. It provides an efficient way to distribute space and align items in a container, even when their sizes are unknown or dynamic. Flexbox is particularly useful for creating navigation bars, card layouts, and centering content.
CSS Grid
CSS Grid is a powerful two-dimensional layout system that provides precise control over both rows and columns simultaneously. Unlike Flexbox which is one-dimensional, Grid excels at creating complex layouts with explicit row and column structures. It's ideal for page layouts, image galleries, and any design requiring both horizontal and vertical alignment.
The Box Model
Every element in CSS is a rectangular box made up of four layers, from innermost to outermost: content, padding, border, and margin. Understanding the box model is fundamental to controlling layout - it explains exactly how much space an element actually occupies and how that space is distributed.
box-sizing
box-sizing controls how an element's total width and height are calculated. The default, content-box, means padding and border are added on top of the declared width, making sizing math confusing. border-box includes padding and border within the declared width instead, which is why nearly every modern CSS reset sets it globally.
display Property
The display property determines how an element generates boxes and participates in layout. block elements start on a new line and fill available width. inline elements flow within text and ignore width/height. inline-block combines inline flow with block-like sizing control. none removes the element from layout entirely.
position Property
The position property controls how an element is positioned in the document. static is the default, following normal flow. relative positions an element relative to its normal position. absolute removes it from flow entirely, positioning it relative to its nearest positioned ancestor. fixed positions relative to the viewport, staying in place during scroll. sticky toggles between relative and fixed based on scroll position.
overflow Property
overflow controls what happens when content is too large to fit its container. visible (default) lets content spill out. hidden clips anything beyond the box. scroll always shows scrollbars. auto adds scrollbars only when needed. overflow-x and overflow-y control each axis independently.
float and clear
float was CSS's original tool for wrapping text around an image or building multi-column layouts, pulling an element to one side while other content flows around it. clear stops an element from wrapping around floated siblings. Flexbox and Grid have replaced float for layout purposes, but float is still legitimately used for wrapping text around images.
Flex Item Properties
While display: flex controls the container, individual flex items have their own properties for fine-grained control. flex-grow, flex-shrink, and flex-basis (usually combined via the flex shorthand) control how an item grows or shrinks to fill space. order changes visual order without touching the HTML. align-self overrides the container's align-items for a single item.
grid-template-areas
grid-template-areas lets you visually lay out a grid using named regions written directly in your CSS, making complex page layouts remarkably readable. Each string represents a row, each word represents a named area, and child elements are placed into an area using grid-area, matching the visual shape of your layout with the code itself.
Grid Alignment: place-items, place-content
Grid alignment properties control how content is positioned within grid cells and how the grid itself is positioned within its container. justify-items/align-items control individual item alignment along each axis, and their shorthand place-items sets both at once. justify-content/align-content position the whole grid when it is smaller than its container, with place-content as their shorthand.
Container Queries
Container queries let an element style itself based on the size of its containing element, rather than the viewport. This solves a problem media queries never could: a truly reusable component that looks right whether it is placed in a narrow sidebar or a wide main content area. Declare a container with container-type, then respond to it with @container.
Font Properties
Core typography properties control how text is displayed. font-family sets the typeface (with fallbacks), font-size controls size, font-weight controls boldness, font-style controls italics, and the font shorthand can set several of these at once. Well-chosen typography is one of the highest-impact, lowest-effort improvements you can make to a design.
Text Properties
Beyond font selection, CSS offers properties to control text alignment, decoration, spacing, and casing. text-align positions text horizontally, text-decoration adds underlines/strikethroughs, text-transform changes casing, and letter-spacing/word-spacing adjust character and word gaps.
line-height and Vertical Spacing
line-height controls the vertical space a line of text occupies, directly affecting readability. Unitless values (like 1.5) are generally preferred over fixed units, since they scale proportionally with font-size rather than creating an inconsistent fixed gap.
Color Values
CSS supports several ways to specify color: named colors, hexadecimal, rgb()/rgba(), hsl()/hsla(), and the modern color functions oklch() and color-mix(). All accept an alpha channel for transparency. oklch() is increasingly preferred because it produces more perceptually uniform, predictable color adjustments than older formats.
Background Properties
Background properties control an element's background color and image. background-image sets one or more images, background-size controls their scaling, background-position controls placement, and background-repeat controls tiling. Multiple backgrounds can be layered by comma-separating values.
Gradients
CSS gradients generate smooth transitions between colors without needing an image file. linear-gradient() transitions along a straight line/angle, radial-gradient() transitions outward from a center point, and conic-gradient() transitions around a center point like a color wheel. Gradients are used as background-image values.
Border Properties
border draws a line around an element's edge, controlled by width, style, and color, which can be set together via the border shorthand or individually per side (border-top, border-right, etc). border-radius rounds the corners, accepting one value for all corners or up to four for individual control.
box-shadow
box-shadow adds one or more drop shadows to an element's box, accepting horizontal offset, vertical offset, blur radius, optional spread radius, and color. The inset keyword flips the shadow to render inside the element instead of outside. Multiple shadows can be layered by comma-separating values, useful for realistic elevation effects.
Transitions
Transitions smoothly animate a property change over a specified duration, rather than the change happening instantly. They require a property to transition, a duration, and typically a timing function that controls the pace of the animation - useful for hover effects, state changes, and general UI polish.
Animations & @keyframes
@keyframes defines a named sequence of styles at different points (0% to 100%) of an animation, which is then applied to an element via the animation property. Unlike transitions, which only animate between two states, keyframe animations can define arbitrarily complex multi-step sequences and loop indefinitely.
Transforms
transform lets you visually move, rotate, scale, or skew an element without affecting the document flow of surrounding elements - unlike changing position/width directly. Multiple transform functions can be combined in a single declaration, and transform-origin controls the pivot point for rotation and scaling.
Filters
The filter property applies graphical effects like blur, brightness, contrast, and grayscale directly to an element, similar to Photoshop-style filters. backdrop-filter applies the same effects to the area behind an element instead, commonly used for frosted-glass UI effects. Multiple filter functions can be chained together.
Length Units: px, %, em, rem
CSS offers several length units. px is an absolute, fixed unit. % is relative to the parent element. em is relative to the current element's font-size (compounding when nested). rem is relative to the root (html) element's font-size, avoiding the compounding problem of em, and is generally preferred for consistent, predictable sizing.
Viewport Units: vh, vw, dvh
Viewport units are relative to the browser window's dimensions rather than a parent element. vh and vw represent 1% of the viewport height and width respectively. The newer dvh (dynamic viewport height) solves the classic mobile browser problem where vh included space later covered by the address bar.
calc(), min(), max(), clamp()
These functions let you compute CSS values dynamically. calc() performs math between different units. min() and max() pick the smallest or largest of a list of values. clamp(min, preferred, max) is especially powerful for fluid, responsive sizing - it uses the preferred value but never goes below min or above max.
Basic Selectors
CSS selectors target elements to style. Type selectors match by tag name, class selectors (.name) match elements with that class, ID selectors (#name) match a single unique element, and the universal selector (*) matches everything. Classes are the most commonly used selector for reusable styling.
Combinators
Combinators define relationships between selectors. The descendant combinator (space) matches any nested element. The child combinator (>) matches only direct children. The adjacent sibling combinator (+) matches the very next sibling. The general sibling combinator (~) matches all following siblings.
Attribute Selectors
Attribute selectors target elements based on the presence or value of an HTML attribute, using square bracket syntax. They support several matching modes beyond exact equality, including starts-with, ends-with, and contains, making them powerful for targeting elements without needing extra classes.
:has() - The Parent Selector
:has() matches an element if any of the selectors passed to it match something within it - effectively letting you style a parent based on its children or descendants, something CSS could never do natively before. It has broad, mainstream browser support as of 2026 and is safe to use in production.
:is() and :where()
:is() and :where() both accept a list of selectors and match any of them, letting you write more compact selector groups. The key difference is specificity: :is() takes on the specificity of its most specific argument, while :where() always contributes zero specificity, making its rules trivially easy to override.
Native CSS Nesting
Native CSS nesting lets you write selectors inside other selectors, similar to what Sass offered for years, but now supported directly in browsers with no build step required. The & symbol explicitly references the parent selector, useful for pseudo-classes, modifiers, and compound selectors.
Interactive Pseudo-classes
These pseudo-classes style elements based on user interaction state. :hover applies while the pointer is over an element, :focus while it has keyboard focus, :active during the moment of being clicked/pressed, and :visited for links the user has already navigated to.
:focus-visible and :focus-within
:focus-visible applies only when the browser determines focus should be visibly indicated - typically keyboard navigation, not a mouse click - solving the old complaint of unwanted focus rings on click. :focus-within applies to a parent element when any descendant inside it has focus, useful for highlighting an entire form group when one of its fields is active.
Form State Pseudo-classes
CSS can style form elements based on their validation and interaction state without any JavaScript. :checked applies to checked checkboxes/radios, :disabled to disabled fields, :required and :optional based on the required attribute, and :valid/:invalid based on constraint validation results.
Pseudo-elements
Pseudo-elements let you style a specific part of an element rather than the whole thing, or insert generated content without adding extra HTML. ::before and ::after insert content before/after an element's actual content. ::first-line and ::first-letter target specific text portions. ::placeholder styles input placeholder text, and ::selection styles user-highlighted text.
Structural Pseudo-classes: nth-child()
Structural pseudo-classes select elements based on their position among siblings, without needing extra classes. :first-child and :last-child match the first/last element. :nth-child() accepts a formula (like 2n for even, 2n+1 for odd) or a simple number, letting you target patterns like every third item or striped table rows.
Specificity
When multiple CSS rules target the same element with conflicting declarations, specificity determines which one wins. It is calculated as a four-part value: inline styles, ID selectors, class/attribute/pseudo-class selectors, and type/pseudo-element selectors, compared in that order from most to least significant.
Cascade Layers (@layer)
@layer lets you explicitly define the priority order between groups of CSS rules, independent of selector specificity. Styles in a layer declared later always beat styles in an earlier layer, regardless of how specific the earlier layer's selectors are - solving specificity conflicts between resets, frameworks, components, and overrides in a predictable, structured way.
Custom Properties (CSS Variables)
Custom properties, written as --name, let you define reusable values directly in CSS, accessed with var(). Unlike Sass variables, they are live in the browser - they can be read and changed with JavaScript, and they respect the cascade, meaning their value can be different in different parts of the DOM.
Media Queries
Media queries apply CSS conditionally based on characteristics of the device or viewport, most commonly width, forming the foundation of responsive design. They use the @media at-rule with a condition, and can be combined with and/or logic to test multiple conditions at once.
prefers-color-scheme & prefers-reduced-motion
These media queries detect user system preferences rather than device characteristics. prefers-color-scheme detects whether the user has requested a light or dark theme at the OS level. prefers-reduced-motion detects whether the user has requested minimal animation, important for users with vestibular motion sensitivity.
z-index and Stacking Context
z-index controls which element appears on top when elements overlap, but only works on positioned elements (anything other than static). Stacking contexts group elements together for z-index comparison purposes - z-index values only compete within the same stacking context, which is why a very high z-index can sometimes mysteriously fail to appear on top.
Subgrid
subgrid lets a nested grid container inherit the track sizing of its parent grid, instead of defining its own independent tracks. This solves a long-standing alignment problem: getting content in different, unrelated grid items (like card headers and footers) to line up perfectly across a row.
Sizing: width, min/max-width
Beyond a fixed width, CSS offers min-width and max-width to set flexible boundaries - an element can shrink or grow within those limits. This is fundamental to responsive design, letting content adapt fluidly while never becoming unreadably narrow or unreasonably wide.
Logical Properties
Logical properties describe direction in terms of writing mode (inline/block flow) rather than fixed physical directions (left/right/top/bottom). margin-inline-start behaves like margin-left in English but automatically adapts for right-to-left languages, making them essential for properly internationalized layouts.
aspect-ratio
aspect-ratio sets a preferred width-to-height ratio for an element, letting the browser automatically calculate one dimension from the other. This replaced older, hackier techniques (like the "padding-top trick") for maintaining consistent proportions on responsive elements like video embeds and images.
object-fit and object-position
object-fit controls how a replaced element's content (like an <img> or <video>) is resized to fit its box, similar to background-size but for actual media elements. cover crops to fill the box, contain scales to fit entirely within it, and object-position controls which part of the content stays visible when cropping occurs.
List Styling
list-style controls how list markers (bullets or numbers) appear on <ul>/<ol> elements. list-style-type sets the marker style, list-style-position controls whether markers sit inside or outside the content box, and list-style: none is the standard way to remove markers entirely, commonly used when repurposing a list for navigation.
scroll-behavior and Scroll Snap
scroll-behavior: smooth animates scrolling to anchors instead of jumping instantly. Scroll snap properties (scroll-snap-type and scroll-snap-align) create carousel-like scrolling where content snaps neatly into position, commonly used for image galleries and full-page sections, without any JavaScript.
Progressive Enhancement with @supports
@supports tests whether the browser accepts a CSS declaration or supported selector syntax. It allows enhanced styles to accompany a simpler fallback. A successful feature query confirms recognized syntax, not that a feature is free from bugs or suitable for every accessibility need.
Custom Fonts with @font-face
@font-face names a font resource that can be used by font-family. A font-display strategy controls the rendering period while a web font loads. Match declared weight and style to the supplied font file; cross-origin font downloads also require appropriate server CORS headers.
Numbering Sections with CSS Counters
CSS counters maintain numbering in the document’s style tree. counter-reset creates or resets a counter, counter-increment advances it, and counter() formats its current value. Generated numbering is useful for presentation, but critical content should remain available in semantic HTML.
Flowing Text into Multiple Columns
Multi-column layout flows one continuous content stream down columns, similar to a newspaper. The columns shorthand can request an ideal width and a maximum count. It is different from Grid, where separate items occupy explicit cells.
Controlling Page and Column Breaks
break-before, break-after, and break-inside guide fragmentation across printed pages and multi-column containers. Avoid values request that related content stay together, but oversized boxes and layout constraints can force a break. These properties do not create pagination on an ordinary scrolling screen.
Vertical Layout with writing-mode
writing-mode chooses the direction in which lines are stacked and whether text runs horizontally or vertically. text-orientation controls glyph orientation in vertical lines. Logical dimensions and spacing follow the writing mode, making them useful for multilingual layouts.
Preserving and Wrapping Whitespace
white-space controls whether spaces and line breaks are collapsed and whether lines wrap. pre preserves spacing without ordinary wrapping, while pre-wrap preserves spacing and still allows wrapping. This is useful for notes, logs, and user text where line breaks carry meaning.
Wrapping Long Words and Identifiers
overflow-wrap allows otherwise unbreakable strings to wrap when needed. anywhere also affects intrinsic minimum sizing, helping content fit narrow Grid or Flexbox items. hyphens: auto uses language-sensitive hyphenation when the browser has an appropriate dictionary; it is not guaranteed for every language.
Single-line Truncation with text-overflow
text-overflow: ellipsis draws a truncation marker for clipped inline content. It does not itself create overflow or prevent wrapping. A typical single-line pattern combines a constrained width, overflow: hidden, and white-space: nowrap.
Text Decoration Thickness and Offset
Text decoration properties control underline style, color, thickness, and offset. text-decoration-skip-ink lets underlines avoid letter descenders where supported. Underlines remain a valuable cue for links, especially when color differences alone are difficult to perceive.
Outlines without Layout Changes
An outline is drawn around an element without taking up layout space like a border. outline-offset moves it away from the edge. It is particularly useful for visible keyboard focus because adding it does not shift neighboring content.
Native Form Accents with accent-color
accent-color requests an accent for supported native controls such as checkboxes, radio buttons, ranges, and progress bars. Browsers retain their native control behavior and can adjust rendering for contrast. Exact appearance and supported controls vary by engine and operating system.
Styling the Text Insertion Caret
caret-color changes the insertion caret in editable controls and contenteditable regions. It changes neither the text color nor the selection highlight. A visible caret helps users locate where their next character will be inserted.
User-resizable Regions with resize
resize lets users change an eligible box’s dimensions through a browser-provided affordance. It commonly applies to textareas or boxes with non-visible overflow. min/max dimensions constrain resizing. The exact affordance and touch support depend on the browser.
Pointer Hit Testing with pointer-events
pointer-events: none removes an element from pointer hit testing, allowing clicks to reach content underneath. It does not disable keyboard focus or inherently make an element inaccessible. Use disabled or inert when the intent is to disable interaction rather than let pointer events pass through.
Controlling Text Selection with user-select
user-select adjusts whether and how text can be selected. all requests atomic selection of an element’s content, while none suppresses normal text selection. It does not prevent copying through scripts or developer tools and should not be treated as content protection.
Containing Blend Effects with isolation
mix-blend-mode blends an element with its backdrop. isolation: isolate creates a new isolated blending group so its descendants do not unexpectedly blend with content outside that group. This is useful for overlapping decorative shapes and illustrations.
Clipping Boxes with clip-path
clip-path restricts an element’s visible region to a shape or referenced clipping path. Basic shapes such as circle() and polygon() provide responsive decorative crops. Clipping affects rendering and hit testing, but does not change the element’s rectangular layout footprint.
Fading Graphics with CSS Masks
A CSS mask controls visibility using the alpha or luminance of another image. A gradient mask can fade a graphic without changing its underlying colors. Modern engines support unprefixed mask properties; older WebKit-based browsers may require prefixed forms.
Rendering Containment and content-visibility
contain describes boundaries the browser can rely on when performing layout and painting. content-visibility: auto allows off-screen rendering work to be skipped while keeping content available to find-in-page and accessibility. contain-intrinsic-size supplies a placeholder size when rendering is skipped; measure performance instead of assuming improvement.
Grid auto-fit versus auto-fill
auto-fit and auto-fill repeat grid tracks as many times as fit in the container.
Flexible Grid Tracks with minmax
minmax sets a minimum and maximum track size rather than one fixed width.
Named Grid Lines
Grid line names label boundaries between tracks.
Dense Grid Packing and Reading Order
Dense auto-placement lets the grid algorithm revisit earlier gaps when a later item can fit.
Why Flex Items Sometimes Refuse to Shrink
A flex item’s automatic minimum size can prevent it from shrinking enough to fit beside a sibling.
Alignment with Flex Auto Margins
An auto margin on a flex item absorbs available space on its axis before ordinary alignment is applied.
Spacing Flex Items with gap
gap supplies spacing between flex items and flex lines without adding margins around the container’s outside edges.
Flex order and Accessible Sequence
The order property changes the order in which flex items are laid out visually.
Containing Floats with flow-root
flow-root establishes a new block formatting context.
Understanding Vertical Margin Collapse
Adjacent block margins can collapse into a combined margin instead of adding together.
Sticky Positioning inside a Scroll Container
Sticky positioning keeps a box in normal flow while constraining its position relative to its scroll container and containing block.
Transforms and Fixed-Position Containing Blocks
A fixed-position element usually uses the viewport as its containing block, but certain ancestor properties change that relationship.
overflow: clip versus hidden
Both clip and hidden can hide content outside a box, but they differ in scrolling behaviour.
Reserving Space for Scrollbars
scrollbar-gutter can reserve space for a classic scrollbar so content width changes less when scrolling becomes necessary.
Containing Scroll Chaining
Scroll chaining can move an outer page when an inner scrolling panel reaches its boundary.
Space around Scroll Targets
scroll-margin expands the effective area used around a target for relevant scrolling operations and snapping.
Insets for a Scrolling Region
scroll-padding describes an inset from a scroll container’s scrollport for relevant scroll positioning and snapping.
Controlling Snap Skipping
scroll-snap-stop controls whether certain scrolling operations may pass over an item’s snap position.
Declaring Touch Gesture Behaviour
touch-action tells the browser which default touch gestures are permitted in a region.
Hover and Pointer Capability Queries
The hover and pointer media features describe capabilities of the primary pointing device rather than a screen size or device brand.
Supporting Forced-Colors Mode
Forced-colors mode lets a browser replace many author colours with a user-selected palette.
Responding to prefers-contrast
prefers-contrast reports a user preference for a different level of contrast.
Highlighting Fragment Targets with :target
:target selects the element identified by the current document URL’s fragment.
Selecting Empty Elements with :empty
:empty is useful for styling containers that contain no element children or non-empty text nodes under widely implemented behaviour.
Excluding Matches with :not
:not matches elements that do not match its argument.
Filtered Counting with :nth-child of
The of selector clause makes :nth-child count only siblings matching a chosen selector.
Styling List Markers with ::marker
::marker targets the marker box of a list item, such as its bullet or counter.
Styling Input Placeholders
::placeholder styles the placeholder text shown by supported empty form controls.
Styling the Native File Picker Button
::file-selector-button targets the button inside a file input.
Text Selection Colours with ::selection
::selection styles supported aspects of text selected by the user.
Gradient Text with a Solid Fallback
Text-clipped backgrounds can fill letter shapes with a gradient.
Multiple Background Layers
An element can paint several background layers separated by commas.
Gradient Borders with border-image
border-image paints a border using an image and slicing rules instead of only a solid border colour.
Elliptical Corner Radii
The slash form of border-radius separates horizontal and vertical corner radii.
Decorations across Line Breaks
An inline box can split into fragments when its text wraps across lines.
Balanced Heading Wrapping
Balanced wrapping asks the browser to distribute text more evenly across a limited set of lines.
Progressive Text Wrapping with pretty
Pretty wrapping allows a browser to spend more effort improving line breaks, often avoiding an isolated short final word where its implementation supports that optimisation.
Aligned Numbers with font-variant-numeric
Numeric font variants request specialised digit forms supported by the chosen font.
Displaying Tabs with tab-size
tab-size controls the advance of tab characters in text whose whitespace is preserved.
Readable Underlines with text-decoration-skip-ink
Underline ink skipping lets the line avoid areas where it would collide with glyph ink, such as descenders.
JavaScript documentation
Introduction to JavaScript
Start here: learn where JavaScript came from, how browsers and Node.js run it, and what people build with it.
Install Node.js on Windows
Install a supported Node.js release on Windows and run your first JavaScript file from PowerShell.
Install Node.js on macOS
Install a supported Node.js release on macOS and execute a saved JavaScript file from Terminal.
Install Node.js on Linux
Choose a supported Node.js release on Linux, check npm, and run a .js file from the shell.
npm and your first JavaScript project
Learn what npm installs, what package.json records, and how to manage a small Node.js project.
Set up JavaScript in Visual Studio Code
Create, run and debug a JavaScript project in VS Code, with or without Node.js.
Set up JavaScript in WebStorm
Create, run and debug JavaScript projects in WebStorm, and understand when a Node runtime is needed.
How HTML, CSS and JavaScript work together
Build a small page that changes text when you click a button, and see the separate job of each web technology.
JavaScript vs TypeScript
Compare JavaScript and TypeScript code, type checking, tools, runtime behaviour and when each language fits.
JavaScript in the Codectionary Playground
Open the Playground, run JavaScript in its browser preview, read Console output and errors, and understand its limits.
Arrow Functions
Arrow functions provide a more concise syntax for writing function expressions in JavaScript. Introduced in ES6, they use the => syntax and have some important differences from regular functions, particularly in how they handle the "this" keyword. Arrow functions are especially useful for callbacks, array methods, and short inline functions.
Async/Await
Async/await is modern JavaScript syntax for handling asynchronous operations, making asynchronous code look and behave like synchronous code. The async keyword marks a function as asynchronous, and await pauses execution until a Promise resolves. This approach makes asynchronous code more readable and easier to understand than traditional Promise chains or callbacks.
Variables: var, let, const
JavaScript has three ways to declare variables. var is the original way, function-scoped and hoisted with a default value of undefined. let, introduced in ES6, is block-scoped and can be reassigned. const is also block-scoped but cannot be reassigned after its initial value is set. Modern JavaScript strongly favors let and const over var.
Data Types
JavaScript has seven primitive data types - string, number, boolean, undefined, null, bigint, and symbol - plus the object type, which includes arrays, functions, and plain objects. JavaScript is dynamically typed, meaning a variable can hold any type and that type can change. The typeof operator reports a value's type at runtime.
Arithmetic Operators
Arithmetic operators perform mathematical calculations on numbers: addition (+), subtraction (-), multiplication (*), division (/), remainder/modulo (%), and exponentiation (**). The + operator also performs string concatenation when either operand is a string. Increment (++) and decrement (--) adjust a variable by one.
Assignment Operators
Assignment operators assign values to variables. Beyond the basic = operator, compound assignment operators combine an operation with assignment in one step, like += to add and assign. Logical assignment operators (&&=, ||=, ??=), introduced more recently, combine a logical check with assignment.
Comparison Operators
Comparison operators compare two values and return a boolean. == and != perform type coercion before comparing (loose equality), while === and !== compare both value and type without coercion (strict equality). Relational operators (<, >, <=, >=) compare numeric or string ordering.
Logical Operators
Logical operators combine or invert boolean expressions. && (AND) returns the first falsy value or the last value if all are truthy. || (OR) returns the first truthy value or the last value if all are falsy. ! (NOT) inverts a boolean. The nullish coalescing operator (??) returns the right side only when the left is null or undefined.
Bitwise Operators
Bitwise operators treat numbers as 32-bit binary sequences and operate on them bit by bit. They include AND (&), OR (|), XOR (^), NOT (~), left shift (<<), right shift (>>), and unsigned right shift (>>>). These are rarely needed in typical web development but appear in performance-sensitive code, flags/permissions systems, and low-level algorithms.
Ternary Operator
The ternary (conditional) operator is a compact one-line alternative to an if...else statement. It takes the form condition ? valueIfTrue : valueIfFalse, and evaluates to whichever value matches the condition. It is an expression, meaning it produces a value that can be assigned or used directly, unlike an if statement.
Template Literals
Template literals, introduced in ES6, use backticks (`) instead of quotes and allow embedded expressions via ${expression} syntax, along with genuine multi-line strings without needing escape characters. They largely replace manual string concatenation with + for building dynamic strings.
Functions: Declarations & Expressions
Functions are reusable blocks of code. A function declaration (using the function keyword with a name) is hoisted, meaning it can be called before its definition in the code. A function expression assigns a function to a variable and is not hoisted the same way - it must be defined before it is called.
Function Parameters: Default & Rest
Default parameters let you specify a fallback value used when an argument is omitted or undefined. Rest parameters, written with ...name, collect any remaining arguments into a real array, letting a function accept a variable number of arguments cleanly.
Destructuring
Destructuring lets you unpack values from arrays or properties from objects into distinct variables in a single concise statement, instead of accessing each one individually. It works with arrays (by position) and objects (by property name), and can be nested for deeply structured data.
Spread Operator
The spread operator (...) expands an iterable (like an array) or an object's own enumerable properties into individual elements. It is commonly used to copy arrays/objects, merge them together, or pass array elements as individual function arguments.
if...else and switch
if...else executes code blocks based on boolean conditions, with else if for additional conditions and a final else as a catch-all. switch compares a single value against multiple possible cases, useful when checking one variable against many discrete values - each case needs a break to prevent falling through to the next.
Loops: for, while, do...while
JavaScript offers several loop types. The classic for loop is ideal when you know the number of iterations, using an initializer, condition, and increment. while loops run as long as a condition remains true, checking before each iteration. do...while is similar but always runs at least once, checking the condition after the first iteration.
for...in vs for...of
for...in iterates over the enumerable property keys of an object (or the indices of an array, though this is discouraged). for...of iterates over the values of an iterable, like arrays, strings, Maps, and Sets - it is generally the better choice when working with arrays.
break and continue
break immediately exits the nearest enclosing loop (or switch statement), skipping any remaining iterations. continue skips the rest of the current iteration and moves on to the next one, without exiting the loop entirely. Labeled statements let break/continue target an outer loop from within a nested one.
Objects: Basics
Objects store collections of related data as key-value pairs, where keys are strings (or Symbols) and values can be any type, including functions (called methods). Properties can be accessed with dot notation or bracket notation, and objects can be created with object literals, the Object() constructor, or classes.
The this Keyword
this refers to the object that is currently executing a function, but its value depends entirely on how the function is called, not where it is defined. In a regular method call, this is the object before the dot. In a standalone function call, this is undefined in strict mode. Arrow functions do not have their own this - they inherit it from the enclosing scope.
Classes
Classes provide syntax for creating objects with shared structure and behavior, built on top of JavaScript's existing prototype-based inheritance. A class has a constructor for initialization, methods shared across instances, and can extend another class to inherit its behavior via the extends and super keywords.
Closures
A closure is a function that remembers and can access variables from its outer (enclosing) scope, even after that outer function has finished executing. Closures happen automatically whenever a function is defined inside another function. They are the mechanism behind private state, function factories, and many common JavaScript patterns.
Hoisting
Hoisting is JavaScript's behavior of moving declarations (not initializations) to the top of their scope before code executes. Function declarations are fully hoisted, including their body, so they can be called before their definition. var declarations are hoisted but initialized as undefined. let and const are hoisted but remain in a "temporal dead zone" - accessing them before their declaration throws an error.
Scope
Scope determines where variables are accessible in your code. JavaScript has global scope (accessible everywhere), function scope (var-declared variables inside a function), and block scope (let/const-declared variables inside any { } block, including if statements and loops). Inner scopes can access outer scope variables, but not vice versa.
Strict Mode
"use strict" opts your code into a restricted variant of JavaScript that catches common mistakes by turning them into errors - like accidentally creating a global variable by forgetting to declare it. ES6 modules and classes are automatically in strict mode, so most modern code benefits from it without explicitly writing the directive.
Error Handling: try/catch/finally
try...catch lets you handle errors gracefully instead of letting them crash your program. Code that might fail goes in the try block; if an error occurs, control jumps to the catch block. finally runs regardless of whether an error occurred, useful for cleanup. The throw statement lets you raise your own custom errors.
Modules: import/export
ES modules let you split code across multiple files and share functionality between them using export and import. A named export can export multiple values from one file, each imported individually by name. A default export represents the file's primary value, imported without curly braces and under any name you choose.
Optional Chaining & Nullish Coalescing
Optional chaining (?.) safely accesses deeply nested properties without throwing an error if an intermediate value is null or undefined - it short-circuits and returns undefined instead of crashing. Nullish coalescing (??) provides a default value only when the left side is specifically null or undefined, not for other falsy values like 0 or "".
typeof and instanceof
typeof returns a string indicating the general type of a value (like "string", "number", "object"). instanceof checks whether an object is an instance of a specific class or constructor function by walking its prototype chain, useful for distinguishing between different object types like Array, Date, or custom classes.
Type Conversion
JavaScript converts values between types both explicitly (when you deliberately call a conversion function like Number() or String()) and implicitly (when the language automatically coerces types during operations, like using + with a string and a number). Understanding both is essential for avoiding subtle bugs.
Regular Expressions
Regular expressions (RegExp) describe patterns for matching text, used for validation, searching, and replacing. They can be created with literal syntax (/pattern/flags) or the RegExp constructor. Common methods include test() to check for a match, and string methods like match(), replace(), and split() that accept a regex pattern.
Iterables and Generators
An iterable is any object that implements the Symbol.iterator method, allowing it to be used with for...of and the spread operator - arrays, strings, Maps, and Sets are all built-in iterables. Generator functions, defined with function*, provide an easy way to create custom iterables by using yield to produce a sequence of values one at a time, pausing execution between each.
Symbols
Symbol is a primitive type that creates unique, immutable identifiers. Every Symbol() call produces a completely unique value, even with the same description, which makes them useful as object property keys that are guaranteed not to collide with other keys - including string keys or other symbols. They are also used internally by JavaScript for things like Symbol.iterator.
Sets
A Set is a collection of unique values of any type - unlike an array, it automatically prevents duplicates. Sets maintain insertion order and provide efficient add, delete, and lookup operations. They are ideal for deduplicating data or tracking membership without caring about order or indexed access.
Maps
A Map is a collection of key-value pairs, similar to a plain object, but with important differences: keys can be any type (not just strings), it maintains insertion order, and it provides a direct size property. Maps are generally the better choice over plain objects when keys are dynamic, non-string, or when you need reliable size and iteration.
JSON: stringify() and parse()
JSON (JavaScript Object Notation) is a text format for representing structured data, widely used for APIs and configuration. JSON.stringify() converts a JavaScript value into a JSON string, and JSON.parse() converts a JSON string back into a JavaScript value. Functions, undefined, and symbols are silently dropped or converted during stringification.
JavaScript Arrays
JavaScript arrays store an ordered list of values. Create one with [], read items by index starting at 0, and use array methods to add or transform items.
push(), pop(), shift(), unshift()
These four methods add or remove elements from the ends of an array, all mutating the original array in place. push() and pop() work on the end of the array (fast). shift() and unshift() work on the beginning (slower, since remaining elements must be re-indexed).
slice() and splice()
slice() returns a shallow copy of a portion of an array as a new array, without modifying the original - useful for extracting a section. splice() modifies the original array in place by removing, replacing, or inserting elements at a specific position, and returns the removed elements.
concat() and join()
concat() merges two or more arrays into a new array, without modifying the originals. join() converts all array elements into a single string, separated by a specified delimiter (comma by default) - the reverse operation of String.prototype.split().
indexOf(), includes(), lastIndexOf()
Use includes() to check whether a value is present, or indexOf() and lastIndexOf() when you need its position. The index methods return -1 when no value matches. None of these methods compares the contents of separate objects: use some() or find() with a property check for that.
find(), findIndex(), findLast(), findLastIndex()
These methods stop at one item that passes your test. find() returns the first matching value; findIndex() returns its position. findLast() and findLastIndex() start at the end. Use them to look up one lesson by id, for example, rather than collecting every match with filter().
filter()
filter() builds a new array of items that pass your test, in their original order. Use it to show only unfinished lessons or available products. If nothing matches, you receive an empty array. The new array contains the existing values; objects inside it are not cloned.
map()
map() turns each existing item into a result and collects those results in a new array. For example, turn lesson objects into titles or add a display label to each one. It preserves positions rather than removing items; use filter() to choose which items to keep.
reduce() and reduceRight()
reduce() carries a result from one callback call to the next. Use it when several items contribute to one total, lookup or other accumulated value. reduceRight() follows the same process from the end of the array. If a loop explains the calculation more clearly, use a loop.
forEach()
forEach() executes a function once for each array element, used purely for side effects like logging or updating external state - it always returns undefined and cannot be chained. Unlike map()/filter(), it does not produce a new array, and unlike a for loop, it cannot be stopped early with break.
some() and every()
some() tests whether at least one array element passes a condition, returning true as soon as it finds a match (or false if none do). every() tests whether all elements pass a condition, returning false as soon as it finds one that fails (or true if all pass). Both short-circuit for efficiency.
sort() and reverse()
sort() orders the elements of an array in place. Without a comparator function, it converts elements to strings and sorts lexicographically - which produces surprising results for numbers. A comparator function gives full control over the ordering. reverse() simply flips the current order of the array in place.
flat() and flatMap()
flat() creates a new array with nested sub-arrays flattened up to a specified depth (default 1 level). flatMap() combines mapping and flattening in a single, more efficient step - it maps each element and then flattens the result by exactly one level, useful when a mapping function returns an array for each item.
fill() and copyWithin()
fill() changes all elements in an array (or a specified range) to a single static value, mutating the array in place - useful for initializing arrays. copyWithin() copies a sequence of elements to another position within the same array, also mutating in place, without changing the array's length.
String Basics: length, charAt(), at()
Strings are immutable sequences of characters - every string method returns a new string rather than modifying the original. The length property gives the character count. charAt() returns the character at a given index, while the newer at() method also supports negative indices to count from the end.
slice(), substring(), substr()
These three methods extract a portion of a string as a new string. slice() and substring() are similar, but slice() accepts negative indices (counting from the end) while substring() treats negative values as 0 and swaps arguments if start is greater than end. substr() (deprecated) uses a start index and a length rather than an end index.
indexOf(), includes(), startsWith(), endsWith()
These methods search within a string for a substring. indexOf() returns the position of the first match (or -1). includes() returns a simple true/false. startsWith() and endsWith() check specifically whether the string begins or ends with a given substring. All are case-sensitive.
replace() and replaceAll()
replace() returns a new string with the first match of a pattern replaced by a new value - or all matches, if the pattern is a regex with the global (g) flag. replaceAll(), introduced in ES2021, always replaces every occurrence without needing a regex, making simple find-and-replace-all operations more straightforward.
split()
split() divides a string into an array of substrings based on a specified separator, which can be a literal string or a regular expression. It is the inverse operation of Array.prototype.join(). An optional second argument limits the number of resulting elements.
trim(), trimStart(), trimEnd()
trim() removes whitespace from both ends of a string, commonly used to clean up user input before validation or storage. trimStart() and trimEnd() (aliases: trimLeft/trimRight) remove whitespace from only the beginning or end respectively.
toUpperCase() and toLowerCase()
toUpperCase() and toLowerCase() return a new string with all characters converted to the respective case. They are frequently used for case-insensitive comparisons, since converting both sides to the same case avoids inconsistent casing causing a false mismatch.
padStart(), padEnd(), repeat()
padStart() and padEnd() pad a string with a specified character until it reaches a target length, commonly used for formatting numbers with leading zeros or aligning text in columns. repeat() returns a new string with the original repeated a specified number of times.
Number Methods & Parsing
Number methods handle formatting and validation. toFixed() formats a number to a fixed number of decimal places, returning a string. parseInt() and parseFloat() convert strings to numbers, stopping at the first invalid character. Number.isInteger() and Number.isNaN() provide more reliable type checks than their global counterparts.
Math Object: round, floor, ceil, abs, max, min, pow, sqrt
The Math object provides mathematical constants and functions as static methods - it is not a constructor, so you never create a Math instance. Common methods include rounding (round, floor, ceil, trunc), extremes (max, min), and power operations (pow, sqrt, cbrt).
Math.random()
Math.random() returns a pseudo-random floating-point number between 0 (inclusive) and 1 (exclusive). It is commonly combined with multiplication and Math.floor() to generate random integers within a specific range. It is not cryptographically secure - for security-sensitive randomness, use the Web Crypto API instead.
Date: Creating and Getting Values
The Date object represents a single moment in time. new Date() with no arguments creates the current date/time; it also accepts a specific date, individual components (year, month, day...), or a timestamp. Getter methods like getFullYear(), getMonth(), and getDate() extract individual components - note that getMonth() is zero-indexed (0 = January).
Date: Setting and Formatting
Setter methods like setFullYear() and setDate() modify a Date object in place. Formatting methods convert a Date into a readable string: toDateString() and toTimeString() give simple readable formats, toISOString() gives the standardized ISO 8601 format (useful for APIs), and toLocaleDateString() formats according to a locale's conventions.
Object.keys(), values(), entries(), assign(), freeze()
These static Object methods work with any plain object. keys(), values(), and entries() return arrays of an object's own enumerable property names, values, or [key, value] pairs respectively - useful for iterating over objects. assign() copies properties from source objects into a target. freeze() prevents any further modification to an object.
Promises
A Promise represents a value that may not be available yet - the eventual result of an asynchronous operation. It exists in one of three states: pending, fulfilled, or rejected. then() handles a successful result, catch() handles an error, and finally() runs regardless of outcome. Promises are the foundation that async/await is built on top of.
Promise.all(), allSettled(), race(), any()
These static methods handle multiple promises at once. Promise.all() waits for every promise to resolve, but rejects immediately if any one fails. allSettled() waits for all to finish regardless of outcome, giving you both successes and failures. race() resolves or rejects as soon as the first promise settles. any() resolves as soon as the first one succeeds, ignoring rejections unless all fail.
Fetch API
The Fetch API provides a modern, promise-based way to make HTTP requests, replacing the older XMLHttpRequest. fetch() returns a promise that resolves to a Response object once headers are received - note that a Response is only considered "ok" if the status is 2xx, so checking response.ok is essential, since fetch() does not reject on HTTP error statuses.
addEventListener() and the Event Object
addEventListener() attaches a function to run when a specific event occurs on an element, without overwriting any other listeners already attached (unlike the older onclick= style). The callback receives an Event object with details about what happened, including target (the element that triggered it) and methods like preventDefault().
Event Bubbling and Delegation
Most events "bubble" - after firing on the target element, they also fire on each ancestor element up to the document root, unless stopped with stopPropagation(). Event delegation takes advantage of bubbling by attaching a single listener to a parent element instead of many listeners on individual children, using event.target to identify which child was actually interacted with.
DOM Selection: querySelector(), getElementById()
These methods find elements in the DOM. getElementById() finds a single element by its unique id, generally the fastest option. querySelector() finds the first element matching any valid CSS selector, and querySelectorAll() returns all matching elements as a static NodeList.
Creating and Modifying Elements
createElement() builds a new DOM element in memory, which can then be customized and inserted into the page with methods like appendChild() or append(). textContent sets plain text safely, while innerHTML parses and inserts HTML markup - which carries injection risks if the content includes untrusted user input.
classList: add, remove, toggle, contains
The classList property provides a convenient API for managing an element's CSS classes without manually parsing the className string. add() and remove() add or remove one or more classes, toggle() switches a class on or off based on its current presence, and contains() checks whether a class is currently applied.
localStorage and sessionStorage
localStorage and sessionStorage let you store key-value data directly in the browser, using the same simple API. localStorage persists indefinitely, even after closing the browser, while sessionStorage clears when the tab is closed. Both only store strings - objects must be converted with JSON.stringify() and JSON.parse().
Proxy and Reflect
Proxy wraps an object and lets you intercept and customize fundamental operations on it - like getting, setting, or deleting a property - by defining "trap" functions in a handler object. Reflect provides methods that mirror those same fundamental operations, letting you forward the default behavior from inside a Proxy trap rather than reimplementing it manually.
Typed Arrays & ArrayBuffer
ArrayBuffer represents a fixed-length raw binary data buffer. Typed arrays (Int8Array, Uint8Array, Float32Array, and others) provide a structured, array-like view onto that buffer, where every element is the same fixed-size numeric type. They are used for binary data processing, working with files, WebGL, audio/video data, and network protocols.
WeakMap and WeakSet
WeakMap and WeakSet are like Map and Set, but their keys (WeakMap) or values (WeakSet) must be objects, and those references are "weak" - meaning they do not prevent the object from being garbage collected if nothing else references it. This makes them ideal for attaching metadata to objects without causing memory leaks.
Web Workers
Web Workers run JavaScript on a separate background thread, away from the main UI thread, so expensive computations do not freeze the page. Communication between the main script and a worker happens through message passing with postMessage() and the onmessage event handler, rather than shared memory - workers cannot directly access the DOM.
Temporal API
Temporal is the modern, immutable replacement for the long-criticized Date object, reaching TC39 Stage 4 and becoming part of the ECMAScript 2026 specification. It fixes Date's biggest pain points: no built-in time zone support, confusing zero-indexed months, and mutable objects that are easy to accidentally modify. Temporal provides distinct types for different use cases - PlainDate, PlainTime, ZonedDateTime, Duration, and more.
Getters and Setters
Getters and setters let you define object or class properties that run custom logic when read or assigned, while still being accessed with normal property syntax (no parentheses). They are useful for computed properties, validation on assignment, or controlling access to internal state.
Custom Error Classes
You can create your own error types by extending the built-in Error class, giving you custom error names and additional properties while still working correctly with try/catch, instanceof checks, and stack traces. This makes error handling more precise than checking error.message strings.
Object.defineProperty() & Property Descriptors
Object.defineProperty() gives fine-grained control over a single property's behavior via a descriptor object, letting you control whether it is writable, enumerable (shows up in loops/Object.keys), and configurable (can be redefined or deleted) - none of which is possible with normal property assignment.
Intl API: Number & Date Formatting
The Intl object provides language-sensitive formatting for numbers, currencies, dates, and more, correctly following the conventions of a specified locale. Intl.NumberFormat handles numbers and currency, and Intl.DateTimeFormat handles dates - both far more robust than manually formatting strings.
structuredClone()
structuredClone() creates a true deep copy of a value, correctly handling nested objects, arrays, Maps, Sets, dates, and even circular references - something JSON.parse(JSON.stringify(obj)) cannot do reliably. It is a built-in global function, available without any import.
URL and URLSearchParams
The URL object parses and constructs URLs, giving structured access to their parts (protocol, host, pathname, etc.) without manual string manipulation. URLSearchParams specifically handles query string parameters - reading, adding, and removing them correctly, including proper encoding.
FormData
FormData represents a set of key-value pairs, mirroring an HTML form's data, and is commonly used to send form submissions (including file uploads) via fetch() without manually constructing multipart request bodies. It can be created from an existing <form> element or built up manually.
IntersectionObserver
IntersectionObserver efficiently detects when an element enters or exits the viewport (or another container), without the performance cost of manually listening to scroll events and calculating positions. It is the standard tool for lazy-loading images, infinite scroll, and scroll-triggered animations.
MutationObserver
MutationObserver watches for changes to the DOM tree - added/removed elements, attribute changes, or text content changes - and runs a callback in response. It is useful for reacting to DOM changes made by other scripts or third-party widgets that you do not directly control.
Console Methods Beyond log()
The console object offers several methods beyond the familiar console.log() for more effective debugging: console.table() for tabular data, console.group() for nested/collapsible logs, console.time()/timeEnd() for measuring performance, console.warn()/error() for severity-styled messages, and console.assert() for conditional logging.
Tagged Template Literals & String.raw
A tagged template literal calls a function ("tag") with the template's string parts and interpolated values passed separately, letting you fully customize how the final string is built - useful for sanitization, internationalization, or styling libraries. String.raw is a built-in tag that returns the literal string with escape sequences left un-processed.
Async Generators & for await...of
Async generators combine generators and async functions, defined with async function*, yielding values that may themselves be promises. for await...of consumes an async iterable, automatically awaiting each yielded value - useful for processing streamed data or paginated API results one chunk at a time.
getComputedStyle() and element.style
element.style gives direct read/write access to an element's inline styles only - not styles applied via CSS classes or stylesheets. getComputedStyle() returns the actual final, computed value of any CSS property after all stylesheets, inheritance, and browser defaults are applied, regardless of where that style came from.
History API: pushState() and popState
The History API lets JavaScript manipulate the browser's session history and URL without triggering a full page reload - the foundation of client-side routing in single-page applications. pushState() adds a new entry to the history stack, and the popstate event fires when the user navigates back/forward.
Clipboard API
The Clipboard API provides a modern, promise-based way to read from and write to the system clipboard, replacing the older, more limited document.execCommand("copy"). Both reading and writing typically require a secure context (HTTPS) and, for reading, explicit user permission.
JavaScript Optional Chaining & Nullish Coalescing
Optional chaining (?.) stops and produces undefined when its left side is null or undefined. Nullish coalescing (??) supplies a fallback only for null or undefined, not for valid falsey values such as 0 or an empty string.
Cooperative Cancellation with AbortController
AbortController exposes a signal that compatible operations can observe. Calling abort marks the signal aborted and notifies listeners; it does not forcibly stop arbitrary JavaScript. APIs such as fetch and event listener registration can cooperate with the signal. An aborted signal cannot be reset.
Observing Element Sizes with ResizeObserver
ResizeObserver reports changes to an element’s box size, including changes unrelated to window resizing. It is useful for components that depend on their allocated width. Callbacks run during rendering; changing the observed dimensions in response can produce feedback loops.
Animating with requestAnimationFrame
requestAnimationFrame schedules a one-shot callback before a future repaint. Use the supplied timestamp to calculate progress independently of display refresh rate. Frames may pause in background tabs, so frame counts are not a reliable clock.
Debouncing with Timers
Debouncing delays work until calls stop arriving for a chosen period. Each new call cancels the previous timeout and schedules another. A timeout specifies a minimum delay, not an exact execution time; busy event loops and background tabs can defer it.
Microtasks and Event-loop Ordering
queueMicrotask schedules work after the current JavaScript stack finishes, before the event loop proceeds to another task. Promise reactions also use microtasks. Recursively queuing microtasks can delay rendering and timers indefinitely, so this queue is for short follow-up work.
Application Events with EventTarget and CustomEvent
EventTarget provides a small event dispatch mechanism independent of DOM elements. CustomEvent carries application data through detail. dispatchEvent invokes listeners synchronously; a custom event does not automatically become an asynchronous message or provide isolation between listeners.
UTF-8 Bytes with TextEncoder and TextDecoder
TextEncoder converts JavaScript text to UTF-8 bytes. TextDecoder converts supported byte encodings back into strings. String length counts UTF-16 code units rather than bytes, so byte length must be measured after encoding when preparing network or binary formats.
Binary Data with Blob and Object URLs
Blob represents immutable bytes with an optional MIME type. An object URL temporarily exposes a Blob to APIs that expect a URL. The URL is tied to a browser-managed resource; revoke it when the consumer no longer needs it, rather than treating it as permanent storage.
Cryptographic Random Values
crypto.getRandomValues fills an integer typed array with cryptographically strong random values. crypto.randomUUID creates a version-4 UUID and requires a secure browser context. Neither a UUID nor a random value automatically supplies authorization or replaces a properly designed security protocol.
Computing a SHA-256 Digest
crypto.subtle.digest computes a digest of supplied bytes and returns an ArrayBuffer asynchronously. SHA-256 is useful for content fingerprints and integrity workflows, but an unauthenticated hash does not prove who produced the content. Web Crypto subtle APIs require a secure browser context.
Consuming a ReadableStream
ReadableStream delivers chunks over time. A reader locks the stream while it is in use; read() returns an object with value and done. Streams help process incremental data without collecting the entire payload, but producers and consumers still need a cancellation and error policy.
Own Properties and Object.fromEntries
Object.hasOwn checks whether a property belongs directly to an object, independent of its prototype. Object.fromEntries builds an object from key-value pairs. These methods support record manipulation without confusing inherited methods with data; Object.hasOwn was added in ES2022.
Exact Integer Arithmetic with BigInt
BigInt represents integers beyond Number’s safe integer range. Create values with an n suffix or BigInt from an integer string. Arithmetic generally cannot mix Number and BigInt; integer division truncates toward zero. BigInt is standardized in ES2020 and cannot be directly JSON-stringified.
Immutable Array Updates with Copying Methods
ES2023 adds toSorted, toReversed, toSpliced, and with as copying alternatives to common array mutations. They create new arrays while retaining the original sequence. Copies are shallow, so referenced objects are still shared; older runtimes need a polyfill or another copying pattern.
Locale-aware Sorting with Intl.Collator
Intl.Collator compares strings according to locale-sensitive collation rules. Options such as numeric and sensitivity control treatment of digit sequences and case or accent distinctions. Exact ordering can vary with locale data and runtime versions, so specify the intended locale.
Plural Categories with Intl.PluralRules
Intl.PluralRules maps a number to a language’s plural category, such as one, few, many, or other. Categories are language rules, not a universal singular/plural boolean. The API selects categories; the application still supplies translated phrases for those categories.
Grapheme Segmentation with Intl.Segmenter
Intl.Segmenter finds language-aware grapheme, word, or sentence boundaries. Grapheme segmentation is useful for user-perceived characters that consist of several Unicode code points. Availability is newer than basic Intl formatting, so feature-detect it when supporting older runtimes.
Named Captures and Unicode Regular Expressions
Named capture groups expose matched portions through a groups object rather than positional indexes. Unicode property escapes such as \p{L} match Unicode character categories with the u flag. Both features were added in ES2018; they are useful when ASCII-only classes would reject ordinary international text.
Explicit Receivers with call, apply, and bind
call and apply invoke an ordinary function with an explicit this value; apply accepts an array-like argument list. bind creates a new function with a fixed receiver and optional leading arguments. Arrow functions capture this lexically, so these methods cannot replace an arrow’s receiver.
Prototype Delegation and Object.create
JavaScript property lookup can delegate to an object’s prototype when an own property is missing. Object.create builds an object with a chosen prototype. This explains inherited methods and shared behavior without implying that inherited data is copied into each object.
TypeScript documentation
Introduction to TypeScript
Start here: learn why TypeScript was created, how it checks JavaScript code, what runs after compilation and where its benefits and limits matter.
How TypeScript Works
Follow a TypeScript file through checking, JavaScript generation and execution, then learn what tsc, tsconfig.json, source maps and runtime type stripping do.
Set Up TypeScript on Windows
Install the Node.js prerequisites on Windows, then create, check, compile and run a local TypeScript project in PowerShell.
Set Up TypeScript on macOS
Use Node.js and npm on macOS to create a TypeScript project, check its types and run the emitted JavaScript from Terminal.
Set Up TypeScript on Linux
Prepare Node.js and npm on Linux, then create a local TypeScript project and run its compiled JavaScript in a shell.
Your First TypeScript Project
Build a small receipt calculator from an empty npm folder, add types, diagnose and fix an error, then run the generated JavaScript with Node.js.
Interfaces
Interfaces in TypeScript define the structure of objects by specifying property names and their types. They act as contracts that ensure objects conform to specific shapes, providing type safety and better IDE support. Interfaces can be extended, merged, and used to type-check function parameters, return values, and object literals.
Basic Types
TypeScript extends JavaScript with static types, letting the compiler catch type errors before code ever runs. Beyond the familiar string, number, and boolean, TypeScript adds any (disables checking entirely), unknown (a safer any that requires narrowing), void (a function returning nothing), and never (a value that can never occur, like a function that always throws).
Type Aliases
The type keyword creates a named alias for any type - not just object shapes like interface, but also unions, primitives, tuples, and function signatures. Type aliases make complex types reusable and give them a meaningful name, improving both readability and error messages.
Union and Intersection Types
A union type (A | B) means a value can be either type A or type B. An intersection type (A & B) means a value must satisfy both A and B simultaneously, combining their members into one type. Unions are common for values with a few valid states; intersections are common for combining smaller, focused types into a larger one.
Literal Types
Literal types narrow a type down to one specific, exact value rather than a general category - "success" instead of string, or 200 instead of number. They are most useful combined with union types, letting you precisely constrain a value to a specific set of allowed options, catching typos and invalid values at compile time.
Type Inference
TypeScript can automatically determine a value's type from its initializer, without an explicit annotation - this is type inference. It reduces boilerplate significantly while still providing full type safety. Understanding what TypeScript infers (and when it needs help) is key to writing idiomatic, uncluttered TypeScript.
Type Assertions: as and satisfies
The as keyword tells the compiler to treat a value as a specific type, overriding its own inference - useful when you know more about a value's type than TypeScript can determine on its own. The newer satisfies operator validates that a value matches a type without changing the value's own inferred type, giving you both validation and precise inference at once.
Enums
An enum defines a named set of related constants, making code more readable than using raw numbers or strings for a fixed set of options. Numeric enums auto-increment by default, string enums require explicit values for each member, and const enum is fully erased at compile time, replaced by its literal values with no runtime object generated at all.
Typing Functions
Function parameters and return types can be explicitly typed for safety and clarity. Optional parameters (marked with ?) must come after required ones, and default parameter values let TypeScript infer their type automatically. Function type expressions let you type a variable that holds a function, describing exactly what parameters and return type it must have.
Typed Arrays and Tuples
Arrays are typed as Type[] (or Array<Type>), where every element must be the same type. Tuples, written with square brackets containing specific types, are fixed-length arrays where each position has its own distinct, known type - useful for representing a small, ordered, heterogeneous group of values.
type vs interface
Both type and interface can describe object shapes, and for that common case they are largely interchangeable. The key differences: interface supports declaration merging (multiple declarations with the same name combine automatically) and can only describe object-like shapes, while type can alias anything - unions, tuples, primitives - but cannot be re-opened once declared.
Index Signatures
An index signature lets an interface or type describe an object with dynamic keys of a known type, when you don't know the exact property names in advance - only their pattern. This is common for dictionary-like objects, such as a lookup table keyed by user ID or product SKU.
Typed Classes
TypeScript enhances JavaScript classes with typed properties, constructor parameters, and method signatures. Class fields must either be initialized or explicitly typed, and TypeScript checks that constructor assignments match declared property types, catching mismatches before runtime.
Access Modifiers: public, private, protected
Access modifiers control visibility of class members. public (the default) is accessible from anywhere. private restricts access to within the declaring class only, not even subclasses. protected allows access within the class and its subclasses, but not from outside. These are compile-time only checks - true runtime privacy needs the # syntax instead.
Abstract Classes
An abstract class cannot be instantiated directly - it exists only to be extended. It can define abstract methods (a signature with no implementation, which subclasses must provide) alongside regular, fully-implemented methods that subclasses inherit as-is. This is TypeScript's way of enforcing a shared contract across a family of related classes.
implements Keyword
The implements keyword declares that a class must conform to a specific interface's shape - TypeScript checks that every property and method the interface requires is actually present with a compatible type. Unlike extends, implements does not provide any inherited implementation; it is purely a compile-time contract check.
Decorators
Decorators are functions that can observe, modify, or replace a class, method, property, or accessor, applied with @decoratorName syntax. They became a genuinely stable, standard part of TypeScript with TC39 Stage 3 decorator support landing as of TypeScript 5.9, and are the mechanism behind frameworks like Angular and NestJS for dependency injection and metadata-driven APIs.
Generics Basics
Generics let you write reusable functions, classes, and types that work with a variety of types while still preserving type safety - rather than using any and losing that safety, or writing near-duplicate code for each type. A generic type parameter, conventionally named T, acts as a placeholder that gets filled in with a real type each time it is used.
Generic Constraints
By default, a generic type parameter can be anything. The extends keyword constrains it to only types compatible with a given shape, letting you safely access specific properties or methods within the generic function while still supporting many different concrete types.
Generic Classes and Interfaces
Classes and interfaces can also be generic, letting you build reusable data structures (like a Stack, Queue, or API response wrapper) that work with any type while remaining fully type-safe for whichever specific type is used in each instance.
Conditional Types
A conditional type selects between two types based on a condition, using syntax that mirrors JavaScript's ternary operator: T extends U ? X : Y. This lets you build types that adapt based on the shape of another type, forming the foundation for many of TypeScript's built-in utility types.
The infer Keyword
infer, used only within the extends clause of a conditional type, lets you declare a new type variable that captures part of a matched structure, so it can be reused in the result. It is the mechanism behind utility types like ReturnType<T> and Parameters<T>, which extract specific pieces of a function's type signature.
Mapped Types
A mapped type builds a new type by transforming every property of an existing type, using syntax similar to a for...in loop at the type level: { [K in keyof T]: NewType }. This is the mechanism behind built-in utility types like Partial<T> and Readonly<T>, and lets you write your own systematic property transformations.
Partial<T> and Required<T>
Partial<T> constructs a new type with every property of T marked optional - useful for representing partial updates, like a PATCH request body. Required<T> does the opposite, making every property mandatory even if the original type had optional ones, useful for ensuring a fully-populated object at a specific point in your code.
Pick<T> and Omit<T>
Pick<T, Keys> constructs a new type by selecting only the specified properties from T. Omit<T, Keys> does the reverse, constructing a new type with all properties of T except the specified ones. Both are extremely common for deriving smaller, focused types from a larger base type without duplicating the definition.
Record<K, V>
Record<Keys, ValueType> constructs an object type with a specific set of keys, all mapped to the same value type. It is the concise, standard way to type dictionary-like objects, and is often clearer than writing an equivalent index signature by hand.
Readonly<T>
Readonly<T> constructs a new type where every property of T is marked readonly, preventing reassignment after the object is created. It is a shallow transformation - nested objects within a Readonly<T> are not automatically deep-frozen, only the top-level properties are protected from reassignment.
ReturnType<T> and Parameters<T>
ReturnType<T> extracts the return type of a function type, and Parameters<T> extracts its parameter types as a tuple. Both are especially useful for deriving types from functions you do not directly control, like third-party library functions, without manually duplicating their signatures.
Exclude<T> and Extract<T>
Exclude<UnionType, ExcludedMembers> constructs a type by removing specific members from a union. Extract<UnionType, Union> does the opposite, keeping only the members that are assignable to the given type. Both are useful for deriving a narrower union from an existing one without redefining it from scratch.
tsconfig.json Basics
Learn how a TypeScript project chooses files, checks types and emits JavaScript, using a small browser-script configuration whose output you can inspect.
TypeScript in the Browser
Build a small browser page with TypeScript, compile src/main.ts to dist/main.js, and use the emitted file to update text after a click.
TypeScript in the Codectionary Playground
Learn what Codectionary’s TypeScript preview runs, where output and errors appear, and why local tsc is needed for full project checking.
Strict Mode Options
The "strict" tsconfig option is actually a shorthand that enables a whole family of individual strictness flags at once, including strictNullChecks (null/undefined are not assignable to other types by default), noImplicitAny (variables must have an inferable or explicit type), and strictFunctionTypes. Enabling strict mode is one of the highest-value changes for TypeScript's type safety.
Declaration Files (.d.ts)
Declaration files contain only type information, no actual implementation - they describe the shape of existing JavaScript code so TypeScript can type-check against it. This is how you get autocomplete and type safety for plain JavaScript libraries, and how your own TypeScript library can ship types alongside its compiled JavaScript output.
TypeScript satisfies Operator
The satisfies operator checks that an expression is compatible with a type without replacing the expression’s more specific inferred type.
Key Unions with keyof
keyof derives a union of property keys from an object type. Combined with a constrained type parameter, it prevents callers from requesting nonexistent properties while preserving the return type for the selected key. It operates during type checking and emits no runtime validation.
Deriving Types from Values with typeof
In a type position, typeof refers to the static type of a variable or property. This avoids duplicating the shape of a configuration or factory value. It is separate from JavaScript’s runtime typeof expression, which returns strings such as object or number.
Looking Up Property Types
Indexed access types retrieve a property’s type from another type. Indexing an array type with number retrieves its element type. These operators keep related declarations aligned when the original model changes; the index in a type position must itself be a type.
Structured Strings with Template Literal Types
Template literal types construct string types by interpolating literal unions. They can describe event names or localized keys and reject misspellings at compile time. Introduced in TypeScript 4.1, they are type-level constraints and do not check arbitrary runtime strings automatically.
Exhaustive Discriminated Unions
A discriminated union uses a shared literal-valued field to identify each variant. Checking that field narrows the associated payload. A never assignment after all variants provides an exhaustiveness check: adding a variant requires updating the handling code.
Reusable Type Guards with Type Predicates
A predicate return type such as value is string tells TypeScript how a boolean result narrows a value. This is useful for validation helpers and filtering. The compiler trusts the declared predicate, so its implementation must check the claimed condition accurately.
Runtime Checks with Assertion Functions
An assertion function states that normal return guarantees a condition or narrower type. It should throw when the assertion is false. TypeScript 3.7 added assertion signatures; unlike an as assertion, this pattern includes executable validation.
Correlated Function Overloads
Overload signatures describe different accepted call shapes and their return types while sharing one implementation. The implementation signature must support all overloads, but is not an extra public call signature. Use overloads when a simple union signature cannot express a useful argument-to-result relationship.
Typing a Function’s this Receiver
A special first parameter named this declares the expected receiver of an ordinary function. It is erased from emitted JavaScript and is not an argument callers pass positionally. This supports callback APIs and functions whose behavior depends on call, apply, or bind.
Literal Preservation with as const
A const assertion prevents literal widening and gives object properties readonly types and array literals readonly tuple types. Introduced in TypeScript 3.4, it is a compile-time operation, not a runtime deep freeze. Referenced mutable objects can remain mutable.
Literal Inference with const Type Parameters
TypeScript 5.0 introduced const type parameters to request literal-preserving inference for inline arguments. This can capture a readonly tuple without requiring every caller to add as const. It does not retroactively narrow a variable that was already inferred as a broad mutable array.
Choosing Inference Sources with NoInfer
NoInfer<T>, added in TypeScript 5.4, prevents a position from contributing candidates while inferring T. The position is still checked against the resulting type. This is useful when a list of allowed values should determine the type and a default value should only be checked against it.
Unwrapping Async Results with Awaited
Awaited<T> models the resolved type of an await operation, including nested promises and compatible thenables. Introduced in TypeScript 4.5, it is commonly combined with ReturnType to derive a loader’s resolved result without repeating its data model.
Removing Nullish Members with NonNullable
NonNullable<T> removes null and undefined from a type union. It does not remove other falsy values, and it performs no runtime check. Under strictNullChecks, pair it with a real guard before assuming data is present.
ConstructorParameters and InstanceType
ConstructorParameters extracts a constructor’s argument tuple, while InstanceType extracts the type of its instances. They are useful for factories and wrappers that should stay aligned with a class signature. ConstructorParameters requires TypeScript 3.1+; InstanceType was introduced in 2.8.
Interface Declaration Merging
Multiple interface declarations with the same name in the same scope merge into one type. This can support extensible contracts, but conflicting property declarations are errors. Type aliases do not merge this way, and merging creates no runtime object or implementation.
Default Generic Type Arguments
A generic parameter can have a default type so callers may omit it when inference provides no better choice. Defaults must satisfy constraints, and required type parameters cannot follow optional ones. The default controls a type argument, not a runtime parameter value.
Variadic Tuple Types
Variadic tuples model tuple composition with generic rest elements. Added in TypeScript 4.0, they let helpers preserve the types and positions of an arbitrary argument tail. They avoid long lists of overloads for every possible tuple length.
Branded Types for Validated Domain Values
A branded type intersects a primitive with a distinctive marker to discourage mixing values that share the same runtime representation. This is a TypeScript design pattern built on structural typing and unique symbols, not a runtime wrapper. A validating factory should be the controlled point where a brand is asserted.
Recursive Types for Tree Data
A recursive type refers to itself to model nested data such as a tree. Pair the data model with recursive traversal that has a clear base case. Static typing does not guarantee that a runtime structure is acyclic or shallow enough to fit the call stack.
unknown at Input Boundaries
unknown accepts a value without granting permission to use it as a specific type.
never versus void Return Types
void describes a function whose return value is not used, while never describes a function that does not complete normally.
Reading Optional Properties Safely
An optional property can be absent from an object.
Optional Chaining and Nullish Defaults
Optional chaining stops a property access or call when its left-hand value is null or undefined.
Readonly Arrays and Mutable Copies
A readonly array type allows reading elements without allowing mutation through that reference.
Labeled Tuples and Optional Elements
A tuple describes positions with different meanings and possibly different types.
Typing Destructured Parameters
An object parameter can group related options and give callers descriptive field names.
Typed Rest Parameters
A rest parameter gathers any remaining arguments into an array.
Generic Arrow Functions
An arrow function can have a type parameter just like a named generic function.
Generic Setters with Correlated Keys and Values
A generic setter can connect a selected object key to the type of value allowed at that key.
Renaming Keys in Mapped Types
Key remapping changes the property names produced by a mapped type.
Adding and Removing Mapped-Type Modifiers
Mapped types can add or remove readonly and optional modifiers from properties.
Distributive Conditional Types
A conditional type with a naked type parameter on the left of extends distributes over union members.
Recursive Conditional Types for Nested Arrays
A recursive conditional type can repeatedly unwrap a nested array type until it reaches a non-array element.
Uppercase, Lowercase and Capitalize Types
Intrinsic string-manipulation types transform string literal types at compile time.
Unique Symbols as Property Keys
A unique symbol type identifies one particular symbol declaration.
Symbol Index Signatures
A symbol index signature describes values stored under arbitrary symbol keys.
Template-Pattern Index Signatures
An index signature can accept a pattern of string keys rather than every string.
Structural Type Compatibility
TypeScript usually compares object types by their members rather than by a declared type name.
Excess Property Checks
Fresh object literals receive an additional check for unexpected fields when assigned to a known object type.
Narrowing with the in Operator
The in operator checks whether a property exists on an object or its prototype chain.
Narrowing Primitive Unions with typeof
A typeof test identifies JavaScript primitive categories and lets TypeScript narrow a union accordingly.
Class Narrowing with instanceof
instanceof checks an object against a constructor’s runtime prototype relationship.
Validating Arrays from unknown
Array.isArray checks whether a runtime value is an array, but does not validate its element types.
Truthiness versus Explicit Missing-Value Checks
A truthiness condition rejects values such as zero, an empty string, false, null and undefined.
Narrowing by Equality
An equality check can narrow two variables to the alternatives their types share.
Callable Objects with Properties
JavaScript functions are objects and can also carry properties.
Typing Constructor Values
A construct signature describes a value that can be called with new.
Fluent Methods with the this Type
A method returning the polymorphic this type preserves the more specific receiver type in a chain.
Constructor Parameter Properties
A constructor parameter with an accessibility or readonly modifier can declare and initialise a class property at the same time.
ECMAScript #private Fields versus private
A field whose name begins with # has JavaScript runtime private-field semantics.
Generic Instances and Static Members
A generic class has instance types for different type arguments, but its static side belongs to the single runtime constructor.
Readonly Dictionary Index Signatures
A readonly index signature allows lookup through a dictionary reference while rejecting assignment through that signature.
Numeric Index Signatures and String Keys
A numeric index signature describes values retrieved with numeric-looking keys.
Safe Callback Parameter Types
A callback must be able to handle every input its consumer promises to supply.
noUncheckedIndexedAccess
noUncheckedIndexedAccess adds undefined to reads whose indexed key is not known to exist.
exactOptionalPropertyTypes
exactOptionalPropertyTypes distinguishes an omitted optional property from an explicitly supplied undefined value.
Safe catch Variables
JavaScript can throw any value, not just an Error instance.
Checking Return Paths with noImplicitReturns
noImplicitReturns checks functions for inconsistent return paths.
Checking bind, call and apply
Functions expose call, apply and bind to invoke them with a chosen receiver or prefilled arguments.
Python documentation
Introduction to Python
Start here: understand what Python does, choose a place to practise, and write your first program. You do not need previous programming experience.
Install Python on Windows
Install an official Python runtime, check which interpreter runs, and execute a saved Python file from PowerShell.
Install Python on macOS
Install Python from python.org, verify the interpreter, and run your first script without changing Apple’s system tools.
Install Python on Linux
Use your distribution’s supported Python packages, keep the system interpreter intact, and run a first script.
Python Virtual Environments
Give each project its own packages and use pip through the same interpreter that runs your code.
Python in Visual Studio Code
Connect the editor, Microsoft’s Python extension and a Python interpreter, then run a saved script.
Python in PyCharm
Create a Python project with a chosen interpreter and run your code in the IDE’s output window.
Python in IDLE
Use Python’s lightweight editor and interactive shell to save and run a first program.
Python in Thonny
Start with a beginner-focused editor that makes variables and program execution easier to inspect.
Python in Jupyter Notebook
Combine Python cells, output and written notes while keeping track of the kernel that executes your code.
Edit Python in Codectionary
Write and save small Python files in the Playground; run them locally while browser execution is paused.
True
True is one of Python’s two Boolean values. It represents an affirmative result or state, such as a successful comparison or an enabled setting. Conditions also accept other truthy objects; an object does not have to be the literal True to enter an if branch.
False
False is the Boolean value for a negative result or disabled state. In a condition, Python also treats values such as zero, empty containers and None as falsy. These values share a truth-value result without being interchangeable meanings.
if
An if statement runs an indented block when its condition is truthy. Optional elif branches test further conditions in order, and else handles the case where none matched. Use it to choose actions based on data.
for
A for loop takes successive items from an iterable and assigns each item to its loop target before running the body. Lists, strings, dictionaries, ranges and generators are iterable. The number of items does not need to be known beforehand.
def
The def keyword in Python is used to define functions - reusable blocks of code that perform specific tasks. Functions are fundamental to organizing code, avoiding repetition, and making programs more maintainable. A function can accept inputs (parameters), perform operations, and return outputs. Functions are one of the core building blocks of clean, modular Python code.
class
The class keyword defines a blueprint for creating objects in Python. Classes are the foundation of Object-Oriented Programming (OOP), allowing you to bundle data (attributes) and functionality (methods) together. A class defines what attributes an object will have and what operations can be performed on it. Think of a class as a template or a factory for creating objects with similar characteristics.
None
None is Python’s singleton object used to represent the absence of a value. It can mean not yet known, not applicable or no result, depending on the API. Use is None and is not None to check for that exact sentinel.
Variables & Assignment
A variable is a name bound to an object. Assignment evaluates the expression on the right, then binds the name on the left to its result. Python determines types from objects at runtime; you do not need to declare a variable type before assigning it.
print()
print() writes readable text to a text stream, normally the terminal. It converts its arguments to strings, puts a separator between them and appends an ending. Use it to show results and inspect a small program while learning.
input()
input() displays an optional prompt, reads one line from standard input and returns a string with its trailing newline removed. It waits for a response in an interactive terminal. Convert and validate that string before treating it as a number.
Comments & Docstrings
A comment explains code to a reader and starts with # outside a string. A docstring is a string used as the first statement of a module, class or function; Python makes it available through __doc__ and tools such as help(). They serve different purposes.
Arithmetic Operators
Arithmetic operators calculate numeric results. Python provides addition (+), subtraction (-), multiplication (*), division (/), floor division (//), remainder (%) and exponentiation (**). The operand types determine the result type; the examples here use built-in integers and floats.
Comparison & Logical Operators
Comparisons test relationships between values; Boolean operators combine decisions. Comparisons between the ordinary built-in values used here return True or False. and and or short-circuit and return one of their operands; not always returns a Boolean.
Type Conversion
Conversion creates a value of a requested type when the input has a suitable representation. int(), float(), str() and bool() are common built-ins. Use explicit conversion at input boundaries rather than hoping Python will add text and numbers together.
f-Strings
An f-string is a string literal prefixed with f. Expressions inside braces are evaluated when that line runs and their formatted values become part of a new string. Use f-strings for readable messages that combine text and computed values.
String Methods
String methods transform, search or inspect text. Strings are immutable, so methods do not modify the original string. Their results have different types: upper() returns text, split() returns a list, find() returns an integer and isdigit() returns a Boolean.
Lists
A list is Python's built-in ordered, mutable collection type, created with square brackets. Lists can hold items of any type - even a mix of types - and support indexing, slicing, and a wide range of built-in methods for adding, removing, and reordering elements. Because they are mutable, lists can be changed in place after creation, which makes them the go-to structure for collections that grow or shrink over time.
Tuples
A tuple is an ordered, immutable collection, created with parentheses (or often just commas). Once created, a tuple's contents cannot be changed, added to, or removed - this immutability makes tuples faster than lists and safe to use as dictionary keys or in sets. Tuples are commonly used for fixed collections of related values, like coordinates or RGB colors, and for returning multiple values from a function.
Dictionaries
A dictionary stores data as key-value pairs, created with curly braces. Keys must be unique and hashable (strings, numbers, or tuples are common choices), while values can be anything, including other dictionaries or lists. Since Python 3.7, dictionaries maintain insertion order. They are one of the most heavily used data structures in Python, ideal for representing structured records, lookups, and mappings.
Sets
A set is an unordered collection of unique, hashable items, created with curly braces or the set() function. Sets automatically eliminate duplicates and support fast membership testing, along with mathematical set operations like union, intersection, and difference. They're especially useful for deduplicating data and for comparing two collections to find overlaps or differences.
List Comprehensions
A list comprehension is a concise, expressive way to build a new list by applying an expression to every item in an iterable, optionally filtering with a condition. It replaces the common pattern of creating an empty list and appending to it inside a for loop, condensing that logic into a single readable line. Comprehensions are considered idiomatic Python for simple to moderately complex transformations.
Dictionary & Set Comprehensions
Like list comprehensions, dictionary and set comprehensions provide a concise syntax for building dictionaries and sets from an iterable in a single expression. A dictionary comprehension produces key-value pairs with a colon, while a set comprehension looks like a list comprehension but with curly braces, automatically deduplicating results.
Slicing
Slicing extracts a sub-portion of a sequence (list, tuple, or string) using the [start:stop:step] syntax. The slice includes the start index but excludes the stop index, similar to range(). All three parts are optional, and negative indices count from the end of the sequence, making slicing a compact way to grab sub-ranges, reverse sequences, or skip elements.
len()
len() is a built-in function that returns the number of items in a collection - the character count of a string, the number of elements in a list or tuple, the number of key-value pairs in a dictionary, or the number of items in a set. It's one of the most frequently used built-in functions in Python, often paired with range() or comparisons to control loops and validate data.
Nested Data Structures
Python's collections can contain other collections, letting you model real-world structured data like JSON responses, database records, or configuration files. A list of dictionaries is common for representing multiple similar records, while a dictionary of lists groups related items under keys. Accessing nested values just means chaining index/key lookups together.
Unpacking & Multiple Assignment
Unpacking lets you assign the elements of a list, tuple, or other iterable to multiple variables in a single statement. The star operator (*) can capture 'the rest' of an iterable into a list, giving flexible patterns like grabbing the first item and everything after it. Unpacking also works when calling functions, letting you spread a list or dictionary into positional or keyword arguments.
while
A while loop checks a condition before each iteration and repeats its body while that condition is truthy. Use it when progress is controlled by changing state, such as a retry counter or validated response. A for loop instead takes successive values from an iterable, whose length need not be known.
break and continue
break exits the nearest enclosing loop. continue skips the remainder of the current iteration: a for loop moves to its next item, while a while loop checks its condition again. Use them to stop a search early or ignore irrelevant records.
pass
pass is a statement that performs no operation. It supplies a statement where Python requires a nonempty body, for example a placeholder function or a minimal exception class. Execution continues normally after it.
range()
range represents an immutable sequence of integers using a start, stop and step instead of storing every number. Use it to iterate over integer positions or repeat an action. Its stop boundary is always excluded.
Conditional (Ternary) Expression
A conditional expression chooses one of two values: value_if_true if condition else value_if_false. It is an expression, so it can appear in an assignment, a return statement or a function argument. Use an if statement when the branches perform several actions.
match / case
Introduced in Python 3.10, the match statement provides structural pattern matching - Python's answer to the switch/case statements found in many other languages, but considerably more powerful. It compares a subject value against a series of case patterns, which can match literal values, capture variables, destructure sequences and dictionaries, and even include guard conditions.
try / except
The try/except block lets your program handle errors gracefully instead of crashing. Code that might raise an exception goes in the try block; if an exception occurs, execution jumps to the matching except block instead of stopping the program. You can catch specific exception types, provide a fallback with a generic except, run cleanup code with finally regardless of whether an error occurred, and even raise your own exceptions intentionally.
lambda
A lambda is a small, anonymous, single-expression function, created without the def keyword or a name. Lambdas are restricted to a single expression whose result is automatically returned - they can't contain multiple statements or assignments. They're most useful as short, throwaway functions passed as arguments to other functions like sorted(), map(), and filter().
return
The return statement exits a function immediately and optionally sends a value back to the caller. A function can return any type - including multiple values as a tuple - or nothing at all, in which case it implicitly returns None. Once return executes, no further code in the function runs, making it useful for early exits as well as producing a final result.
*args and **kwargs
*args and **kwargs let a function accept a variable number of arguments. *args collects any extra positional arguments into a tuple, while **kwargs collects extra keyword arguments into a dictionary. The names 'args' and 'kwargs' are just convention - what matters is the * and ** prefixes. This pattern is common in wrapper functions, decorators, and APIs that need to stay flexible about their inputs.
Decorators
A decorator is a function that wraps another function to extend or modify its behavior, without changing its actual source code. Decorators use the @decorator_name syntax placed directly above a function definition, which is shorthand for passing the function into the decorator and reassigning the result. They're widely used for logging, timing, access control, caching, and validation.
Generators (yield)
A generator is a special kind of function that produces a sequence of values lazily, one at a time, using the yield keyword instead of return. Each call to yield pauses the function, remembering its state, and resumes exactly where it left off when the next value is requested. This makes generators highly memory-efficient for large or infinite sequences, since values are produced on demand rather than all at once.
map() and filter()
map() and filter() are built-in functions for applying a function across an iterable in a functional programming style. map() transforms every item by applying a function to each one, returning a lazy map object. filter() keeps only the items for which a function returns True, discarding the rest. Both are often used with lambda functions and, in modern Python, are frequently replaced by the more readable list comprehension syntax.
Recursion
Recursion is when a function calls itself to solve a smaller instance of the same problem. Every recursive function needs a base case - a condition that stops the recursion - and a recursive case that moves progressively toward that base case. Recursion is a natural fit for problems with a self-similar structure, like tree traversal, factorial calculation, and Fibonacci sequences, though it's not always the most efficient approach in Python due to function call overhead.
Closures
A closure is a function that remembers and has access to variables from its enclosing scope, even after that outer function has finished executing. This happens when an inner function is defined inside an outer function and references the outer function's variables, then gets returned or passed elsewhere. Closures are the mechanism behind function factories and are commonly used to create functions with private, persistent state.
Inheritance & super()
Inheritance lets a class (the child or subclass) reuse and extend the attributes and methods of another class (the parent or superclass), written as class Child(Parent). The built-in super() function gives access to the parent class's methods from within the child, most commonly used to call the parent's __init__ so the child doesn't have to duplicate its setup logic. Python also supports multiple inheritance, where a class inherits from more than one parent.
Magic (Dunder) Methods
Magic methods, also called dunder (double underscore) methods, let your custom classes hook into Python's built-in syntax and behavior. __init__ runs on object creation, __str__ controls how an object is displayed with print(), __eq__ and __lt__ control comparisons, __len__ controls the len() function, and __add__ lets objects respond to the + operator. Implementing these makes your custom classes feel like natural, first-class Python types.
@property
The @property decorator lets you define a method that can be accessed like a plain attribute, without parentheses. This is useful for computed values that should look like simple attributes, and for adding validation logic that runs whenever an attribute is set, via a matching @x.setter. Properties let you start with simple public attributes and later add logic without breaking any code that uses the class.
@staticmethod and @classmethod
Regular instance methods automatically receive self, the specific object they were called on. @staticmethod methods receive neither self nor the class - they behave like a plain function that just happens to live inside a class, grouped there for organizational purposes. @classmethod methods receive the class itself (conventionally named cls) instead of an instance, making them useful for alternative constructors that build an instance in a different way.
Abstract Base Classes
Abstract base classes, provided by the abc module, let you define a common interface that subclasses are required to implement. A class inheriting from ABC and using the @abstractmethod decorator cannot be instantiated directly - any concrete subclass must override every abstract method, or it can't be instantiated either. This is useful for enforcing a consistent interface across multiple related classes, similar to interfaces in other languages.
import
The import statement brings code from another module or package into the current file, letting you reuse functions, classes, and variables defined elsewhere - whether from Python's standard library, a third-party package, or your own project files. Python offers several import styles: importing an entire module, importing specific names directly, and renaming imports with 'as' to avoid naming conflicts or shorten long module names.
if __name__ == '__main__'
Every Python module has a built-in __name__ variable. When a file is run directly, __name__ is set to '__main__'; when the same file is imported into another module, __name__ is set to the module's actual name instead. The if __name__ == '__main__': guard lets you write code that only runs when the file is executed directly, not when it's imported elsewhere - essential for writing reusable modules that also work as standalone scripts.
File Handling
Python's built-in open() function reads from and writes to files on disk. Using it with the 'with' statement (a context manager) ensures the file is automatically closed when the block ends, even if an error occurs - this is the recommended way to work with files. The mode argument controls behavior: 'r' for reading, 'w' for writing (overwriting), 'a' for appending, among others.
os Module
The os module provides functions for interacting with the operating system - working with file paths, listing directory contents, creating and removing folders, and reading environment variables. Its os.path submodule (or the more modern pathlib alternative) handles cross-platform file path manipulation, so your code works correctly on Windows, macOS, and Linux without hardcoding path separators.
datetime Module
The datetime module provides classes for working with dates and times - creating them, formatting them for display, parsing them from text, and performing date arithmetic. The datetime class combines both a date and a time, while timedelta represents a duration, letting you add or subtract time spans from a date. strftime() formats a datetime as text, and strptime() parses text back into a datetime.
json Module
The json module converts between Python objects and JSON (JavaScript Object Notation) text, the standard format for exchanging data with web APIs and configuration files. json.dumps() serializes a Python object (dict, list, etc.) into a JSON string, and json.loads() parses a JSON string back into Python objects. json.dump() and json.load() do the same directly with file objects.
Python Context Managers
A context manager manages setup and cleanup around a block of code. The with statement calls its cleanup logic even when an exception interrupts the block.
Pathlib and Portable Paths
Path objects join and inspect filesystem paths without manual separator concatenation. PurePath variants perform only lexical operations; concrete Path objects can also access files. Run as a Python 3.11+ script.
Counter Frequency Tables
Counter counts hashable items and supports frequency queries without manually initializing each key. Missing counts read as zero. Run as a Python 3.11+ script.
Iterator Pipelines with itertools
itertools combines small lazy iterators to flatten and limit streams. Work happens as the result is consumed, avoiding a full intermediate list. Run as a Python 3.11+ script.
Bounded Memoization with lru_cache
lru_cache stores results by arguments and evicts least-recently-used entries when its size limit is reached. It suits repeated pure calculations with hashable inputs. Run as a Python 3.11+ script.
Dataclasses and Independent Defaults
dataclass generates initialization, representation and equality methods from annotated fields. default_factory creates a separate mutable default for each instance; annotations do not validate runtime values. Run as a Python 3.11+ script.
Decimal Arithmetic and Rounding
Decimal represents base-ten values with configurable precision and rounding. Construct from decimal strings to avoid importing binary floating-point approximation. Run as a Python 3.11+ script.
Exact Fractions
Fraction stores a reduced rational numerator and denominator, preserving exact ratios through arithmetic. A zero denominator raises ZeroDivisionError. Run as a Python 3.11+ script.
Descriptive Statistics
statistics computes common summaries without an external numerical package. Mean and median describe different aspects of a dataset, especially when outliers are present. Run as a Python 3.11+ script.
CSV Records with Headers
csv.DictReader maps header names to fields and handles quoted separators. Fields remain strings unless converted explicitly. Run as a Python 3.11+ script.
Regex Validation and Named Groups
re.fullmatch requires the entire input to satisfy a pattern. Named capture groups extract validated components without fragile numeric group positions. Run as a Python 3.11+ script.
Command-Line Arguments with argparse
ArgumentParser declares positional arguments, options, defaults and type conversion. It also generates help text and reports malformed input. Run as a Python 3.11+ script.
Named States with Enum
Enum gives a fixed set of symbolic members distinct identities and associated values. Value lookup and name lookup are different operations. Run as a Python 3.11+ script.
Priority Queues with heapq
heapq maintains a min-heap in a list, allowing efficient extraction of the smallest entry. A heap is not a fully sorted list. Run as a Python 3.11+ script.
Sorted Insertion with bisect
bisect finds insertion boundaries in an already sorted sequence. The returned index is not proof that a value exists. Run as a Python 3.11+ script.
Shallow and Deep Copies
A shallow copy creates an outer container while sharing nested objects. deepcopy recursively copies contained objects while tracking already copied references. Run as a Python 3.11+ script.
Custom Context Managers
contextmanager turns a generator function into a with-statement resource manager. Code before yield sets up the resource and finally performs cleanup even after a body exception. Run as a Python 3.11+ script.
SQLite Parameterized Queries
sqlite3 provides a local SQL database interface. Bound parameters separate data values from SQL syntax. This example uses an in-memory database and requires a Python build with sqlite3. Run as a Python 3.11+ script.
Testing Collaborators with Mock
unittest.mock replaces a collaborator with a configurable object and records calls. It helps test how code coordinates work without a live external service. Run as a Python 3.11+ script.
Dependency Ordering with graphlib
TopologicalSorter orders tasks so prerequisites precede dependents. The input maps each task to its predecessors, not to the tasks that depend on it. Available since Python 3.9. Run as a Python 3.11+ script.
Reading TOML Configuration
tomllib reads TOML into Python dictionaries and typed scalar values. It is included from Python 3.11 and does not write TOML. Run as a Python 3.11+ script.
enumerate(): counters and values
Pair each item with a running counter without managing a separate index variable.
zip(): combine iterables
Process corresponding values together and detect mismatched input lengths when truncation would be a bug.
any() and all()
Summarise a sequence of conditions with short-circuiting Boolean checks.
Sorting with keys
Order records by a selected value while preserving the original data when needed.
min() and max()
Select an extreme value or record without sorting the whole collection.
Positional-only and keyword-only parameters
Make function call conventions explicit using / and * in parameter lists.
Default arguments and mutable values
Understand when defaults are created and avoid accidentally sharing state between calls.
Variable scope and name lookup
Distinguish local bindings, enclosing function names and module-level state.
global: rebind module names
Explicitly assign to a module-level binding from a function.
nonlocal: update an enclosing binding
Keep small amounts of state in a closure without using a module-level variable.
functools.partial()
Create a callable with selected arguments already supplied.
defaultdict: initialise missing groups
Build grouped collections with a factory that supplies missing values.
deque: queues and bounded history
Use efficient operations at both ends of a collection.
Named tuples
Give a small tuple record readable field names while retaining tuple behaviour.
Bytes and text encoding
Convert between Unicode text and byte sequences deliberately at file and network boundaries.
Type hints
Describe function and collection contracts for readers, editors, and static type checkers without changing runtime validation.
TypedDict
Give dictionary records named fields and static value types while retaining ordinary dictionary behavior.
Protocol
Describe an interface by the operations an object provides, without forcing implementations to inherit a shared base class.
isinstance and issubclass
Check an object against a type hierarchy, or check whether one class derives from another.
Identity and equality
Distinguish two names pointing to the same object from two separate objects with equal values.
raise
Signal a failure explicitly and let an appropriate caller choose how to recover.
Custom exceptions
Define meaningful application failure types that callers can catch independently of implementation details.
Exception chaining
Translate low-level failures into application errors while preserving their cause for diagnosis.
assert
Document and check internal assumptions during normal debug execution, while keeping required validation explicit.
unittest
Write repeatable standard-library tests with independent cases, useful assertions, and explicit results.
logging
Record application events with severity, named loggers, and configurable destinations.
Iterator protocol
Understand how iter and next drive loops, and implement a finite custom iterator.
Generator expressions
Compute a sequence lazily with comprehension syntax, consuming values only when a caller requests them.
async and await
Define coroutines and cooperate with an event loop while awaiting operations that may suspend.
Async tasks
Schedule independent coroutines, collect their results, and manage cancellation and task lifetime.
Assignment expressions (:=)
Bind a result inside an expression when naming it there makes a condition easier to follow.
else on for and while loops
Express what happens when a loop finishes without taking a break.
Merging dictionaries
Combine settings with explicit precedence and understand the difference between copying and updating.
operator helpers
Use small standard-library callables for extracting fields and applying familiar operations.
ast.literal_eval(): parse literal data
Read a restricted Python literal representation without evaluating arbitrary Python expressions.
Temporary files and directories
Create short-lived working storage with automatic cleanup and explicit file lifetimes.
Reading package resources
Read bundled data through importlib.resources instead of assuming a path relative to the current working directory.
Time zones with zoneinfo
Represent regional time zones and convert aware datetimes without hardcoding daylight-saving offsets.
URL encoding with urllib.parse
Encode query values and path segments without confusing data with URL separators.
Reproducible randomness
Use independent pseudo-random generators for repeatable demonstrations and tests.
Java documentation
Introduction to Java
Start here to learn what Java is, why it was created, how Java programs run and where developers use it today.
How Java programs work
Follow a Java program from a .java source file through compilation, bytecode and execution on a JVM.
Install Java on Windows
Choose a JDK, install it on Windows, verify java and javac in PowerShell and run Main.java.
Install Java on macOS
Install a suitable macOS JDK for Apple Silicon or Intel, verify it in Terminal and run Main.java.
Install Java on Linux
Choose a JDK for your Linux distribution, verify the active tools and compile a first Java program.
Java in Visual Studio Code
Configure a JDK and Java extensions in VS Code, run Main.java and use a breakpoint to inspect the program.
Java in IntelliJ IDEA
Create a Java project in IntelliJ IDEA, select a JDK, run Main and debug a simple program.
Your first Java program
Create Main.java, compile it with the JDK, run it from a terminal and understand each important part of the code.
Java in Codectionary’s Playground
Understand what Codectionary’s Java editor and optional remote runner can do, where output appears and when to use a local JDK.
Variable Arguments with Varargs
Accept zero or more arguments of one type without writing a separate overload for every argument count.
Pass-by-Value and Object References
Understand why a method can mutate a supplied list but cannot replace the caller’s variable.
final Variables and Mutable Objects
Distinguish a variable that cannot be reassigned from an object whose contents cannot change.
Multiline Strings with Text Blocks
Write readable multiline text while understanding indentation and the final newline.
switch Expressions and yield
Choose a value with a switch expression instead of repeatedly assigning a result variable.
Pattern Matching for instanceof
Check an object’s type and obtain a safely typed variable in one expression.
Sealed Classes and Interfaces
Restrict which types directly extend a class or implement an interface.
Static Nested Classes
Group a helper type with its owner without requiring an enclosing object instance.
Automatic Cleanup with try-with-resources
Close AutoCloseable resources reliably when a block finishes normally or exceptionally.
Custom Checked Exceptions
Name a domain-specific failure and make callers handle or declare it.
Generic Wildcards: extends and super
Read numeric values from producers and add integers to compatible consumers safely.
Combining Predicates
Build reusable true-or-false rules with Predicate, and, or and negate.
Function Composition with andThen and compose
Connect small transformations and understand which operation runs first.
Unmodifiable Snapshots with List.copyOf
Take a stable list snapshot while understanding shallow copying and null restrictions.
Unmodifiable Views versus Copies
Expose a read-only list view that still reflects changes made through the backing list.
Grouping Values with computeIfAbsent
Create a missing map value on demand before adding an item to it.
Frequency Counts with Map.merge
Combine repeated keys with a clear rule for updating their values.
Removing Matching Items with removeIf
Remove collection elements using a predicate instead of modifying a list inside a for-each loop.
Sorting by Multiple Fields
Sort by one key and use a second key only when the first values compare equally.
Enum Keys with EnumMap
Use a specialised map when every key belongs to one enum type.
Flattening Nested Data with flatMap
Turn a stream of groups into one stream of individual items.
Grouping Stream Results with groupingBy
Collect elements into groups using a key calculated from each element.
Splitting Results with partitioningBy
Divide a stream into true and false groups using one condition.
Duplicate Keys in Collectors.toMap
Choose an explicit merge rule when several stream elements produce the same map key.
Numeric Summary Statistics
Compute a count, sum, minimum, maximum and average in one numeric stream traversal.
Stream Prefixes with takeWhile and dropWhile
Process the matching prefix of an ordered stream and distinguish it from filtering.
Calendar Amounts with Period
Represent date-based years, months and days without treating every month as a fixed duration.
Testable Time with Clock
Supply the current time as a dependency so date-dependent logic can be tested consistently.
Unicode Code Points and String Length
Understand why String.length can differ from the number of Unicode code points.
Detecting Integer Overflow with Math.addExact
Detect arithmetic overflow explicitly instead of accepting a wrapped integer result.
Classes
Classes in Java are blueprints for creating objects, defining their properties (fields) and behaviors (methods). Java is a strictly object-oriented language where everything is encapsulated within classes. A class serves as a template that specifies what data an object will store and what operations it can perform.
Variables & Primitive Data Types
Java is a statically-typed language, meaning every variable must be declared with an explicit type before use, and that type cannot change afterward. Java has eight primitive types - byte, short, int, long, float, double, char, and boolean - which store simple values directly rather than references, making them fast and memory-efficient. Anything beyond primitives (String, arrays, custom classes) is a reference type instead.
System.out.println / print / printf
System.out is Java's standard output stream, and it exposes three main methods for writing text to the console. println() prints its argument followed by a newline, print() prints without adding a newline, and printf() gives C-style formatted output using format specifiers like %d, %s, and %.2f for precise control over how values are displayed.
Comments & Javadoc
Java supports single-line comments with //, multi-line comments with /* */, and a special documentation format called Javadoc, written as /** */. Javadoc comments support tags like @param, @return, and @throws, and can be processed by the javadoc tool to automatically generate HTML API documentation - the same format used for Java's own official standard library docs.
Arithmetic & Assignment Operators
Java provides the standard arithmetic operators for numeric computation: +, -, *, / for division, and % for the remainder (modulus). It also has compound assignment operators (+=, -=, etc.) that combine an operation with assignment, along with increment (++) and decrement (--) operators in both prefix and postfix forms, which subtly differ in when the value is updated relative to being used.
Comparison & Logical Operators
Comparison operators (==, !=, <, >, <=, >=) compare two values and evaluate to a boolean. Logical operators (&&, ||, !) combine or invert boolean expressions, with && and || short-circuiting - meaning the second operand is skipped entirely if the first already determines the result. Importantly, == compares object references for non-primitive types like String, so .equals() should be used to compare their actual content.
Strings & String Methods
String is one of the most heavily used classes in Java, representing an immutable sequence of characters - once created, a String's content can never change, and every 'modifying' method actually returns a brand new String. Java offers a rich set of built-in methods for common operations like extracting substrings, searching, splitting, and case conversion.
Type Casting
Type casting converts a value from one data type to another. Widening (implicit) casting happens automatically when converting a smaller type to a larger one, like int to double, since no data can be lost. Narrowing (explicit) casting requires you to manually write the target type in parentheses, since converting a larger type to a smaller one - like double to int - can lose data or precision.
Arrays
An array in Java is a fixed-size, ordered collection of elements of the same type, stored in contiguous memory for efficient access. Once created, an array's length cannot change - if you need a resizable collection, use an ArrayList instead. Arrays can be one-dimensional or multi-dimensional (arrays of arrays), and are zero-indexed like most Java collections.
if / else if / else
The if statement executes a block of code only when its condition evaluates to true. Java lets you chain additional conditions with else if, and provide a fallback with else for when none of the preceding conditions match. Unlike some languages, Java requires the condition to be an actual boolean expression - it cannot use a number or object directly as a truthy/falsy value.
switch Statement
The switch statement compares a single value against multiple possible cases, offering a cleaner alternative to a long else if chain when checking one variable against many discrete values. Traditional switch statements require a break after each case to prevent 'fall-through' into the next case. Java 14+ introduced a modernized switch expression syntax using arrows (->) that eliminates fall-through and can directly return a value.
for Loop
Learn Java for loops: initialise a counter, test a condition and update it. Compare indexed loops with the enhanced for loop for arrays and collections.
while and do-while Loops
Compare while and do-while loops in Java, including when conditions are checked and why a do-while body always runs at least once.
break and continue
break and continue give fine-grained control over loop execution in Java. break immediately exits the nearest enclosing loop (or switch statement) entirely. continue skips the rest of the current iteration and jumps straight to the loop's next iteration check. Java also supports labeled break/continue, which can target an outer loop from within a nested one.
Scanner (User Input)
The Scanner class, from java.util, reads input from various sources - most commonly System.in for keyboard input from the console. It provides typed methods like nextInt(), nextDouble(), and nextLine() to read and parse input directly into the desired type, avoiding manual string conversion. Scanner must be imported explicitly since it's not part of java.lang.
Methods
A method is a named, reusable block of code that performs a specific task, defined with a return type, a name, and a parameter list. Methods can return a value (with any type, including primitives and objects) or return nothing at all using the void keyword. Java supports method overloading, where multiple methods share the same name but differ in their parameter lists.
Wrapper Classes & Autoboxing
Every Java primitive type has a corresponding wrapper class - int has Integer, double has Double, boolean has Boolean, and so on. Wrapper classes turn primitive values into full objects, which is necessary when working with generics or collections like ArrayList, since those can only hold objects, not primitives. Autoboxing and unboxing let Java automatically convert between a primitive and its wrapper class as needed.
Interfaces
An interface defines a contract of methods that implementing classes must provide, without specifying how those methods work internally. Unlike a class, an interface cannot be instantiated directly - it only declares what a class can do, not how. A class uses the 'implements' keyword to fulfill an interface's contract, and a single class can implement multiple interfaces, which is Java's way of achieving a form of multiple inheritance.
Abstract Classes
Understand Java abstract classes: share fields and implemented methods, declare abstract methods and implement them in concrete subclasses.
Constructors
A constructor is a special method that runs automatically when an object is created with 'new', typically used to initialize the object's fields. A constructor shares its name with the class and has no return type, not even void. Java supports constructor overloading, letting a class offer multiple ways to construct an object, and constructor chaining with this(...), where one constructor calls another in the same class.
Access Modifiers
Access modifiers control the visibility of classes, fields, and methods from other parts of a program. Java has four levels: public (accessible from anywhere), protected (accessible within the same package and by subclasses), default/package-private (accessible only within the same package, used when no modifier is written), and private (accessible only within the declaring class itself).
Method Overloading
Method overloading lets a class define multiple methods with the same name but different parameter lists - differing in the number, type, or order of parameters. Java determines which overload to call at compile time based on the arguments provided. Note that overloading is different from overriding: overloading is about multiple methods with the same name in the same class, while overriding replaces a parent class's method in a subclass.
Method Overriding & @Override
Method overriding lets a subclass provide its own specific implementation of a method already defined in its parent class, replacing the inherited behavior. The overriding method must have the same name, return type (or a covariant subtype), and parameter list as the parent's version. The @Override annotation isn't strictly required, but it tells the compiler to verify you're actually overriding a real parent method, catching typos at compile time instead of silently creating an unrelated new method.
this and super Keywords
The 'this' keyword refers to the current object instance, most often used to distinguish between a field and a constructor/method parameter that share the same name, or to chain constructors. The 'super' keyword refers to the parent class, used to call the parent's constructor, access a parent field, or invoke a parent method that has been overridden.
Polymorphism
Polymorphism - literally 'many forms' - lets objects of different subclasses be treated through a common parent type or interface, while each object still behaves according to its own specific class at runtime. This is achieved through method overriding: a variable declared with a parent type can hold any subclass object, and calling an overridden method automatically runs the correct subclass version, a mechanism called dynamic (runtime) dispatch.
Enums
An enum (enumeration) is a special Java type used to define a fixed set of named constants, like the days of the week or possible states of an order. Enums are type-safe - the compiler ensures only valid enum values can be assigned - and, unlike simple constants, they are full classes that can have fields, constructors, and methods of their own.
Records
Introduced as a standard feature in Java 16, a record is a compact way to declare an immutable data-carrier class. Writing 'record Point(int x, int y) {}' automatically generates a constructor, private final fields, public accessor methods, plus equals(), hashCode(), and toString() - all the boilerplate that would otherwise need to be written by hand for a simple immutable class.
equals(), hashCode(), and toString()
Every Java class inherits equals(), hashCode(), and toString() from Object, but their default implementations are rarely useful - default equals() checks reference identity (like ==), default hashCode() is based on memory address, and default toString() prints an unreadable class name plus hash code. Overriding all three properly is essential for any class you plan to compare by value, print for debugging, or store in hash-based collections like HashMap or HashSet.
Exception Handling
Java uses exceptions to signal that something went wrong during execution. Checked exceptions (like IOException) must be either caught or declared with 'throws' in the method signature, enforced by the compiler, while unchecked exceptions (like NullPointerException, extending RuntimeException) do not require this. A try block wraps risky code, one or more catch blocks handle specific exception types, and an optional finally block always runs for cleanup.
Generics
Generics let you write classes, interfaces, and methods that work with any type while still enforcing type safety at compile time, rather than at runtime. Instead of writing a separate class for each type you want to support, a generic class like Box<T> can hold any type T, with the compiler catching type mismatches before the code ever runs. Type parameters conventionally use single uppercase letters like T, E, K, and V.
ArrayList
ArrayList is a resizable array implementation of the List interface, part of java.util. Unlike a plain array, an ArrayList automatically grows as elements are added, and it provides a rich set of methods for adding, removing, searching, and iterating. Since generics require object types, an ArrayList of primitives (like int) actually stores their wrapper class (Integer) via autoboxing.
LinkedList
LinkedList is a doubly-linked list implementation of both the List and Deque interfaces. Unlike ArrayList, it stores elements as individual nodes linked to their neighbors, which makes inserting and removing elements at the beginning or middle much faster, at the cost of slower random access by index. Because it implements Deque, LinkedList can also be used directly as a stack or queue.
HashMap
HashMap stores data as key-value pairs, offering constant-time (average case) lookup, insertion, and deletion by key, backed by a hash table. Keys must be unique - adding a value with an existing key overwrites the previous value. HashMap does not guarantee any particular ordering of its entries, unlike LinkedHashMap (which preserves insertion order) or TreeMap (which keeps keys sorted).
HashSet
HashSet is a collection that stores unique elements with no guaranteed ordering, backed by a HashMap internally. Adding a duplicate element has no effect, since HashSet automatically enforces uniqueness. It provides constant-time (average case) performance for adding, removing, and checking membership, making it ideal for deduplication and fast lookups.
TreeMap & TreeSet
TreeMap and TreeSet are sorted collections backed by a red-black tree, automatically keeping their keys (or elements) in ascending order at all times. This ordering comes at a cost - operations run in logarithmic time rather than the constant time of HashMap/HashSet - but it's invaluable when you need sorted iteration, range queries, or to quickly find the smallest or largest element.
Iterator
An Iterator provides a standard way to traverse a collection one element at a time without exposing its internal structure, using hasNext() to check for more elements and next() to retrieve the next one. Unlike a for-each loop, an Iterator's remove() method lets you safely delete elements from a collection while iterating over it - directly modifying a collection during a for-each loop throws a ConcurrentModificationException.
Collections Utility Class
java.util.Collections is a utility class full of static helper methods for working with collections - sorting, shuffling, finding the minimum/maximum, reversing order, and creating unmodifiable or synchronized wrapper collections. It's distinct from the Collection interface itself (singular), which is the root interface that List, Set, and Queue all extend.
Arrays Utility Class
java.util.Arrays is a utility class providing static helper methods specifically for working with arrays - sorting, searching, filling, comparing, copying, and converting to a readable String or a List. Since arrays don't have built-in methods of their own the way ArrayList does, this utility class fills that gap for common array tasks.
Queue & Deque
Queue is an interface representing a first-in-first-out (FIFO) collection, typically implemented by LinkedList or the more efficient ArrayDeque. Deque (double-ended queue) extends Queue and allows insertion and removal at both ends, making it suitable for both queue (FIFO) and stack (LIFO) behavior. Queue methods come in two flavors: ones that throw an exception on failure (add, remove) and safer ones that return a special value instead (offer, poll).
Comparable & Comparator
Comparable and Comparator both define how to order objects, but serve different purposes. A class implements Comparable<T> to define its single 'natural' ordering via compareTo(), used automatically by Collections.sort() and TreeSet. A Comparator is a separate object passed alongside a collection to define one or more custom, alternative orderings, without modifying the class being sorted at all.
Lambda Expressions
A lambda expression is a compact way to represent an anonymous function - a block of code that can be passed around as a value. Lambdas work with functional interfaces (interfaces with exactly one abstract method), letting you replace a full anonymous class implementation with a short, focused expression. Lambdas are the foundation that makes Java's Stream API and functional-style programming possible.
Stream Basics (map, filter, forEach)
The Stream API, introduced in Java 8, provides a functional, declarative way to process sequences of elements from collections, arrays, or other sources. A stream pipeline consists of a source, zero or more intermediate operations (like filter and map, which are lazy and return a new stream), and exactly one terminal operation (like forEach or collect) that actually triggers processing.
Stream Terminal Operations
Terminal operations are what actually trigger a stream pipeline to execute and produce a final result, consuming the stream in the process - after a terminal operation runs, the stream cannot be reused. Common terminal operations include reduce() for combining elements into a single value, count(), sum-style operations for numeric streams, anyMatch()/allMatch() for boolean checks, and findFirst() for retrieving a single element.
Collectors
Collectors, used with the stream terminal operation collect(), provide ready-made ways to accumulate stream elements into a final result - a List, Set, Map, a joined String, or grouped/partitioned data. The java.util.stream.Collectors class offers factory methods like toList(), joining(), groupingBy(), and counting() that cover the vast majority of real-world aggregation needs.
Optional
Optional<T> is a container object that may or may not hold a non-null value, designed to make the possibility of 'no result' explicit in a method's return type, reducing NullPointerExceptions. Rather than returning null and hoping callers remember to check for it, a method returning Optional<T> signals clearly that a value might be absent, and provides safe methods like isPresent(), ifPresent(), and orElse() for handling both cases.
Method References
A method reference is shorthand syntax for a lambda that does nothing but call an existing method, using the :: operator. Java supports four kinds: a reference to a static method (ClassName::staticMethod), an instance method on a particular object (object::instanceMethod), an instance method on an arbitrary object of a type (ClassName::instanceMethod), and a constructor reference (ClassName::new).
Creating Threads (Thread & Runnable)
A thread is an independent path of execution within a program, letting multiple tasks run seemingly simultaneously. Java offers two main ways to create a thread: extending the Thread class directly and overriding its run() method, or implementing the Runnable interface and passing it to a Thread - the Runnable approach is generally preferred, since Java doesn't support multiple inheritance and Runnable keeps your class free to extend something else.
synchronized Keyword
The synchronized keyword prevents multiple threads from executing a block of code (or a method) at the same time on the same object, protecting shared, mutable data from race conditions. When one thread enters a synchronized block, it acquires a lock on the specified object; any other thread trying to enter a synchronized block on that same object must wait until the lock is released.
ExecutorService & Thread Pools
ExecutorService, from java.util.concurrent, manages a pool of reusable threads, letting you submit tasks without manually creating and managing individual Thread objects. This avoids the overhead of constantly creating new threads and gives you control over how many run concurrently. Executors provides convenient factory methods for common pool configurations, like a fixed-size pool or a single-threaded executor.
Atomic Variables
Classes like AtomicInteger, AtomicLong, and AtomicBoolean, from java.util.concurrent.atomic, provide thread-safe operations on single variables without needing explicit synchronized blocks. They use low-level, lock-free CPU instructions (compare-and-swap) to guarantee that operations like incrementAndGet() are atomic - performed as a single, uninterruptible step - even when many threads use them concurrently.
Thread Control: sleep, join, interrupt
Java provides several methods for coordinating and controlling thread execution. Thread.sleep() pauses the current thread for a specified duration. join() makes the calling thread wait until another thread finishes before continuing. interrupt() signals a thread that it should stop what it's doing, a cooperative mechanism the target thread must actively check for and respond to.
Java File Handling
Use Path to identify a file and Files to read or write it. These examples require Java 11 or later. Save each as Main.java, then run javac Main.java and java Main. I/O operations can throw IOException.
BigDecimal and Explicit Rounding
BigDecimal performs arbitrary-precision decimal arithmetic with an explicit scale. String constructors preserve decimal input exactly; division may require a rounding policy. Save as Main.java and run with a Java 17+ JDK: java Main.java.
BigInteger Arithmetic
BigInteger stores integers beyond the range of long. Its immutable arithmetic methods return new values and avoid primitive integer overflow. Save as Main.java and run with a Java 17+ JDK: java Main.java.
Regular Expressions with Pattern
Pattern compiles a reusable regex while Matcher holds the state of a particular search. matches validates the entire input; find searches for the next matching region. Save as Main.java and run with a Java 17+ JDK: java Main.java.
Calendar Dates with LocalDate
LocalDate models a calendar date without time or time zone. Date arithmetic handles month lengths and leap years while returning immutable results. Save as Main.java and run with a Java 17+ JDK: java Main.java.
Elapsed Time with Duration
Duration measures an amount of time in seconds and nanoseconds. Unlike a calendar period, a duration day is exactly 24 hours. Save as Main.java and run with a Java 17+ JDK: java Main.java.
Time Zone Conversion
ZonedDateTime combines a local date/time with zone rules. withZoneSameInstant changes the displayed clock time while preserving the actual instant. Save as Main.java and run with a Java 17+ JDK: java Main.java.
Strict Date Parsing
DateTimeFormatter defines reusable, immutable date formats. Strict resolution rejects impossible calendar dates instead of normalizing them. Save as Main.java and run with a Java 17+ JDK: java Main.java.
UUID Identifiers
UUID models a 128-bit identifier and provides parsing, formatting and generation. A UUID identifies a record; it does not grant access to that record. Save as Main.java and run with a Java 17+ JDK: java Main.java.
Base64 Binary Encoding
Base64 converts bytes into a transport-friendly text representation. Java provides basic, MIME and URL-safe variants; these encodings do not encrypt data. Save as Main.java and run with a Java 17+ JDK: java Main.java.
SHA-256 Content Digests
MessageDigest computes a fixed-size digest from bytes, useful for content fingerprints and integrity checks against a trusted reference. Save as Main.java and run with a Java 17+ JDK: java Main.java.
Properties Configuration
Properties reads and stores string-valued configuration, with defaults for absent keys. Reader-based loading lets the caller choose character decoding. Save as Main.java and run with a Java 17+ JDK: java Main.java.
Building Text with StringBuilder
StringBuilder is a mutable character buffer for accumulating text across multiple steps. toString produces the final immutable String. Save as Main.java and run with a Java 17+ JDK: java Main.java.
EnumSet Membership
EnumSet stores members of one enum type compactly. It gives type-safe membership operations for feature selections or permissions. Save as Main.java and run with a Java 17+ JDK: java Main.java.
PriorityQueue Scheduling
PriorityQueue removes the least element according to natural ordering or a supplied comparator. Its iterator does not promise sorted traversal. Save as Main.java and run with a Java 17+ JDK: java Main.java.
BitSet Index Sets
BitSet represents a growable collection of boolean flags indexed by nonnegative integers. Logical operations efficiently combine groups of active indices. Save as Main.java and run with a Java 17+ JDK: java Main.java.
CompletableFuture Pipelines
CompletableFuture composes dependent computations. thenApply transforms a result, while thenCompose flattens an operation that itself returns a future. Save as Main.java and run with a Java 17+ JDK: java Main.java.
CountDownLatch Coordination
CountDownLatch lets one thread wait until a fixed number of completion signals arrive. Once opened, a latch remains open and cannot be reset. Save as Main.java and run with a Java 17+ JDK: java Main.java.
Semaphore Capacity Limits
Semaphore limits concurrent access with permits. Each successful acquisition must be paired with a release, even when the protected operation throws. Save as Main.java and run with a Java 17+ JDK: java Main.java.
Atomic Concurrent Map Updates
ConcurrentHashMap provides thread-safe map operations. merge performs a read/modify/write update atomically for one key, unlike a separate get followed by put. Save as Main.java and run with a Java 17+ JDK: java Main.java.
Explicit Locking with ReentrantLock
ReentrantLock provides explicit mutual exclusion with optional timed or interruptible acquisition. The same thread may acquire it repeatedly, but must unlock the same number of times. Save as Main.java and run with a Java 17+ JDK: java Main.java.
C# documentation
Introduction to C#
Start here to learn what C# is, where it came from, how it works with .NET, and the different kinds of applications you can build with it.
Install C# and .NET on Windows
Install a supported .NET SDK on Windows, verify it in PowerShell, and create a console project.
Install C# and .NET on macOS
Choose the correct Intel or Apple Silicon .NET SDK installer, verify it in Terminal, and set up a supported editor.
Install C# and .NET on Linux
Choose a supported distribution package source, install the .NET SDK, and verify the build tools.
Your first C# program
Create a .NET console project, write and run a C# greeting, understand the syntax, and resolve common first-project errors.
Set up C# in Visual Studio
Install a supported Visual Studio on Windows, create and run a C# console app, and use its debugger and Error List.
Set up C# in JetBrains Rider
Install Rider, connect a supported .NET SDK, create and debug a C# console project, and understand its licence options.
C# projects and solutions
Understand C# source files, project and solution files, target frameworks, dependencies and Debug and Release builds.
NuGet packages in .NET projects
Learn what NuGet packages are, add a verified package, restore dependencies and inspect requested and resolved versions.
C# in the Codectionary Playground
Learn exactly what Codectionary’s Playground can do with C# files, why Run does not compile them, and how to run C# locally with the .NET SDK.
Variables & Data Types
C# is a statically-typed language, meaning every variable's type is fixed at compile time. Built-in value types include int, double, decimal, bool, and char, while string and object are reference types. The var keyword lets the compiler infer a variable's type from its initializer, but the variable is still strongly typed underneath - it just saves you from writing the type name explicitly.
Console.WriteLine / ReadLine
The Console class, from the System namespace, provides the standard way to read from and write to the terminal in a C# console application. Console.WriteLine() prints a value followed by a newline, Console.Write() prints without one, and Console.ReadLine() reads a full line of text typed by the user, returning a string or null at the end of input.
Comments & XML Documentation
C# supports single-line comments with //, multi-line comments with /* */, and a special triple-slash XML documentation format (///) placed above a member. XML doc comments support tags like <summary>, <param>, and <returns>, and are used by Visual Studio and other IDEs to power IntelliSense tooltips and can be compiled into full API documentation.
Arithmetic & Assignment Operators
C# provides the standard arithmetic operators for numeric computation: +, -, *, / for division, and % for the remainder. Integer division truncates any decimal part, just as in many C-family languages. Compound assignment operators (+=, -=, etc.) combine an operation with assignment, and increment/decrement operators (++, --) come in prefix and postfix forms that differ subtly in when the value updates relative to being used.
Comparison & Logical Operators
Comparison operators (==, !=, <, >, <=, >=) compare two values and produce a bool. Logical operators (&&, ||, !) combine or invert boolean expressions, with && and || short-circuiting so the second operand is skipped once the result is already determined. For strings, == compares content by default (unlike some languages), since string overrides the equality operator.
Strings & String Interpolation
string represents an immutable sequence of characters in C# - once created, its content never changes, and every 'modifying' operation returns a new string. String interpolation, using the $ prefix, is the modern, preferred way to embed expressions directly inside a string literal, replacing older approaches like string.Format() or manual concatenation with +.
String Methods
The string class provides a large set of built-in methods for searching, transforming, splitting, and validating text. Common ones include Split() and Join() for converting between a string and an array, Replace() for substitution, and a family of Is-prefixed static helpers like string.IsNullOrEmpty() for validation. Since strings are immutable, every transforming method returns a new string.
Type Conversion & Casting
C# supports implicit conversions (widening, like int to double) that happen automatically since no data is lost, and explicit casts (narrowing, like double to int) that require writing the target type in parentheses since precision could be lost. For converting between fundamentally different types, like string and int, the Convert class and each type's Parse()/TryParse() methods are used instead of a direct cast.
Arrays
An array in C# is a fixed-size, ordered collection of elements of the same type, zero-indexed like most C# collections. Once created, an array's length cannot change - use a List<T> instead if you need a resizable collection. C# supports single-dimensional arrays, multi-dimensional arrays (a true grid, declared with a comma like int[,]), and jagged arrays (an array of arrays, where each inner array can have a different length).
if / else if / else
The if statement executes a block of code only when its condition evaluates to true. C# lets you chain additional conditions with else if, and provide a fallback with else for when none of the preceding conditions match. The condition must be a genuine bool expression - unlike some C-family languages, C# does not allow a number to be used directly as a truthy/falsy condition.
switch Statement & Expression
The switch statement compares a single value against multiple possible cases. Traditional C# switch statements require a break after each case. Modern C# (8.0+) also offers a more concise switch expression using arrow (=>) syntax that directly evaluates to a value, supports pattern matching, and eliminates the need for break entirely.
for Loop
Use a C# for loop to repeat work over an index range. Follow the initializer, Boolean condition and iterator through practical examples.
while and do-while Loops
Write condition-controlled loops in C# with while and do-while. Understand Boolean conditions, repeated work and when the loop stops.
break and continue
break and continue give fine-grained control over loop execution. break immediately exits the nearest enclosing loop (or switch statement) entirely, skipping any remaining iterations. continue skips just the rest of the current iteration and jumps straight to the loop's next condition check, without exiting the loop.
Classes & Objects
A class is a blueprint for creating objects, bundling related data (fields/properties) and behavior (methods) together. C# is a fully object-oriented language - every application has at least one class, typically with a Main method as its entry point. An object is a specific instance of a class, created with the new keyword, with its own independent copy of the class's instance data.
Constructors
A constructor is a special method that runs automatically when an object is created with new, used to initialize the object's state. A constructor shares its name with the class and has no return type. C# supports constructor overloading (multiple constructors with different parameter lists) and constructor chaining with this(...), where one constructor calls another in the same class to avoid duplicating initialization logic.
Properties (get/set)
Properties are C#'s idiomatic way to expose class data through accessor-like syntax while still allowing controlled access via get and set. Unlike a plain public field, a property can validate a value before it's set, compute a value on the fly, or restrict access to read-only. Auto-implemented properties (using { get; set; } with no body) provide a concise shorthand when no custom logic is needed.
Access Modifiers
Access modifiers control the visibility of classes, fields, methods, and properties from other parts of a program. C# provides public (accessible from anywhere), private (accessible only within the declaring class - the default for class members), protected (accessible within the class and its subclasses), internal (accessible only within the same assembly/project), and combinations like protected internal and private protected.
Inheritance & base
Inheritance lets a class (the derived or child class) reuse and extend the members of another class (the base or parent class), written as class Child : Parent. The base keyword gives access to the parent class's members from within the child, most commonly used to call the parent's constructor so the child doesn't have to duplicate its setup logic. Unlike some languages, C# only supports single class inheritance - a class can extend just one base class, but can implement multiple interfaces.
Polymorphism
Polymorphism lets objects of different derived classes be treated through a common base type or interface, while each object still behaves according to its own specific class at runtime. This is achieved through virtual/override method pairs: a variable declared with a base type can hold any derived class object, and calling an overridden method automatically runs the correct derived version - a mechanism called dynamic dispatch.
Interfaces
An interface defines a contract of members that implementing classes must provide, without specifying how those members work internally. By convention, interface names start with a capital I (IShape, IComparable). Unlike a class, an interface cannot be instantiated directly. A class uses a colon to implement an interface, and a single class can implement multiple interfaces - C#'s way of achieving a form of multiple inheritance.
Abstract Classes
Understand C# abstract classes, shared implementation and abstract methods. See how concrete derived classes use override to supply method bodies.
Method Overloading
Method overloading lets a class define multiple methods with the same name but different parameter lists, differing in the number, type, or order of parameters. C# resolves which overload to call at compile time based on the arguments provided. C# also supports optional parameters (with a default value) and named arguments, which can reduce the need for overloads in some cases.
Enums
An enum defines a fixed set of named integer constants, like the days of the week or the possible states of an order. Enums are type-safe - the compiler ensures only valid enum values can be assigned - and each constant maps to an underlying integer by default (starting at 0), though you can assign custom values explicitly.
Records
Introduced in C# 9, a record is a reference type designed for immutable data, with built-in value-based equality - two records are considered equal if all their properties match, unlike classes which compare by reference. Declaring a record with positional syntax automatically generates a constructor, init-only properties, plus Equals(), GetHashCode(), ToString(), and a Deconstruct method - all boilerplate that would otherwise be written by hand.
Exception Handling
C# uses exceptions to signal that something went wrong during execution. A try block wraps risky code, one or more catch blocks handle specific exception types, and an optional finally block always runs for cleanup, whether or not an exception occurred. Unlike Java, C# does not have checked exceptions - the compiler never forces you to catch or declare an exception, though catching specific, meaningful types is still best practice.
Generics
Generics let you write classes, interfaces, and methods that work with any type while still enforcing type safety at compile time. Instead of writing a separate class for each type you want to support, a generic class like Box<T> can hold any type T, with the compiler catching type mismatches before the code ever runs. Type parameters conventionally use T, or a more descriptive name prefixed with T (TKey, TValue) for clarity.
Structs
A struct is a value type, defined much like a class but with a key difference: structs are copied by value when assigned or passed to a method, while classes are copied by reference. This makes structs efficient for small, simple data groupings (like coordinates or colors) where copy semantics are actually desirable, avoiding heap allocation and garbage collection overhead.
List<T>
List<T> is a resizable, generic collection from System.Collections.Generic, and the most commonly used collection type in C#. Unlike a plain array, a List<T> automatically grows as elements are added, and it provides a rich set of methods for adding, removing, searching, and sorting. The <T> means a List can be strongly typed to hold any specific type, like List<string> or List<int>.
Dictionary<TKey, TValue>
Dictionary<TKey, TValue> stores data as key-value pairs, offering fast average-case lookup, insertion, and deletion by key, backed by a hash table. Keys must be unique - adding a value with an existing key throws an exception, while indexer assignment (dict[key] = value) overwrites it instead. Dictionary does not guarantee any particular iteration order.
Queue<T> & Stack<T>
Queue<T> is a first-in-first-out (FIFO) collection - items are added with Enqueue() and removed with Dequeue(), just like a real-world line. Stack<T> is last-in-first-out (LIFO) - items are added with Push() and removed with Pop(), like a stack of plates. Both are useful for specific processing orders where a general-purpose List<T> would require extra bookkeeping.
HashSet<T>
HashSet<T> is a collection that stores unique elements with no guaranteed ordering, backed by a hash table. Adding a duplicate element has no effect, since HashSet automatically enforces uniqueness. It provides very fast average-case performance for adding, removing, and checking membership, and offers built-in set operations like union, intersection, and difference.
foreach & IEnumerable
foreach is C#'s dedicated loop for iterating over any collection that implements IEnumerable<T> - which includes arrays, List<T>, Dictionary<TKey,TValue>, and virtually every built-in collection. Behind the scenes, foreach uses an enumerator (via GetEnumerator()) to walk through items one at a time. Any custom class can support foreach by implementing IEnumerable<T> itself.
Array Class & Utility Methods
The static Array class, from the System namespace, provides utility methods for working with arrays - sorting, searching, resizing, and copying. Since arrays don't have many built-in instance methods of their own (unlike List<T>), this utility class fills that gap for common array tasks like Array.Sort(), Array.BinarySearch(), and Array.Resize().
IComparable & IComparer
IComparable<T> and IComparer<T> both define how to order objects, but serve different purposes. A class implements IComparable<T> to define its single 'natural' ordering via CompareTo(), used automatically by List<T>.Sort() and Array.Sort(). An IComparer<T> is a separate object passed alongside a collection to define one or more custom, alternative orderings, without modifying the class being sorted at all.
LinkedList<T>
LinkedList<T> is a doubly-linked list implementation from System.Collections.Generic. Unlike List<T>, it stores elements as individual nodes linked to their neighbors, which makes inserting and removing elements at the beginning, end, or middle (given a reference to the node) very fast, at the cost of slower access by index, since reaching a specific position means walking the chain.
Lambda Expressions
A lambda expression is a compact way to represent an anonymous function - a block of code that can be passed around as a value, using the => (goes to) operator. Lambdas work with delegate types and functional interfaces like Func<> and Action<>, letting you write inline logic without a full named method. Lambdas are the foundation that makes LINQ's fluent, expressive query syntax possible.
LINQ Basics: Where & Select
LINQ (Language Integrated Query) provides a consistent, declarative way to query collections, databases, and XML directly within C# syntax. Where() filters a sequence down to elements matching a condition, and Select() transforms each element into something new (a projection). Both are 'lazy' - they build a query that only actually runs when you iterate over the result or call something like ToList().
LINQ Ordering & Grouping
OrderBy() and OrderByDescending() sort a sequence by a key you specify, with ThenBy() for secondary sort keys on ties. GroupBy() splits a sequence into groups based on a key selector, producing a sequence of groups where each group itself is enumerable and has a Key property identifying which group it represents.
LINQ Aggregation: Sum, Count, Average
LINQ provides built-in aggregation methods that reduce a sequence down to a single summary value: Count() for the number of elements, Sum() for a total, Average() for the mean, and Max()/Min() for extremes. Aggregate() is the general-purpose version, letting you define fully custom accumulation logic when the built-in methods aren't enough.
LINQ Element & Quantifier Operators
Element operators retrieve a single item from a sequence: First()/FirstOrDefault() for the first match, Single()/SingleOrDefault() for exactly one match, with 'OrDefault' variants returning a default value instead of throwing when nothing matches. Quantifier operators return a bool describing the sequence as a whole: Any() checks if at least one element matches, and All() checks if every element matches.
LINQ Deferred Execution
Most LINQ operators (Where, Select, OrderBy, etc.) use deferred execution - they don't actually run when you write the query, only when you enumerate the result, such as with a foreach loop or a call to ToList(). This means a deferred query re-runs every time you enumerate it, picking up any changes to the underlying data source since it was defined, which can be surprising if not understood.
async and await
The async and await keywords let you write asynchronous code that reads almost like ordinary sequential code. Marking a method async allows it to use await, which pauses execution at that point until the awaited operation completes, without blocking the calling thread - freeing it up to do other work in the meantime. This is essential for keeping applications responsive during I/O-bound work like network calls, file access, or database queries.
Task & Task<T>
Task represents an asynchronous operation that may still be running, and Task<T> represents one that will eventually produce a value of type T. Tasks are the building block that async/await is built on top of - an async method actually returns a Task (or Task<T>) that the caller can await, check the status of, or attach continuations to.
Task.WhenAll & Task.WhenAny
Task.WhenAll() lets you run multiple independent asynchronous operations concurrently and await all of them together, completing once every task finishes - much faster than awaiting them one at a time. Task.WhenAny() completes as soon as the first of several tasks finishes, useful for timeout patterns or taking whichever result arrives first.
CancellationToken
CancellationToken provides a standard, cooperative way to signal that an asynchronous operation should stop before it completes naturally. A CancellationTokenSource creates the token and controls when cancellation is requested; the token itself is passed into async methods, which check it periodically (or pass it to another cancellable operation) and can throw an OperationCanceledException to unwind cleanly.
Async Pitfalls: void vs Task, ConfigureAwait
A few recurring mistakes trip up many C# developers new to async: using async void instead of async Task (which makes exceptions impossible to catch normally), and blocking on async code with .Result or .Wait() (which can cause a deadlock in contexts with a synchronization context, like older ASP.NET or WPF apps). Understanding these pitfalls up front avoids some of the most common async-related bugs.
Delegates
A delegate is a type-safe reference to a method - essentially a variable that can hold a method and be invoked like one. Delegates enable passing behavior around as data, forming the foundation for events, callbacks, and LINQ. C# provides built-in generic delegate types, Func<> and Action<>, that cover the vast majority of use cases without needing to declare a custom delegate type.
Events
An event is a special kind of delegate field that provides a publish-subscribe pattern: the declaring class can raise (invoke) the event, but external code can only subscribe (+=) or unsubscribe (-=) - it cannot invoke the event directly or overwrite existing subscribers. This makes events the standard, safe way to notify other parts of a program that something has happened, like a button being clicked or a value changing.
Extension Methods
Extension methods let you add new methods to an existing type - including types you don't own, like built-in .NET types or third-party classes - without modifying its source code or creating a subclass. They're defined as static methods in a static class, with the first parameter prefixed with this to indicate which type they extend. LINQ's Where(), Select(), and friends are themselves implemented as extension methods on IEnumerable<T>.
Nullable Reference Types & Null-Coalescing
Since C# 8, nullable reference types let the compiler track and warn about potential null reference issues at compile time, even for reference types like string and custom classes (which were always implicitly nullable before). A type like string means 'never null' under this feature, while string? explicitly allows null. The null-coalescing operator (??) and null-conditional operator (?.) provide concise syntax for safely working with potentially-null values.
Pattern Matching
Pattern matching, expanded significantly since C# 7, lets you test a value against a shape or condition using is, switch expressions, and more, often extracting matched data in the same step. It covers type patterns (checking and casting in one step), property patterns (matching on an object's properties), and relational patterns (matching numeric ranges), making conditional logic more expressive and less error-prone than manual casting.
Tuples & Deconstruction
C# tuples let you group multiple values together without defining a dedicated class or struct, ideal for lightweight, temporary groupings like returning multiple values from a method. Modern C# (7+) supports named tuple elements for readability, and deconstruction syntax lets you unpack a tuple (or any type that supports it) into separate variables in one statement.
C# using Declarations
A using declaration disposes an IDisposable resource automatically at the end of the enclosing scope. It is a concise alternative to a nested using statement.
System.Text.Json Serialization
JsonSerializer converts .NET values to and from JSON. Typed deserialization provides structure but application-specific validation remains the caller’s responsibility. Use a .NET 8+ console project; replace Program.cs with this C# example.
Regex Validation with Timeouts
Regex matches and extracts structured text. A timeout bounds matching time for patterns that may backtrack; handle timeout failures separately from a normal nonmatch. Use a .NET 8+ console project; replace Program.cs with this C# example.
StringBuilder Text Accumulation
StringBuilder accumulates mutable text efficiently across a loop. Convert the finished buffer to a string when passing it to code that expects immutable text. Use a .NET 8+ console project; replace Program.cs with this C# example.
DateTimeOffset and UTC
DateTimeOffset represents a date/time and UTC offset, identifying an instant. It does not store a region’s future daylight-saving rules. Use a .NET 8+ console project; replace Program.cs with this C# example.
TimeSpan Components and Totals
TimeSpan represents an elapsed time interval. Component properties such as Minutes differ from total properties such as TotalMinutes. Use a .NET 8+ console project; replace Program.cs with this C# example.
Guid Parsing and Formatting
Guid stores a 128-bit identifier. TryParse handles malformed user input without using exceptions for an expected validation outcome. Use a .NET 8+ console project; replace Program.cs with this C# example.
Decimal Midpoint Rounding
Math.Round accepts a rounding policy. Decimal literals use the m suffix and represent common decimal fractions without binary floating-point approximation. Use a .NET 8+ console project; replace Program.cs with this C# example.
Checked Integer Overflow
checked makes overflowing integral arithmetic throw OverflowException. Its effect applies to operations textually inside the checked context, not automatically to code called from it. Use a .NET 8+ console project; replace Program.cs with this C# example.
Combining Flags Enums
A Flags enum represents a set of independent options using nonoverlapping bits. Bitwise operators combine, test and clear those options. Use a .NET 8+ console project; replace Program.cs with this C# example.
ArrayPool Buffer Ownership
ArrayPool<T> lends reusable arrays to reduce repeated allocations. Rent returns at least the requested length, possibly with old contents; the caller must initialize the portion it reads and return the array to the same pool exactly once. Use a .NET 8+ console project; replace Program.cs with this C# example.
Span Views over Arrays
Span<T> is a stack-only view of contiguous memory. Slicing a span produces another view into the same data rather than copying elements. Use a .NET 8+ console project; replace Program.cs with this C# example.
Lazy Initialization
Lazy<T> postpones construction until Value is first accessed and then reuses the result. Its default mode synchronizes initialization across threads. Use a .NET 8+ console project; replace Program.cs with this C# example.
ConcurrentDictionary Updates
ConcurrentDictionary supports concurrent access and atomic key updates. AddOrUpdate replaces unsafe separate read/write operations, but its delegates may be invoked more than once. Use a .NET 8+ console project; replace Program.cs with this C# example.
PriorityQueue Scheduling
PriorityQueue<TElement,TPriority> retrieves the element with the lowest priority value. It is available in .NET 6+ and does not guarantee FIFO order for ties. Use a .NET 8+ console project; replace Program.cs with this C# example.
Read-Only Collection Views
ReadOnlyCollection<T> prevents modification through its interface but can still reflect changes to the underlying collection. A read-only view is not an immutable snapshot. Use a .NET 8+ console project; replace Program.cs with this C# example.
Indices and Ranges
The ^ operator indexes from the end and .. describes a half-open range. Array slicing with a range creates a new array; span slicing creates a view. Use a .NET 8+ console project; replace Program.cs with this C# example.
Static Local Functions
Local functions hide helper logic inside the containing member. Marking one static prevents accidental capture of surrounding variables. Use a .NET 8+ console project; replace Program.cs with this C# example.
ref and out Parameters
ref passes an initialized variable by reference, while out lets a method assign a result without requiring prior initialization. Both modifiers are visible at the call site. Use a .NET 8+ console project; replace Program.cs with this C# example.
Custom Attributes and Reflection
Attributes attach metadata to program elements. Reflection can read that metadata at runtime; an attribute alone does not execute application behavior. Use a .NET 8+ console project; replace Program.cs with this C# example.
Text Files and Cleanup
File provides convenience methods for small text files. Specify encoding explicitly and clean up temporary files even when an operation throws. Use a .NET 8+ console project; replace Program.cs with this C# example.
Ruby documentation
Introduction to Ruby
Start here to understand Ruby, where it came from, what people build with it, and how a short Ruby program works. No previous programming experience is needed.
How Ruby Works
Follow a Ruby source file from the terminal to its output, and understand the runtime, objects, errors, dynamic typing and garbage collection.
Ruby vs Ruby on Rails
Ruby is the programming language; Rails is one web framework built with it. Learn what each provides and why you can learn Ruby without Rails.
Install Ruby on Windows
Choose a maintained Ruby release, install RubyInstaller with Devkit, verify Ruby in PowerShell and run your first script.
Install Ruby on macOS
Check the macOS Ruby, install an independently managed version with rbenv and run a Ruby program without changing system files.
Install Ruby on Linux
Choose a Linux distribution package or a user-managed Ruby, verify it, and diagnose PATH, permissions and compiler problems.
Your First Ruby Program
Create a project folder and Ruby file, run it in a terminal, understand its output, then change it safely.
Interactive Ruby (IRB)
Start IRB, evaluate expressions, try variables and methods, and distinguish returned values from printed output.
Ruby in Visual Studio Code
Open a Ruby folder in VS Code, use the maintained Ruby LSP extension, run scripts and start debugging.
Ruby in RubyMine
Install RubyMine, select a Ruby interpreter, create and run a script, and understand its debugger and licence choices.
RubyGems and Bundler
Understand gems, RubyGems, Gemfile, Gemfile.lock, bundle install and bundle exec through a small terminal project.
Ruby Project Structure
Learn how a small ordinary Ruby project can organise scripts, reusable code, tests and optional dependencies without assuming Rails.
Ruby in Codectionary’s Playground
Find out what Ruby editing supports in the Playground, why Run does not execute Ruby, and where to run a Ruby example instead.
Ruby Variables & Strings
Ruby uses local variables without a declaration keyword. Strings can be enclosed in single or double quotes; double-quoted strings support interpolation with #{...}.
Ruby Arrays & Hashes
An Array holds values at numbered positions starting at zero. A Hash associates keys with values, so a profile can be read by field name instead of remembering a position. Choose the structure by how you will look up the data. Run these examples as Ruby scripts.
Ruby Methods, Blocks & Enumerable
Methods are declared with def and return their final expression unless return is used explicitly. Many collection methods accept blocks, which makes transformations and filtering concise.
Ruby Classes & Modules
Classes define objects and their behaviour. initialize is the conventional constructor method. Modules can group methods and constants, and can be mixed into classes with include.
Ruby Exceptions
Ruby signals exceptional failures by raising exceptions. rescue handles a matching exception, while ensure runs whether the operation succeeded or failed.
Ruby comments
Ruby reference for ruby comments.
Ruby local variables
Ruby reference for ruby local variables.
Ruby numbers
Ruby reference for ruby numbers.
Ruby symbols
Ruby reference for ruby symbols.
Ruby string quotes
Ruby reference for ruby string quotes.
Ruby string interpolation
Ruby reference for ruby string interpolation.
Ruby string methods
Ruby reference for ruby string methods.
Ruby array indexing
Ruby reference for ruby array indexing.
Ruby array mutation
Ruby reference for ruby array mutation.
Ruby hash literals
Ruby reference for ruby hash literals.
Ruby Hash#fetch
Ruby reference for ruby hash#fetch.
Ruby ranges
Ruby reference for ruby ranges.
Ruby booleans and nil
Ruby reference for ruby booleans and nil.
Ruby comparisons
Ruby reference for ruby comparisons.
Ruby logical operators
Ruby reference for ruby logical operators.
Ruby if and elsif
Ruby reference for ruby if and elsif.
Ruby unless
Ruby reference for ruby unless.
Ruby case and when
Ruby reference for ruby case and when.
Ruby ternary expressions
Ruby reference for ruby ternary expressions.
Ruby while loops
Ruby reference for ruby while loops.
Ruby until loops
Ruby reference for ruby until loops.
Ruby for loops
Ruby reference for ruby for loops.
Ruby each
Ruby reference for ruby each.
Ruby times
Ruby reference for ruby times.
Ruby map
Ruby reference for ruby map.
Ruby select
Ruby reference for ruby select.
Ruby reduce
Ruby reference for ruby reduce.
Ruby method definitions
Ruby reference for ruby method definitions.
Ruby default arguments
Ruby reference for ruby default arguments.
Ruby splat arguments
Ruby reference for ruby splat arguments.
Ruby keyword arguments
Ruby reference for ruby keyword arguments.
Ruby blocks and yield
Ruby reference for ruby blocks and yield.
Ruby Proc objects
Ruby reference for ruby proc objects.
Ruby lambdas
Ruby reference for ruby lambdas.
Ruby instance variables
Ruby reference for ruby instance variables.
Ruby attr_accessor
Ruby reference for ruby attr_accessor.
Ruby class inheritance
Ruby reference for ruby class inheritance.
Ruby super
Ruby reference for ruby super.
Ruby modules
Ruby reference for ruby modules.
Ruby include
Ruby reference for ruby include.
Ruby constants
Ruby reference for ruby constants.
Ruby method visibility
Ruby reference for ruby method visibility.
Ruby singleton methods
Ruby reference for ruby singleton methods.
Ruby require
Ruby reference for ruby require.
Ruby begin and rescue
Ruby reference for ruby begin and rescue.
Ruby ensure
Ruby reference for ruby ensure.
Ruby File.read
Ruby reference for ruby file.read.
Ruby File.write
Ruby reference for ruby file.write.
Ruby regular expressions
Ruby reference for ruby regular expressions.
Ruby safe navigation
Ruby reference for ruby safe navigation.
Ruby Hash#dig
Ruby reference for ruby hash#dig.
Ruby freeze
Ruby reference for ruby freeze.
Ruby Struct
Ruby reference for ruby struct.
Ruby enumerable predicates
Ruby reference for ruby enumerable predicates.
Ruby pattern matching
Ruby reference for ruby pattern matching.
JSON Parsing and Generation
JSON converts portable data between text and Ruby hashes, arrays and scalar values. Parsed object keys are strings by default. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.
CSV with Named Columns
CSV handles quoted fields and row boundaries correctly. With headers enabled, each row supports lookup by column name. Require the csv gem; availability as a bundled gem varies by Ruby distribution. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.
Date Arithmetic
Date represents immutable calendar dates. Adding an integer advances by days and subtracting two dates produces an exact rational day difference. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.
BigDecimal Arithmetic
BigDecimal calculates with decimal values rather than binary Float approximations. Require bigdecimal and create values from strings when preserving decimal input matters. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.
Rational Arithmetic
Rational stores exact fractions in reduced form. Integer numerator/denominator construction avoids the approximation introduced by floating-point division. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.
Sets and Set Operations
Set stores unique elements and supports union, intersection and difference. On Ruby 3.x, require set before use. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.
Lazy Enumerator Pipelines
Enumerator::Lazy delays transformations until values are requested. A finite take can safely bound an otherwise unbounded sequence. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.
Sliding Windows with each_cons
each_cons yields overlapping windows of a fixed size, useful for adjacent differences and rolling calculations. A sequence shorter than the window produces no complete windows. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.
Grouping Records with group_by
group_by partitions all elements into a hash of arrays keyed by a block result. It preserves the original elements in each group. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.
Counting Values with tally
tally counts equal values and returns a frequency hash. It is available from Ruby 2.7 and avoids manually maintaining a counter for each key. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.
Splitting with partition
partition traverses a collection and returns two arrays: items for which the block is truthy, followed by the remaining items. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.
Sorting by Derived Keys
sort_by computes a sorting key for each item and returns a new sorted array. Array keys express multiple ordered criteria. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.
Pairing Sequences with zip
zip combines corresponding positions from arrays. The receiver determines result length; missing positions in shorter arguments become nil. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.
Hash Default Blocks
A Hash default block creates a value on demand for an absent key. Assigning inside the block stores that new value independently for each key. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.
Transforming Hash Values
transform_values produces a hash with the same keys and new values from a block. It is useful for normalizing all fields with a shared conversion. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.
Bound Method Objects
A Method object pairs an existing method implementation with its receiver. It can be called directly or converted into a block for iteration. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.
Method Wrapping with prepend
prepend inserts a module before a class in method lookup. A wrapper in the module can call super to reach the class implementation. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.
Lexically Scoped Refinements
Refinements extend methods within the lexical scope where using activates them. They provide an alternative to globally changing a core class. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.
Comparable Domain Objects
Comparable derives comparison operators from a class’s <=> method. Return nil for objects that cannot be compared meaningfully. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.
Binary Packing and Byte Order
Array#pack encodes values into a binary string and String#unpack reverses the process. Directives define field width, signedness and byte order. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.
C++ documentation
Introduction to C++
Start here to understand what C++ is, why it was created, how a program becomes an executable, and where its control over resources is useful.
Your First C++ Program
Write a complete Hello World program, understand every important part, compile it with C++17 and correct a first compiler error.
How C++ Programs Are Built and Run
Follow a small C++ program from source files through preprocessing, object files and linking to an executable, and learn where build errors occur.
C versus C++
Compare C and C++ through the same small program, learn where their rules differ, and see when each language fits a project.
C++ Compilers: GCC, Clang and MSVC
Learn what the major C++ toolchains do, how to build a first program with each one, and how to check versions and language-standard support.
Install C++ on Windows
Install the Visual Studio C++ workload, verify MSVC, create a console project and run a first program. Learn when MSYS2 is an alternative.
Install C++ on macOS
Install Apple Command Line Tools, check clang++, compile a first C++ file and resolve common macOS developer-tool issues.
Install C++ on Linux
Install G++ with the right distribution package manager, compile a first program, and understand Clang and common missing-header errors.
C++ in JetBrains CLion
Install CLion, select a C++ toolchain, create a CMake project and use its run, debugger and code-completion tools.
C++ Project Structure
Learn how .cpp files, headers, declarations, object files, libraries, executables and build directories fit together in a small C++ project.
Introduction to CMake
Learn what CMakeLists.txt describes, configure a C++17 project, build it with a selected generator and locate its executable.
Modern C++ Fundamentals
Learn a practical C++17 baseline: strings, vectors, range-based loops, references, type inference and safer resource ownership.
C++ in the Codectionary Playground
Learn what the C++ editor and optional remote runner actually do, what they cannot promise, and when to use a local compiler.
C++ Variables, Types & References
C++ is statically typed: a variable has a type such as int, double, bool, or std::string. A reference declared with & is an alias for an existing object.
C++ Conditions & Loops
C++ uses if, else if, and else for decisions. Range-based for loops iterate directly over the elements of a container.
C++ Functions & Lambdas
Functions declare a return type, name, and parameters. Lambdas are anonymous callable objects and can capture surrounding values explicitly.
C++ Classes & RAII
Classes group data and functions. Constructors establish valid state. C++ uses RAII: an object owns a resource for its lifetime and releases it in its destructor.
C++ Vector & Map
std::vector is a resizable sequence container. std::map stores key-value pairs ordered by key. Both are available through standard-library headers.
C++ comments
C++ reference for c++ comments.
C++ include directives
C++ reference for c++ include directives.
C++ auto type deduction
C++ reference for c++ auto type deduction.
C++ const values
C++ reference for c++ const values.
C++ enum class
C++ reference for c++ enum class.
C++ built-in arrays
C++ reference for c++ built-in arrays.
C++ std::array
C++ reference for c++ std::array.
C++ std::string
C++ reference for c++ std::string.
C++ references
C++ reference for c++ references.
C++ pointers
C++ reference for c++ pointers.
C++ nullptr
C++ reference for c++ nullptr.
C++ arithmetic operators
Arithmetic operators calculate new values from numbers. The operand types matter: dividing two integers produces an integer, even if you store the answer in a double. Use / for a quotient and % for an integer remainder. Each example below is a complete C++ program.
C++ comparison operators
C++ reference for c++ comparison operators.
C++ logical operators
C++ reference for c++ logical operators.
C++ if initializers
C++ reference for c++ if initializers.
C++ switch statements
C++ reference for c++ switch statements.
C++ for loops
C++ reference for c++ for loops.
C++ range-based for loops
C++ reference for c++ range-based for loops.
C++ while loops
C++ reference for c++ while loops.
C++ do-while loops
C++ reference for c++ do-while loops.
C++ function definitions
C++ reference for c++ function definitions.
C++ pass by value
C++ reference for c++ pass by value.
C++ const reference parameters
C++ reference for c++ const reference parameters.
C++ function overloading
C++ reference for c++ function overloading.
C++ default arguments
C++ reference for c++ default arguments.
C++ lambdas
C++ reference for c++ lambdas.
C++ structs
C++ reference for c++ structs.
C++ class access control
C++ reference for c++ class access control.
C++ constructor initializer lists
C++ reference for c++ constructor initializer lists.
C++ destructors
C++ reference for c++ destructors.
C++ inheritance
C++ reference for c++ inheritance.
C++ virtual and override
C++ reference for c++ virtual and override.
C++ pure virtual functions
C++ reference for c++ pure virtual functions.
C++ function templates
C++ reference for c++ function templates.
C++ class templates
C++ reference for c++ class templates.
C++ namespaces
C++ reference for c++ namespaces.
C++ using declarations
C++ reference for c++ using declarations.
C++ exceptions
C++ reference for c++ exceptions.
C++ std::unique_ptr
C++ reference for c++ std::unique_ptr.
C++ std::shared_ptr
C++ reference for c++ std::shared_ptr.
C++ RAII
C++ reference for c++ raii.
C++ std::vector
C++ reference for c++ std::vector.
C++ std::map
C++ reference for c++ std::map.
C++ std::unordered_map
C++ reference for c++ std::unordered_map.
C++ std::set
C++ reference for c++ std::set.
C++ std::sort
C++ reference for c++ std::sort.
C++ std::find_if
C++ reference for c++ std::find_if.
C++ std::transform
C++ reference for c++ std::transform.
C++ iterators
C++ reference for c++ iterators.
C++ file streams
C++ reference for c++ file streams.
C++ std::optional
C++ reference for c++ std::optional.
C++ std::variant
C++ reference for c++ std::variant.
C++ std::tuple
C++ reference for c++ std::tuple.
C++ chrono durations
C++ reference for c++ chrono durations.
C++ scoped enum values
C++ reference for c++ scoped enum values.
C++ move semantics
C++ reference for c++ move semantics.
C++ std::span views
C++20 std::span passes a contiguous sequence with its length without copying or owning the elements. A span can refer to an array or vector; changing elements through a mutable span changes the original storage.
C++ std::string_view lifetimes
C++17 string_view represents a read-only slice of existing character storage. substr creates another view without allocating a string, making it useful for parsing data whose owner remains alive.
C++ std::from_chars parsing
C++17 from_chars parses numbers without throwing or using the locale. The returned pointer identifies the first unconsumed character, so success and full-input consumption are separate checks.
C++ std::to_chars formatting
C++17 to_chars writes a number into a caller-owned character buffer. It avoids locale-dependent formatting and reports insufficient capacity through an error code.
C++ erase–remove filtering
The erase–remove idiom filters a vector in two stages: remove_if moves retained elements to the front, and erase shrinks the container. This example works in C++11 and later.
C++ std::lower_bound searches
lower_bound locates the first element not less than a target in a range partitioned for the same ordering. A sorted vector is a common input. This example requires C++11 or later.
C++ std::accumulate totals
accumulate folds a range from left to right into an initial value. The initial value determines the accumulator type, which matters for floating-point totals and integer overflow. This example requires C++11 or later.
C++ std::iota sequences
C++11 iota assigns increasing values into an existing writable range. It is convenient for index lists and consecutive identifiers without a handwritten counter loop.
C++ prefix totals with partial_sum
partial_sum computes a running total for every input position. Prefix totals support cumulative reports and fast sums over sections of a sequence. This example uses C++11 or later.
C++ std::deque at both ends
deque is a sequence container with efficient insertion and removal at both ends and indexed access. Its storage is not required to be contiguous like vector storage. This example uses C++11 or later.
C++ std::queue FIFO jobs
queue restricts a sequence to first-in, first-out operations, making the intended processing order explicit. front reads the next value and pop removes it without returning it. This example uses C++11 or later.
C++ std::priority_queue ordering
priority_queue exposes the highest-priority element. By default this is the largest value; std::greater produces a min-heap suitable for earliest-deadline processing. This example uses C++11 or later.
C++ std::unordered_set membership
C++11 unordered_set stores unique keys with average constant-time lookup. It is useful when membership matters more than sorted traversal.
C++ std::bitset flags
bitset holds a fixed number of bits and supports named operations such as set, reset, test and count. It is useful for compact fixed-size feature or availability masks. This example uses C++11 or later.
C++ filesystem path composition
C++17 filesystem::path separates path manipulation from filesystem access. Joining components and inspecting extensions does not require the file to exist.
C++ std::weak_ptr observers
C++11 weak_ptr observes shared ownership without extending the object lifetime. lock attempts to acquire a shared_ptr, returning an empty pointer when the object has already been destroyed.
C++ std::exchange state transitions
C++14 exchange replaces a value and returns its previous value. It expresses consume-and-reset operations and is often useful in move constructors or one-shot state handling.
C++ std::clamp bounds
C++17 clamp returns a value bounded by a lower and upper limit. It is useful for UI ranges and numeric controls when the bounds are ordered.
C++20 constrained templates
C++20 concepts state requirements on template arguments. A constrained function can reject unsupported types during overload resolution and communicate its intended input domain.
C++ structured bindings
C++17 structured bindings give names to components of tuples, pairs, arrays and suitable objects. Adding a reference lets bindings modify the original object instead of a copy.
PHP documentation
Introduction to PHP
Start here to learn what PHP is, how it powers websites, where it runs, what developers build with it, and how to run a first program.
How PHP Works
Follow a PHP web request from the browser through a web server and PHP runtime to the response, with clear explanations of PHP-FPM, sessions and output formats.
PHP vs JavaScript
Compare PHP with browser JavaScript and Node.js, then build a tiny page where PHP serves data and JavaScript updates the interface.
PHP Versions and Supported Releases
Learn how PHP release support works, choose a maintained version, check your installed PHP and extensions, and recognise version-specific features.
Install PHP on Windows
Install a supported PHP command-line release from the official Windows binaries, set PATH, check php.ini and run a first script in PowerShell.
Install PHP on macOS
Check for PHP, install a maintained Homebrew package when suitable, resolve PATH issues and run a first PHP script on macOS.
Install PHP on Linux
Install PHP CLI using Ubuntu/Debian or Fedora package managers, inspect versions and extensions, and understand when PHP-FPM is needed.
Your First PHP Program
Create an index.php file, run it on a local PHP development server, understand each line, and turn the output into an HTML page.
PHP’s Built-in Development Server
Learn how php -S serves a local project, what localhost and ports mean, how to read errors, and why this server is not for production.
PHP Variables & Strings
PHP variables start with $. Double-quoted strings interpolate variables, while single-quoted strings generally treat their contents literally.
PHP Arrays
A PHP array is an ordered map: every value has an integer or string key. A list literal starts with keys 0, 1, 2; named keys can describe a record. Removing an item does not automatically renumber the remaining keys. Run these examples with PHP CLI; their output is plain text.
PHP Functions & Type Declarations
PHP functions use the function keyword. Parameter and return type declarations can document and enforce the values a function accepts and returns.
PHP Request Data
PHP exposes HTTP request data through superglobal arrays such as $_GET and $_POST. Data from a request is untrusted and should be validated before use.
PHP Classes & Interfaces
Classes define objects, while interfaces define methods an implementing class must provide. Visibility controls whether members are public, protected, or private.
PHP opening tags
PHP reference for php opening tags.
PHP comments
PHP reference for php comments.
PHP variables
PHP reference for php variables.
PHP constants
PHP reference for php constants.
PHP string quotes
PHP reference for php string quotes.
PHP heredoc strings
PHP reference for php heredoc strings.
PHP strict types
PHP reference for php strict types.
PHP indexed arrays
PHP reference for php indexed arrays.
PHP associative arrays
PHP reference for php associative arrays.
PHP array destructuring
PHP reference for php array destructuring.
PHP arithmetic operators
PHP reference for php arithmetic operators.
PHP comparison operators
PHP reference for php comparison operators.
PHP logical operators
PHP reference for php logical operators.
PHP null coalescing
PHP reference for php null coalescing.
PHP nullsafe operator
PHP reference for php nullsafe operator.
PHP if and else
PHP reference for php if and else.
PHP switch statements
PHP reference for php switch statements.
PHP match expressions
PHP reference for php match expressions.
PHP ternary expressions
PHP reference for php ternary expressions.
PHP while loops
PHP reference for php while loops.
PHP for loops
PHP reference for php for loops.
PHP foreach loops
PHP reference for php foreach loops.
PHP function definitions
PHP reference for php function definitions.
PHP union types
PHP reference for php union types.
PHP default parameters
PHP reference for php default parameters.
PHP named arguments
PHP reference for php named arguments.
PHP variadic functions
PHP reference for php variadic functions.
PHP closures
PHP reference for php closures.
PHP arrow functions
PHP reference for php arrow functions.
PHP exceptions
PHP reference for php exceptions.
PHP include and require
PHP reference for php include and require.
PHP namespaces
PHP reference for php namespaces.
PHP use imports
PHP reference for php use imports.
PHP member visibility
PHP reference for php member visibility.
PHP constructor promotion
PHP reference for php constructor promotion.
PHP readonly properties
PHP reference for php readonly properties.
PHP interfaces
PHP reference for php interfaces.
PHP traits
PHP reference for php traits.
PHP static members
PHP reference for php static members.
PHP enums
PHP reference for php enums.
PHP __construct
PHP reference for php __construct.
PHP superglobals
PHP reference for php superglobals.
PHP filter_input
PHP reference for php filter_input.
PHP sessions
PHP reference for php sessions.
PHP cookies
PHP reference for php cookies.
PHP JSON encode and decode
PHP reference for php json encode and decode.
PHP password hashing
PHP reference for php password hashing.
PHP PDO connections
PHP reference for php pdo connections.
PHP PDO prepared statements
PHP reference for php pdo prepared statements.
PHP DateTimeImmutable
PHP reference for php datetimeimmutable.
PHP file_get_contents
PHP reference for php file_get_contents.
PHP file_put_contents
PHP reference for php file_put_contents.
PHP generators
PHP reference for php generators.
PHP array_map
PHP reference for php array_map.
PHP array_filter
PHP reference for php array_filter.
PHP throw expressions
PHP reference for php throw expressions.
PHP array_reduce accumulators
array_reduce combines array values into a single result by passing an accumulator and the next element to a callback. An explicit initial value makes empty input predictable.
PHP array_column projections
array_column extracts a field from a collection of records and can index the result by another field. It is useful for building lookup maps from query results.
PHP array_chunk batches
array_chunk divides an array into smaller arrays. The final batch can be shorter than the requested length; the optional preserve_keys argument controls whether original keys survive.
PHP usort record ordering
usort sorts an array in place with a comparator and replaces keys with sequential numeric keys. PHP 8 preserves original order for entries that compare equal.
PHP absent keys versus null
array_key_exists tests whether a key is present even when its value is null. isset answers a different question: it returns false for missing keys and keys containing null.
PHP strict array membership
in_array searches values rather than keys. Its strict argument requires both type and value to match, avoiding implicit conversions in identifiers and allowlists.
PHP regular-expression captures
preg_match finds one regular-expression match and fills a captures array. Its result distinguishes a match (1), no match (0), and a regex error (false).
PHP pattern-based replacements
preg_replace replaces matches throughout a string and can report how many replacements occurred. It returns null when the regular expression fails.
PHP substring predicates
PHP 8 str_contains returns a boolean for a case-sensitive substring search. It avoids confusing a match at position zero with failure.
PHP multibyte text lengths
With the mbstring extension enabled, mb_strlen counts characters in a specified encoding. strlen counts bytes. Neither is a universal count of visible grapheme clusters.
PHP HTML output escaping
htmlspecialchars converts HTML-significant characters when inserting text into HTML. Escaping belongs at the output boundary and must match the output context.
PHP encoded query strings
http_build_query serializes structured parameters into a URL-encoded query string. Explicit RFC3986 encoding uses percent-encoded spaces, avoiding manual concatenation mistakes.
PHP URL components
parse_url breaks a URL into components such as scheme, host, path and query. Parsing is not validation: even some partial or invalid URL strings can produce components.
PHP secure random tokens
random_bytes obtains cryptographically secure random bytes. Encoding with bin2hex makes those bytes printable for tokens without pretending random output has a fixed value.
PHP timing-safe token comparison
hash_equals compares two strings while avoiding content-dependent timing for equal-length inputs. It is suited to comparing a known token or digest with a supplied value.
PHP CSV stream parsing
fgetcsv understands quoted delimiters and CSV records that a plain comma split cannot parse. An empty escape argument disables PHP-specific backslash escaping and is explicitly supplied here.
PHP advisory file locks
flock coordinates access to a file among cooperating processes. Hold an exclusive lock across the entire read-modify-write sequence, not just the write call.
PHP SplQueue worklists
SplQueue provides enqueue and dequeue operations with first-in, first-out behavior. It expresses a worklist without repeatedly shifting large arrays.
PHP attributes as metadata
PHP 8 attributes attach structured metadata to declarations. The metadata has no automatic behavior; reflection or a framework must read it and decide what to do.
PHP reflection for class inspection
ReflectionClass inspects declared classes at runtime. It can examine interfaces, methods and constructor parameters when building tools or diagnosing a plugin contract.
Lua documentation
Introduction to Lua
Meet Lua, the small embeddable language created at PUC-Rio, and choose a clear path from a first script to modules and application scripting.
Install Lua and Choose Your Tools
Choose a verified Lua installer for your operating system, try the interactive interpreter, configure VS Code, and understand LuaRocks packages.
Your First Lua Program
Create a .lua file, run it with a local interpreter, understand variables, concatenation and functions, and fix common first-run errors.
Lua Variables & Values
Lua uses local for scoped variables. Its basic value types include nil, boolean, number, string, function, table, thread, and userdata.
Lua Tables
A Lua table maps keys to values. A sequence uses consecutive integer keys starting at 1; a record uses named fields. Both are tables, but sequence length and iteration rules are not dictionary-counting rules. Assigning a table to another variable shares the table rather than copying it.
Lua Conditions & Loops
Lua uses then/end for conditionals and do/end for loops. In Lua, only false and nil are falsey; zero and empty strings are truthy.
Lua Functions & Closures
Functions are first-class values in Lua: they can be stored, passed, and returned. A nested function can close over a local variable from its surrounding scope.
Lua Modules
Lua modules typically return a table of public functions and values. require loads a module and returns the value it exported, caching it for later requests.
Lua comments
Lua reference for lua comments.
Lua local variables
Lua reference for lua local variables.
Lua global variables
Lua reference for lua global variables.
Lua nil
Lua reference for lua nil.
Lua booleans
Lua reference for lua booleans.
Lua numbers
Lua reference for lua numbers.
Lua strings
Lua reference for lua strings.
Lua string concatenation
Lua reference for lua string concatenation.
Lua multiline strings
Lua reference for lua multiline strings.
Lua array-style tables
Lua reference for lua array-style tables.
Lua keyed tables
Lua reference for lua keyed tables.
Lua table.insert and remove
Lua reference for lua table.insert and remove.
Lua length operator
Lua reference for lua length operator.
Lua pairs
Lua reference for lua pairs.
Lua ipairs
ipairs walks consecutive integer keys starting at 1, returning the index and value on each iteration. It stops at the first missing value (nil). Use it for a sequence such as a list of tags, rather than for a table with named keys.
Lua arithmetic operators
Lua reference for lua arithmetic operators.
Lua comparison operators
Lua reference for lua comparison operators.
Lua logical operators
Lua reference for lua logical operators.
Lua if then end
Lua reference for lua if then end.
Lua elseif
Lua reference for lua elseif.
Lua while loops
Lua reference for lua while loops.
Lua repeat until loops
Lua reference for lua repeat until loops.
Lua numeric for loops
Lua reference for lua numeric for loops.
Lua generic for loops
Lua reference for lua generic for loops.
Lua break
Lua reference for lua break.
Lua goto and labels
Lua reference for lua goto and labels.
Lua multiple return values
Lua reference for lua multiple return values.
Lua closures
A Lua closure is a function that keeps access to local variables from its enclosing scope. These captured variables are called upvalues. They remain available after the outer function returns, so a callback can remember a counter or a configuration value between calls.
Lua varargs
Lua reference for lua varargs.
Lua colon methods
Lua reference for lua colon methods.
Lua pcall
pcall calls a function in protected mode. On success it returns true followed by the function’s return values. On failure it returns false and the error object, allowing the caller to decide what to do next. It does not undo changes made before the error.
Lua xpcall
Lua reference for lua xpcall.
Lua error and assert
Lua reference for lua error and assert.
Lua require
Lua reference for lua require.
Lua dofile and loadfile
Lua reference for lua dofile and loadfile.
Lua coroutine.create
Lua reference for lua coroutine.create.
Lua coroutine.resume
Lua reference for lua coroutine.resume.
Lua coroutine.yield
Lua reference for lua coroutine.yield.
Lua metatables
Lua reference for lua metatables.
Lua setmetatable
Lua reference for lua setmetatable.
Lua __index metamethod
Lua reference for lua __index metamethod.
Lua __newindex metamethod
Lua reference for lua __newindex metamethod.
Lua operator metamethods
Lua reference for lua operator metamethods.
Lua string library
Lua reference for lua string library.
Lua table library
Lua reference for lua table library.
Lua math library
Lua reference for lua math library.
Lua io library
Lua reference for lua io library.
Lua os library
Lua reference for lua os library.
Lua package paths
Lua reference for lua package paths.
Lua collectgarbage
Lua reference for lua collectgarbage.
Lua weak tables
Lua reference for lua weak tables.
Lua rawget and rawset
Lua reference for lua rawget and rawset.
Lua bitwise operators
Lua reference for lua bitwise operators.
Lua table.concat
Lua reference for lua table.concat.
Lua module tables
Lua reference for lua module tables.
Lua pattern captures
string.match extracts the first match of a Lua pattern. Parentheses capture portions, while anchors require a complete match. Lua patterns do not provide regular-expression alternation.
Lua string.gmatch token iteration
string.gmatch creates an iterator over successive pattern matches, extracting tokens without first allocating a complete token array.
Lua string.gsub replacements
string.gsub replaces pattern matches and returns the new string plus the replacement count. A replacement function receives captures and computes replacement text.
Lua literal substring searches
string.find normally treats its needle as a pattern. Its fourth argument selects literal searching, useful for punctuation or user-supplied search text.
Lua formatted text
string.format creates display text with conversion specifiers and widths. Formatting a number for display does not change its stored value.
Lua binary packing
Lua 5.3+ string.pack and string.unpack encode binary layouts with explicit endianness and widths. Use Luau buffers when targeting Luau rather than assuming these Lua APIs exist.
Lua UTF-8 code-point iteration
Lua 5.3+ utf8.codes produces Unicode code points with their starting byte positions. Ordinary string lengths and offsets still count bytes.
Lua nil-preserving argument lists
Lua 5.2+ table.pack stores an explicit argument count in n. Passing that bound to table.unpack preserves holes and trailing nil arguments.
Lua table.move ranges
Lua 5.3+ table.move copies an integer-keyed range and safely handles overlap. The destination can be a separate table or the source itself.
Lua custom record sorting
table.sort reorders a sequence in place with an optional comparator. A tie-breaker makes record order predictable without assuming a stable sort.
Lua numeric base conversion
tonumber accepts a base from 2 through 36 for integer text. Invalid text returns nil, which must be distinguished from a valid zero.
Lua integer subtypes and conversion
Lua 5.3+ distinguishes integer and floating-point numeric subtypes. math.tointeger converts only exactly representable integer values. Luau instead uses one double-precision number type.
Lua integral and fractional parts
math.modf splits a number into integral and fractional parts with the original sign. Its integral part truncates toward zero, unlike floor for negative inputs.
Lua 5.4 const locals
Lua 5.4 <const> prevents reassignment of a local binding. It does not freeze a referenced table. This attribute syntax is not Luau syntax.
Lua 5.4 deterministic cleanup
Lua 5.4 <close> locals call a value's __close metamethod at scope exit, including error unwinding. This supports deterministic cleanup; the syntax is not supported in Luau.
Lua lexical _ENV scopes
In Lua 5.2+, free names resolve through the lexically visible _ENV table. A local environment supplies deliberate globals for one scope. This differs from Luau's Lua 5.1-derived environment model.
Lua text chunks with load
Lua 5.2+ load compiles text with an optional environment. Compilation failure returns nil and an error; running the resulting function is a separate operation.
Lua coroutine iterators with wrap
coroutine.wrap returns a function that resumes a coroutine and yields values directly. It propagates errors instead of returning the success flag supplied by coroutine.resume.
Lua select and argument counts
select counts varargs including nil or returns a suffix starting at a requested position. It operates on argument lists rather than table lengths.
Lua diagnostic stack traces
debug.traceback builds a stack description. Used as an xpcall handler, it captures frames before error unwinding removes useful context.
Luau documentation
Luau and Roblox scripting
Start with Luau values and functions, then use Roblox Studio to connect that code to players, Instances and events. Luau is the language; Roblox supplies the game engine APIs. Codectionary supports editing and highlighting, while these Roblox examples run in Studio.
Lua vs Luau
Luau grew from Lua 5.1 and adds its own syntax and type checking. It is not another name for the latest Lua release. Check both the language and the host APIs before moving a Lua script into Roblox.
Variables, values and scope
Use local names for values that belong to a function or block. A nested block can read outer locals, but a new local with the same name shadows the outer binding. nil represents absence; false is an actual boolean value.
Inference, annotations and strict mode
Luau can infer types from expressions, while annotations document the boundary of a function or record. Strict mode reports more incomplete assumptions. Static checks help authors; runtime checks still protect values received from players or saved storage.
Functions, optional arguments and returns
Functions group a calculation or action behind a named boundary. Optional types allow nil; they do not supply defaults. Return tuples and variadic arguments are useful when the number of values matters, but named record results are often easier to extend.
Tables, arrays and dictionaries
A Luau table can hold a sequence, a dictionary or a record. A sequence uses consecutive integer keys starting at one; named fields describe a record. Type annotations describe the intended shape to the checker, but do not copy tables or validate incoming data at runtime.
Conditionals and operators
Use if statements to choose actions and if expressions to choose values. Only nil and false are falsey. A condition like if count does not test whether a count is positive, because zero is truthy.
Loops and iteration
Choose a numeric for loop for a known range, a table iterator for a collection, or a while loop for a condition. break leaves the loop and continue skips the rest of one iteration. Repeated engine work needs a schedule, not an unbounded busy loop.
Strings and interpolation
Strings hold text and are immutable values. Concatenation builds a new string; interpolation inserts expressions into a backtick-delimited string. Byte length, Unicode code points and what a person sees as one character are different measurements.
Closures and captured state
A closure is a function that keeps access to locals from its surrounding scope. Each call to a factory can create independent state. Capturing a value also extends how long it stays reachable, which matters for long-lived callbacks.
ModuleScripts and exported types
A ModuleScript returns a value for require to use. Keep reusable calculations in modules and choose storage based on who may require them. Requiring the same module on the client and server does not create shared memory between those environments.
Handling errors with pcall and xpcall
Protected calls turn an exception into a success flag and a result. They are useful around operations that can fail outside your control. They do not repair bad state, retry automatically, or mean every error should be ignored.
Script, LocalScript and ModuleScript placement
The same code can behave differently depending on where it runs. These lessons use server Scripts in ServerScriptService and LocalScripts in StarterPlayerScripts or StarterGui. A ModuleScript runs when required. Script RunContext also affects execution, so inspect it when a script appears silent.
Client/server boundaries and project structure
A server owns shared game decisions while each client handles its own input, camera and presentation. Treat client messages as requests. Put private rules in server containers and expose only the data and operations the client actually needs.
game, workspace and storage services
game is the root DataModel and workspace holds the active 3D world. GetService obtains engine services by class name. ReplicatedStorage is visible to both sides; ServerStorage holds objects clients should not receive until the server places them into a replicated location.
Instances, properties and methods
Instances form the Roblox object tree. Properties describe an object, methods perform operations, and events report changes. Check the class before using class-specific properties; a child with the right name can still be the wrong kind of object.
Events, connections and cleanup
Connect registers a callback and returns a connection you can disconnect. The callback runs when the event fires, not when it is registered. Long-lived services can keep callbacks alive after a feature has ended, so give each connection a clear cleanup point.
Player lifecycle and character spawning
A Player can remain connected while its character is destroyed and replaced. Initialize player state once, and character state on every spawn. Connecting an event alone can miss objects that already exist when a script starts.
Humanoid, HumanoidRootPart and attributes
Humanoid controls character behaviour such as health, while HumanoidRootPart gives a useful spatial reference. Attributes attach small named values to Instances. They are convenient for configuration and display, but client-side attributes are not proof that a player earned a reward.
RemoteEvent requests and notifications
RemoteEvent sends a message without waiting for a return value. A client calls FireServer; Roblox supplies the sending Player to OnServerEvent. The server can target one client with FireClient or broadcast with FireAllClients. This example requests a fixed help message, not a reward.
RemoteFunction and yielding requests
RemoteFunction is a request/response operation: InvokeServer yields until the server returns. Use it for a small, bounded query when the caller needs a result. Avoid making essential server progress depend on invoking an untrusted client.
Server authority, validation and rate limits
A valid-looking remote call can still be an impossible game action. Validate both the shape of a request and whether the sender may perform it now. This example lets a nearby living player request a visual switch; it does not trust a client position, target Instance or reward.
Raycasting and hit results
A raycast asks what a line segment intersects. Its direction vector includes the distance to search, not just a unit direction. A miss returns nil; a hit provides an Instance, position and surface normal. Filters determine what the query ignores.
Touch events, proximity prompts and debounce
Touched reports physical contact and can fire repeatedly for different body parts. ProximityPrompt presents an intentional interaction. Both need server checks for valuable actions, and cooldown state should match the unit you intend to limit: an object, a player or an action.
Tools and equipped behaviour
A Tool moves between a player’s Backpack and character when equipped. Activated is an input signal, not proof that a hit or purchase occurred. Separate the local presentation from any server action, and release temporary UI or connections when the tool is unequipped.
GUI buttons and user input
Player UI belongs on the client. Use GuiButton.Activated for a button that works across supported input methods, and avoid handling a keyboard shortcut when the interface has already consumed that input. A local UI action can request a server action, but cannot authorize it.
TweenService and transitions
TweenService interpolates supported properties over time. Creating a tween does not start it; call Play. Completion callbacks can also occur after cancellation, so inspect the playback state before treating the animation as a successful finish.
task scheduling and RunService
Use task scheduling for delayed or deferred work, and RunService when a feature genuinely depends on simulation or rendering steps. A delay is a minimum scheduling interval rather than an exact clock. Avoid doing work every frame when an event can report the change.
DataStore setup and safe Studio testing
DataStoreService persists data across sessions and is accessed by server scripts. Studio API access can reach real experience data. Use a separate test experience and test store names before enabling access; these examples are learning exercises, not a complete production persistence framework.
Load and validate player data
A successful read returning nil means no stored value exists. A failed read means the value is unknown. Those cases must never share a fallback that later saves defaults over real data. Validate stored fields before marking a session ready.
UpdateAsync and concurrent writes
UpdateAsync lets a non-yielding callback transform the latest value. It may invoke that callback again after a conflict. This example saves a monotonic highest-lesson record with max; that merge rule is appropriate for progress that never decreases, not balances, inventories or resets.
Retries, autosave and shutdown limits
A save can fail after gameplay succeeded. Keep the ready session available for another attempt, retry only a bounded number of times and report unresolved failures. PlayerRemoving and BindToClose are opportunities to save, not guarantees of durability.
Part properties
Create a physical block and control its size, position, color, and anchoring.
Model pivots
Move an assembled Model using its pivot instead of changing each part separately.
Folders
Organize related Roblox instances without giving the container physical behavior.
Attachments
Define a point and orientation on a part for effects and physics constraints.
WeldConstraint
Keep two parts in a fixed relative position as one assembly.
Workspace spatial queries
Find parts inside a 3D box using Workspace overlap queries.
Terrain editing
Fill a region of Roblox terrain with a material.
Lighting and time of day
Change a place’s global lighting time to create day or night.
Atmosphere
Control atmospheric haze and distance appearance in a 3D scene.
PointLight
Emit light in all directions from a part or attachment.
Collision groups
Configure which groups of physical parts can collide.
CollectionService tags
Label instances and find all objects that share a behavior.
Debris cleanup
Schedule a temporary instance to be destroyed after a delay.
ObjectValue references
Store a reference to another Roblox instance.
NumberValue state
Store a numeric value in the instance tree and react when it changes.
HingeConstraint motors
Rotate an assembly around a hinge axis using two attachments.
VectorForce
Apply a continuous force to a physics assembly.
LinearVelocity
Drive an assembly toward a target velocity.
ParticleEmitter
Create repeating or manually triggered particle effects.
Beam effects
Draw an effect between two attachments.
Highlight objects
Draw an outline or fill around a target object.
Sound playback
Play an approved audio asset from a sound instance.
SoundGroup mixing
Control the volume of several sounds as a group.
Camera control
Set a client camera viewpoint for a short scripted shot.
Humanoid states
Observe movement states such as running, jumping, and falling.
Animator and animation tracks
Load and play an animation through a character Animator.
PathfindingService paths
Compute navigable waypoints around obstacles.
Teams
Organize players into teams with team colors and assignments.
SpawnLocation
Choose where characters can spawn in a place.
ClickDetector
React when a player clicks a 3D object.
ScreenGui layers
Place a player interface on the screen and control whether it survives respawn.
Frame panels
Group on-screen controls inside a rectangular panel.
TextLabel
Display non-editable text in an interface.
TextButton actions
Handle a press on a text button across supported input methods.
TextBox input
Read text typed by a player and respond when editing ends.
ScrollingFrame
Display a list that can scroll beyond the visible panel.
UIListLayout
Automatically stack interface siblings in a row or column.
UIPadding
Add space between a UI container edge and its contents.
UIGradient
Blend colors across a UI object.
BillboardGui
Show a label in the 3D world that faces the viewer.
SurfaceGui
Render interface content on one face of a 3D part.
UICorner
Round the corners of a rectangular UI object.
UserInputService
Listen for client keyboard, mouse, touch, or other input events.
ContextActionService
Bind a named action to one or more input methods.
BindableEvent
Send a one-way signal between scripts on the same side of the client/server boundary.
BindableFunction
Ask another same-side script for a result.
UnreliableRemoteEvent
Send non-critical, frequent messages without guaranteed delivery or ordering.
HttpService JSON
Encode a simple table as JSON and decode it again.
OrderedDataStore leaderboards
Read ranked numeric values for a leaderboard.
MessagingService
Publish a small notification to live servers in the same experience.
Luau generic functions
A generic function relates its input and output types without replacing them with any. A reusable first-element helper can preserve the array element type while accounting for empty input.
Luau tagged result unions
A tagged union represents alternative record shapes using singleton fields. Testing the shared discriminant narrows the record so each branch can access the appropriate payload.
Luau recursive record types
Recursive type aliases describe linked structures such as trees and lists. An optional link supplies a stopping point; recursion in a type does not allocate any runtime data.
Luau intersection record types
An intersection requires a value to satisfy both component types. It can combine compatible record capabilities without copying or merging tables at runtime.
Luau generic type packs
Type packs describe lists of parameter or return types. A generic pack can preserve heterogeneous return values; it differs from a variadic pack whose elements share one type.
Luau typeof-derived aliases
The typeof type expression derives a static type from an expression. It can keep a helper's return type tied to a prototype while leaving runtime type queries as a separate use of typeof.
Luau frozen configuration tables
table.freeze prevents writes to an existing table and changes to its metatable. Freezing is shallow: nested values remain mutable unless frozen separately. Standard Lua does not provide this API.
Luau ordered record lists
table.sort rearranges a sequence in place with a strict comparator. Secondary keys make tied results deterministic without relying on a stable sort.
Luau preallocated arrays
table.create preallocates the array portion of a table. Providing a non-nil fill value creates entries, while omitting it only reserves capacity. This function is a Luau addition.
Luau table reuse with clear
table.clear removes every entry while preserving the table and its allocated capacity. All aliases observe the clearing because no replacement table is created. Standard Lua lacks this API.
Luau sequence searches
table.find returns the first index whose value equals the target or nil when absent. It searches a contiguous sequence and stops at the first nil; it does not search dictionary values.
Luau table slice copying
table.move copies an integer-keyed range into another position and supports overlapping ranges. It is available in Luau and Lua 5.3+, but not the original Lua 5.1 library.
Luau binary buffers
Luau buffers hold mutable binary bytes with zero-based offsets and typed read/write operations. Integer fields use little-endian storage. This example needs a current Luau runtime with the buffer library.
Luau bit32 masks
bit32 performs bitwise operations on numbers treated as unsigned 32-bit values. It is useful for compact flags; Luau does not use Lua 5.3's infix bitwise syntax.
Luau clamped numeric controls
math.clamp bounds a number between an inclusive minimum and maximum. It is useful for UI controls, progress values and gameplay parameters. It is a Luau library addition relative to standard Lua.
Luau nearest-integer rounding
math.round rounds to the nearest integer and resolves halfway cases away from zero. That rule differs from math.floor(x + 0.5) for negative halfway values.
Luau literal string splitting
string.split separates text using a literal separator and preserves empty fields. It is a Luau addition, not standard Lua's pattern-based gmatch.
Luau pattern-based extraction
Luau string.match supports Lua-style patterns and captures. Patterns are not full regular expressions; explicit anchors make them useful for small structured identifiers.
Luau coroutine producers
coroutine.wrap creates a resumable producer whose returned function supplies yielded values directly. Coroutines are cooperative execution, not operating-system parallelism or Roblox task scheduling.
Luau callable tables
The __call metamethod lets a table behave like a function while retaining state in fields. The first argument to the metamethod is the called table, followed by ordinary call arguments.