مطالعهٔ MDN Web Docs

مرجع عناصر HTML، مبانی CSS Grid، توابع JavaScript

باز کردن مرجع کامل دانلود آرشیو مستندات ناشر

گزیده‌ای از مستندات MDN Web Docs · نسخهٔ df622a2a1c1e · CC BY-SA 2.5 و مجوز جداگانهٔ ناشر برای نمونه‌کد

مرجع عناصر HTML

This page lists all the {{Glossary("HTML")}} {{Glossary("Element","elements")}}, which are created using {{Glossary("Tag", "tags")}}.

They are grouped by function to help you find what you have in mind easily. An alphabetical list of all elements is provided in the sidebar on every element's page as well as this one.

توجه: For more information about the basics of HTML elements and attributes, see Anatomy of an HTML element.

Main root

ElementDescription
{{HTMLElement("html")}}Represents the root (top-level element) of an HTML document, so it is also referred to as the _root element_. All other elements must be descendants of this element.

Document metadata

Metadata contains information about the page. This includes information about styles, scripts and data to help software ({{Glossary("search engine", "search engines")}}, {{Glossary("Browser","browsers")}}, etc.) use and render the page. Metadata for styles and scripts may be defined in the page or linked to another file that has the information.

ElementDescription
{{HTMLElement("base")}}Specifies the base URL to use for all relative URLs in a document. There can be only one such element in a document.
{{HTMLElement("head")}}Contains machine-readable information (metadata) about the document, like its title, scripts, and style sheets.
{{HTMLElement("link")}}Specifies relationships between the current document and an external resource. This element is most commonly used to link to CSS but is also used to establish site icons (both "favicon" style icons and icons for the home screen and apps on mobile devices) among other things.
{{HTMLElement("meta")}}Represents {{Glossary("Metadata","metadata")}} that cannot be represented by other HTML meta-related elements, like {{HTMLElement("base")}}, {{HTMLElement("link")}}, {{HTMLElement("script")}}, {{HTMLElement("style")}} and {{HTMLElement("title")}}.
{{HTMLElement("style")}}Contains style information for a document or part of a document. It contains CSS, which is applied to the contents of the document containing this element.
{{HTMLElement("title")}}Defines the document's title that is shown in a {{glossary("Browser", "browser")}}'s title bar or a page's tab. It only contains text; HTML tags within the element, if any, are also treated as plain text.

Sectioning root

ElementDescription
{{HTMLElement("body")}}Represents the content of an HTML document. There can be only one such element in a document.

Content sectioning

Content sectioning elements allow you to organize the document content into logical pieces. Use the sectioning elements to create a broad outline for your page content, including header and footer navigation, and heading elements to identify sections of content.

ElementDescription
{{HTMLElement("address")}}Indicates that the enclosed HTML provides contact information for a person or people, or for an organization.
{{HTMLElement("article")}}Represents a self-contained composition in a document, page, application, or site, which is intended to be independently distributable or reusable (e.g., in syndication). Examples include a forum post, a magazine or newspaper article, a blog entry, a product card, a user-submitted comment, an interactive widget or gadget, or any other independent item of content.
{{HTMLElement("aside")}}Represents a portion of a document whose content is only indirectly related to the document's main content. Asides are frequently presented as sidebars or call-out boxes.
{{HTMLElement("footer")}}Represents a footer for its nearest ancestor sectioning content or sectioning root element. A <footer> typically contains information about the author of the section, copyright data, or links to related documents.
{{HTMLElement("header")}}Represents introductory content, typically a group of introductory or navigational aids. It may contain some heading elements but also a logo, a search form, an author name, and other elements.
[<h1>](/en-US/docs/Web/HTML/Reference/Elements/Heading_Elements), [<h2>](/en-US/docs/Web/HTML/Reference/Elements/Heading_Elements), [<h3>](/en-US/docs/Web/HTML/Reference/Elements/Heading_Elements), [<h4>](/en-US/docs/Web/HTML/Reference/Elements/Heading_Elements), [<h5>](/en-US/docs/Web/HTML/Reference/Elements/Heading_Elements), [<h6>](/en-US/docs/Web/HTML/Reference/Elements/Heading_Elements)Represent six levels of section headings. <h1> is the highest section level and <h6> is the lowest.
{{HTMLElement("hgroup")}}Represents a heading grouped with any secondary content, such as subheadings, an alternative title, or a tagline.
{{HTMLElement("main")}}Represents the dominant content of the body of a document. The main content area consists of content that is directly related to or expands upon the central topic of a document, or the central functionality of an application.
{{HTMLElement("nav")}}Represents a section of a page whose purpose is to provide navigation links, either within the current document or to other documents. Common examples of navigation sections are menus, tables of contents, and indexes.
{{HTMLElement("section")}}Represents a generic standalone section of a document, which doesn't have a more specific semantic element to represent it. Sections should always have a heading, with very few exceptions.
{{HTMLElement("search")}}Represents a part that contains a set of form controls or other content related to performing a search or filtering operation.

Text content

Use HTML text content elements to organize blocks or sections of content placed between the opening {{HTMLElement("body")}} and closing </body> tags. Important for {{Glossary("accessibility")}} and {{Glossary("SEO")}}, these elements identify the purpose or structure of that content.

ElementDescription
{{HTMLElement("blockquote")}}Indicates that the enclosed text is an extended quotation. Usually, this is rendered visually by indentation. A URL for the source of the quotation may be given using the cite attribute, while a text representation of the source can be given using the {{HTMLElement("cite")}} element.
{{HTMLElement("dd")}}Provides the description, definition, or value for the preceding term ({{HTMLElement("dt")}}) in a description list ({{HTMLElement("dl")}}).
{{HTMLElement("div")}}The generic container for flow content. It has no effect on the content or layout until styled in some way using CSS (e.g., styling is directly applied to it, or some kind of layout model like {{glossary("Flexbox", "flexbox")}} is applied to its parent element).
{{HTMLElement("dl")}}Represents a description list. The element encloses a list of groups of terms (specified using the {{HTMLElement("dt")}} element) and descriptions (provided by {{HTMLElement("dd")}} elements). Common uses for this element are to implement a glossary or to display metadata (a list of key-value pairs).
{{HTMLElement("dt")}}Specifies a term in a description or definition list, and as such must be used inside a {{HTMLElement("dl")}} element. It is usually followed by a {{HTMLElement("dd")}} element; however, multiple <dt> elements in a row indicate several terms that are all defined by the immediate next {{HTMLElement("dd")}} element.
{{HTMLElement("figcaption")}}Represents a caption or legend describing the rest of the contents of its parent {{HTMLElement("figure")}} element.
{{HTMLElement("figure")}}Represents self-contained content, potentially with an optional caption, which is specified using the {{HTMLElement("figcaption")}} element. The figure, its caption, and its contents are referenced as a single unit.
{{HTMLElement("hr")}}Represents a thematic break between paragraph-level elements: for example, a change of scene in a story, or a shift of topic within a section.
{{HTMLElement("li")}}Represents an item in a list. It must be contained in a parent element: an ordered list ({{HTMLElement("ol")}}), an unordered list ({{HTMLElement("ul")}}), or a menu ({{HTMLElement("menu")}}). In menus and unordered lists, list items are usually displayed using bullet points. In ordered lists, they are usually displayed with an ascending counter on the left, such as a number or letter.
{{HTMLElement("menu")}}A semantic alternative to {{HTMLElement("ul")}}, but treated by browsers (and exposed through the accessibility tree) as no different than {{HTMLElement("ul")}}. It represents an unordered list of items (which are represented by {{HTMLElement("li")}} elements).
{{HTMLElement("ol")}}Represents an ordered list of items — typically rendered as a numbered list.
{{HTMLElement("p")}}Represents a paragraph. Paragraphs are usually represented in visual media as blocks of text separated from adjacent blocks by blank lines and/or first-line indentation, but HTML paragraphs can be any structural grouping of related content, such as images or form fields.
{{HTMLElement("pre")}}Represents preformatted text which is to be presented exactly as written in the HTML file. The text is typically rendered using a non-proportional, or monospaced, font. Whitespace inside this element is displayed as written.
{{HTMLElement("ul")}}Represents an unordered list of items, typically rendered as a bulleted list.

Inline text semantics

Use the HTML inline text semantic to define the meaning, structure, or style of a word, line, or any arbitrary piece of text.

ElementDescription
{{HTMLElement("a")}}Together with its href attribute, creates a hyperlink to web pages, files, email addresses, locations within the current page, or anything else a URL can address.
{{HTMLElement("abbr")}}Represents an abbreviation or acronym.
{{HTMLElement("b")}}Used to draw the reader's attention to the element's contents, which are not otherwise granted special importance. This was formerly known as the Boldface element, and most browsers still draw the text in boldface. However, you should not use <b> for styling text or granting importance. If you wish to create boldface text, you should use the CSS {{cssxref("font-weight")}} property. If you wish to indicate an element is of special importance, you should use the {{HTMLElement("strong")}} element.
{{HTMLElement("bdi")}}Tells the browser's bidirectional algorithm to treat the text it contains in isolation from its surrounding text. It's particularly useful when a website dynamically inserts some text and doesn't know the directionality of the text being inserted.
{{HTMLElement("bdo")}}Overrides the current directionality of text, so that the text within is rendered in a different direction.
{{HTMLElement("br")}}Produces a line break in text (carriage-return). It is useful for writing a poem or an address, where the division of lines is significant.
{{HTMLElement("cite")}}Used to mark up the title of a creative work. The reference may be in an abbreviated form according to context-appropriate conventions related to citation metadata.
{{HTMLElement("code")}}Displays its contents styled in a fashion intended to indicate that the text is a short fragment of computer code. By default, the content text is displayed using the user agent's default monospace font.
{{HTMLElement("data")}}Links a given piece of content with a machine-readable translation. If the content is time- or date-related, the <time> element must be used.
{{HTMLElement("dfn")}}Used to indicate the term being defined within the context of a definition phrase or sentence. The ancestor {{HTMLElement("p")}} element, the {{HTMLElement("dt")}}/{{HTMLElement("dd")}} pairing, or the nearest section ancestor of the <dfn> element, is considered to be the definition of the term.
{{HTMLElement("em")}}Marks text that has stress emphasis. The <em> element can be nested, with each nesting level indicating a greater degree of emphasis.
{{HTMLElement("i")}}Represents a range of text that is set off from the normal text for some reason, such as idiomatic text, technical terms, and taxonomical designations, among others. Historically, these have been presented using italicized type, which is the original source of the <i> naming of this element.
{{HTMLElement("kbd")}}Represents a span of inline text denoting textual user input from a keyboard, voice input, or any other text entry device. By convention, the user agent defaults to rendering the contents of a <kbd> element using its default monospace font, although this is not mandated by the HTML standard.
{{HTMLElement("mark")}}Represents text which is marked or highlighted for reference or notation purposes due to the marked passage's relevance in the enclosing context.
{{HTMLElement("q")}}Indicates that the enclosed text is a short inline quotation. Most modern browsers implement this by surrounding the text in quotation marks. This element is intended for short quotations that don't require paragraph breaks; for long quotations use the {{HTMLElement("blockquote")}} element.
{{HTMLElement("rp")}}Used to provide fall-back parentheses for browsers that do not support the display of ruby annotations using the {{HTMLElement("ruby")}} element. One <rp> element should enclose each of the opening and closing parentheses that wrap the {{HTMLElement("rt")}} element that contains the annotation's text.
{{HTMLElement("rt")}}Specifies the ruby text component of a ruby annotation, which is used to provide pronunciation, translation, or transliteration information for East Asian typography. The <rt> element must always be contained within a {{HTMLElement("ruby")}} element.
{{HTMLElement("ruby")}}Represents small annotations that are rendered above, below, or next to base text, usually used for showing the pronunciation of East Asian characters. It can also be used for annotating other kinds of text, but this usage is less common.
{{HTMLElement("s")}}Renders text with a strikethrough, or a line through it. Use the <s> element to represent things that are no longer relevant or no longer accurate. However, <s> is not appropriate when indicating document edits; for that, use the {{HTMLElement("del")}} and {{HTMLElement("ins")}} elements, as appropriate.
{{HTMLElement("samp")}}Used to enclose inline text which represents sample (or quoted) output from a computer program. Its contents are typically rendered using the browser's default monospaced font (such as Courier>) or Lucida Console).
{{HTMLElement("small")}}Represents side-comments and small print, like copyright and legal text, independent of its styled presentation. By default, it renders text within it one font size smaller, such as from small to x-small.
{{HTMLElement("span")}}A generic inline container for phrasing content, which does not inherently represent anything. It can be used to group elements for styling purposes (using the class or id attributes), or because they share attribute values, such as lang. It should be used only when no other semantic element is appropriate. <span> is very much like a div element, but div is a block-level element whereas a <span> is an inline-level element.
{{HTMLElement("strong")}}Indicates that its contents have strong importance, seriousness, or urgency. Browsers typically render the contents in bold type.
{{HTMLElement("sub")}}Specifies inline text which should be displayed as subscript for solely typographical reasons. Subscripts are typically rendered with a lowered baseline using smaller text.
{{HTMLElement("sup")}}Specifies inline text which is to be displayed as superscript for solely typographical reasons. Superscripts are usually rendered with a raised baseline using smaller text.
{{HTMLElement("time")}}Represents a specific period in time. It may include the datetime attribute to translate dates into machine-readable format, allowing for better search engine results or custom features such as reminders.
{{HTMLElement("u")}}Represents a span of inline text which should be rendered in a way that indicates that it has a non-textual annotation. This is rendered by default as a single solid underline but may be altered using CSS.
{{HTMLElement("var")}}Represents the name of a variable in a mathematical expression or a programming context. It's typically presented using an italicized version of the current typeface, although that behavior is browser-dependent.
{{HTMLElement("wbr")}}Represents a word break opportunity—a position within text where the browser may optionally break a line, though its line-breaking rules would not otherwise create a break at that location.

Image and multimedia

HTML supports various multimedia resources such as images, audio, and video.

ElementDescription
{{HTMLElement("area")}}Defines an area inside an image map that has predefined clickable areas. An _image map_ allows geometric areas on an image to be associated with {{Glossary("Hyperlink", "hyperlink")}}.
{{HTMLElement("audio")}}Used to embed sound content in documents. It may contain one or more audio sources, represented using the src attribute or the source element: the browser will choose the most suitable one. It can also be the destination for streamed media, using a {{domxref("MediaStream")}}.
{{HTMLElement("img")}}Embeds an image into the document.
{{HTMLElement("map")}}Used with {{HTMLElement("area")}} elements to define an image map (a clickable link area).
{{HTMLElement("track")}}Used as a child of the media elements, audio and video. It lets you specify timed text tracks (or time-based data), for example to automatically handle subtitles. The tracks are formatted in WebVTT format (.vtt files)—Web Video Text Tracks.
{{HTMLElement("video")}}Embeds a media player which supports video playback into the document. You can also use <video> for audio content, but the audio element may provide a more appropriate user experience.

Embedded content

In addition to regular multimedia content, HTML can include a variety of other content, even if it's not always easy to interact with.

ElementDescription
{{HTMLElement("embed")}}Embeds external content at the specified point in the document. This content is handled by the browser or an external application.
{{HTMLElement("iframe")}}Represents a nested browsing context, embedding another document into the current one.
{{HTMLElement("object")}}Represents an external resource, which can be treated as an image, a nested browsing context, or a resource to be handled by a plugin.
{{HTMLElement("picture")}}Contains zero or more {{HTMLElement("source")}} elements and one {{HTMLElement("img")}} element to offer alternative versions of an image for different display/device scenarios.
{{HTMLElement("source")}}Specifies multiple media resources for the picture, the audio element, or the video element. It is a void element, meaning that it has no content and does not have a closing tag. It is commonly used to offer the same media content in multiple file formats in order to provide compatibility with a broad range of browsers given their differing support for image file formats and media file formats.

SVG and MathML

You can embed SVG and MathML content directly into HTML documents, using the {{SVGElement("svg")}} and {{MathMLElement("math")}} elements.

ElementDescription
{{SVGElement("svg")}}Container defining a new coordinate system and viewport. It is used as the outermost element of SVG documents, but it can also be used to embed an SVG fragment inside an SVG or HTML document.
{{MathMLElement("math")}}The top-level element in MathML. Every valid MathML instance must be wrapped in it. In addition, you must not nest a second <math> element in another, but you can have an arbitrary number of other child elements in it.

Scripting

To create dynamic content and Web applications, HTML supports the use of scripting languages, most prominently JavaScript. Certain elements support this capability.

ElementDescription
{{HTMLElement("canvas")}}Container element to use with either the canvas scripting API or the WebGL API to draw graphics and animations.
{{HTMLElement("noscript")}}Defines a section of HTML to be inserted if a script type on the page is unsupported or if scripting is currently turned off in the browser.
{{HTMLElement("script")}}Used to embed executable code or data; this is typically used to embed or refer to JavaScript code. The <script> element can also be used with other languages, such as WebGL's GLSL shader programming language and JSON.

Demarcating edits

These elements let you provide indications that specific parts of the text have been altered.

ElementDescription
{{HTMLElement("del")}}Represents a range of text that has been deleted from a document. This can be used when rendering "track changes" or source code diff information, for example. The <ins> element can be used for the opposite purpose: to indicate text that has been added to the document.
{{HTMLElement("ins")}}Represents a range of text that has been added to a document. You can use the <del> element to similarly represent a range of text that has been deleted from the document.

Table content

The elements here are used to create and handle tabular data.

ElementDescription
{{HTMLElement("caption")}}Specifies the caption (or title) of a table.
{{HTMLElement("col")}}Defines one or more columns in a column group represented by its implicit or explicit parent {{HTMLElement("colgroup")}} element. The <col> element is only valid as a child of a {{HTMLElement("colgroup")}} element that has no [span](/en-US/docs/Web/HTML/Reference/Elements/colgroup#span) attribute defined.
{{HTMLElement("colgroup")}}Defines a group of columns within a table.
{{HTMLElement("table")}}Represents tabular data—that is, information presented in a two-dimensional table comprised of rows and columns of cells containing data.
{{HTMLElement("tbody")}}Encapsulates a set of table rows ({{HTMLElement("tr")}} elements), indicating that they comprise the body of a table's (main) data.
{{HTMLElement("td")}}A child of the {{HTMLElement("tr")}} element, it defines a cell of a table that contains data.
{{HTMLElement("tfoot")}}Encapsulates a set of table rows ({{HTMLElement("tr")}} elements), indicating that they comprise the foot of a table with information about the table's columns. This is usually a summary of the columns, e.g., a sum of the given numbers in a column.
{{HTMLElement("th")}}A child of the {{HTMLElement("tr")}} element, it defines a cell as the header of a group of table cells. The nature of this group can be explicitly defined by the [scope](/en-US/docs/Web/HTML/Reference/Elements/th#scope) and [headers](/en-US/docs/Web/HTML/Reference/Elements/th#headers) attributes.
{{HTMLElement("thead")}}Encapsulates a set of table rows ({{HTMLElement("tr")}} elements), indicating that they comprise the head of a table with information about the table's columns. This is usually in the form of column headers ({{HTMLElement("th")}} elements).
{{HTMLElement("tr")}}Defines a row of cells in a table. The row's cells can then be established using a mix of {{HTMLElement("td")}} (data cell) and {{HTMLElement("th")}} (header cell) elements.

Forms

HTML provides several elements that can be used together to create forms that the user can fill out and submit to the website or application. Further information about this available in the HTML forms guide.

ElementDescription
{{HTMLElement("button")}}An interactive element activated by a user with a mouse, keyboard, finger, voice command, or other assistive technology. Once activated, it performs an action, such as submitting a form or opening a dialog.
{{HTMLElement("datalist")}}Contains a set of {{HTMLElement("option")}} elements that represent the permissible or recommended options available to choose from within other controls.
{{HTMLElement("fieldset")}}Used to group several controls as well as labels ({{HTMLElement("label")}}) within a web form.
{{HTMLElement("form")}}Represents a document section containing interactive controls for submitting information.
{{HTMLElement("input")}}Used to create interactive controls for web-based forms to accept data from the user; a wide variety of types of input data and control widgets are available, depending on the device and user agent. The <input> element is one of the most powerful and complex in all of HTML due to the sheer number of combinations of input types and attributes.
{{HTMLElement("label")}}Represents a caption for an item in a user interface.
{{HTMLElement("legend")}}Represents a caption for the content of its parent {{HTMLElement("fieldset")}}.
{{HTMLElement("meter")}}Represents either a scalar value within a known range or a fractional value.
{{HTMLElement("optgroup")}}Creates a grouping of options within a {{HTMLElement("select")}} element.
{{HTMLElement("option")}}Used to define an item contained in a {{HTMLElement("select")}}, an {{HTMLElement("optgroup")}}, or a {{HTMLElement("datalist")}} element. As such, <option> can represent menu items in popups and other lists of items in an HTML document.
{{HTMLElement("output")}}Container element into which a site or app can inject the results of a calculation or the outcome of a user action.
{{HTMLElement("progress")}}Displays an indicator showing the completion progress of a task, typically displayed as a progress bar.
{{HTMLElement("select")}}Represents a control that provides a menu of options.
{{HTMLElement("selectedcontent")}}Displays the content of the currently selected <option> inside a closed <select> element.
{{HTMLElement("textarea")}}Represents a multi-line plain-text editing control, useful when you want to allow users to enter a sizeable amount of free-form text, for example, a comment on a review or feedback form.

Interactive elements

HTML offers a selection of elements that help to create interactive user interface objects.

ElementDescription
{{HTMLElement("details")}}Creates a disclosure widget in which information is visible only when the widget is toggled into an "open" state. A summary or label must be provided using the {{HTMLElement("summary")}} element.
{{HTMLElement("dialog")}}Represents a dialog box or other interactive component, such as a dismissible alert, inspector, or subwindow.
{{HTMLElement("geolocation")}} {{experimental_inline}}Creates an interactive control for the user to share their geolocation data with the page.
{{HTMLElement("summary")}}Specifies a summary, caption, or legend for a details element's disclosure box. Clicking the <summary> element toggles the state of the parent {{HTMLElement("details")}} element open and closed.

Web Components

Web Components is an HTML-related technology that makes it possible to, essentially, create and use custom elements as if it were regular HTML. In addition, you can create custom versions of standard HTML elements.

ElementDescription
{{HTMLElement("slot")}}Part of the Web Components technology suite, this element is a placeholder inside a web component that you can fill with your own markup, which lets you create separate DOM trees and present them together.
{{HTMLElement("template")}}A mechanism for holding HTML that is not to be rendered immediately when a page is loaded but may be instantiated subsequently during runtime using JavaScript.

Obsolete and deprecated elements

توجه: These are old HTML elements that are deprecated and should not be used. You should never use them in new projects, and you should replace them in old projects as soon as you can. They are listed here for completeness only.

ElementDescription
{{HTMLElement("acronym")}}Allows authors to clearly indicate a sequence of characters that compose an acronym or abbreviation for a word.
{{HTMLElement("big")}}Renders the enclosed text at a font size one level larger than the surrounding text (medium becomes large, for example). The size is capped at the browser's maximum permitted font size.
{{HTMLElement("center")}}Displays its block-level or inline contents centered horizontally within its containing element.
<content>An obsolete part of the Web Components suite of technologies—was used inside of Shadow DOM as an insertion point, and wasn't meant to be used in ordinary HTML. It has now been replaced by the {{HTMLElement("slot")}} element, which creates a point in the DOM at which a shadow DOM can be inserted. Consider using {{HTMLElement("slot")}} instead.
{{HTMLElement("dir")}}Container for a directory of files and/or folders, potentially with styles and icons applied by the user agent. Do not use this obsolete element; instead, you should use the {{HTMLElement("ul")}} element for lists, including lists of files.
{{HTMLElement("fencedframe")}}Represents a nested browsing context, like <iframe> but with more native privacy features built in.
{{HTMLElement("font")}}Defines the font size, color and face for its content.
{{HTMLElement("frame")}}Defines a particular area in which another HTML document can be displayed. A frame should be used within a {{HTMLElement("frameset")}}.
{{HTMLElement("frameset")}}Used to contain {{HTMLElement("frame")}} elements.
<image>An ancient and poorly supported precursor to the {{HTMLElement("img")}} element. It should not be used.
{{HTMLElement("marquee")}}Used to insert a scrolling area of text. You can control what happens when the text reaches the edges of its content area using its attributes.
<menuitem>Represents a command that a user is able to invoke through a popup menu. This includes context menus, as well as menus that might be attached to a menu button.
{{HTMLElement("nobr")}}Prevents the text it contains from automatically wrapping across multiple lines, potentially resulting in the user having to scroll horizontally to see the entire width of the text.
{{HTMLElement("noembed")}}An obsolete, non-standard way to provide alternative, or "fallback", content for browsers that do not support the embed element or do not support the type of embedded content an author wishes to use. This element was deprecated in HTML 4.01 and above in favor of placing fallback content between the opening and closing tags of an {{HTMLElement("object")}} element.
{{HTMLElement("noframes")}}Provides content to be presented in browsers that don't support (or have disabled support for) the {{HTMLElement("frame")}} element. Although most commonly-used browsers support frames, there are exceptions, including certain special-use browsers including some mobile browsers, as well as text-mode browsers.
{{HTMLElement("param")}}Defines parameters for an {{HTMLElement("object")}} element.
{{HTMLElement("plaintext")}}Renders everything following the start tag as raw text, ignoring any following HTML. There is no closing tag, since everything after it is considered raw text.
{{HTMLElement("rb")}}Used to delimit the base text component of a ruby annotation, i.e., the text that is being annotated. One <rb> element should wrap each separate atomic segment of the base text.
{{HTMLElement("rtc")}}Embraces semantic annotations of characters presented in a ruby of {{HTMLElement("rb")}} elements used inside of {{HTMLElement("ruby")}} element. {{HTMLElement("rb")}} elements can have both pronunciation ({{HTMLElement("rt")}}) and semantic ({{HTMLElement("rtc")}}) annotations.
<shadow>An obsolete part of the Web Components technology suite that was intended to be used as a shadow DOM insertion point. You might have used it if you have created multiple shadow roots under a shadow host. Consider using {{HTMLElement("slot")}} instead.
{{HTMLElement("strike")}}Places a strikethrough (horizontal line) over text.
{{HTMLElement("tt")}}Creates inline text which is presented using the user agent default monospace font face. This element was created for the purpose of rendering text as it would be displayed on a fixed-width display such as a teletype, text-only screen, or line printer.
{{HTMLElement("xmp")}}Renders text between the start and end tags without interpreting the HTML in between and using a monospaced font. The HTML2 specification recommended that it should be rendered wide enough to allow 80 characters per line.

See also

  • {{DOMXref("Element")}} interface

مبانی CSS Grid

CSS grid layout introduces a two-dimensional grid system to CSS. Grids can be used to lay out major page areas or small user interface elements. This guide introduces the CSS grid layout and the terminology that is part of the CSS grid layout specification. The features shown in this overview will then be explained in greater detail in the other guides in this series.

What is a grid?

A grid is a set of intersecting horizontal and vertical lines defining rows and columns. Elements can be placed onto the grid within these column and row lines. CSS grid layout has the following features:

Fixed and flexible track sizes

You can create a grid with fixed track sizes – using pixels for example. This sets the grid to the specified pixel which fits to the layout you desire. You can also create a grid using flexible sizes with percentages or with the [fr](#the_fr_unit) unit designed for this purpose.

Item placement

You can place items into a precise location on the grid using line numbers, names or by targeting an area of the grid. Grid also contains an algorithm to control the placement of items not given an explicit position on the grid.

Creation of additional tracks to hold content

You can define an explicit grid with grid layout. The features defined by the grid layout module provide the flexibility to add additional rows and columns when needed. Features such as adding "as many columns that will fit into a container" are included.

Alignment control

CSS grid layout and CSS box alignment features enable us to control how the items align once placed into a grid area, and how the entire grid is aligned.

Control of overlapping content

More than one item can be placed into a grid cell or area and they can partially overlap each other. This layering may then be controlled with the {{cssxref("z-index")}} property.

Grid is a powerful layout method that, when combined with other parts of CSS such as flexbox, can help you create layouts that are responsive, flexible, and accessible. It all starts by creating a grid in your {{glossary("grid container")}}.

Grid container

We create a _grid container_ by declaring display: grid or display: inline-grid on an element. As soon as we do this, all _direct children_ of that element become _grid items_.

In this example, we have a containing div with a class of wrapper. Nested inside are five child elements.

html
<div class="wrapper">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
  <div>Four</div>
  <div>Five</div>
</div>

We make the .wrapper a grid container using display: grid;.

css
.wrapper {
  display: grid;
}
css hidden

{{ EmbedLiveSample('grid_container', '200', '330') }}

All the direct children are now grid items. In a web browser, you won't see any difference to how these items are displayed before turning them into a grid, as grid has created a single column grid for the items. If you inspect the grid in your browsers developer tools, you may see a small icon next to the value grid. Click this and, in most browsers, the grid on this element will be overlaid in the browser window.

Using the grid highlighter in Firefox DevTools to view a grid

As you learn and then work with the CSS grid layout, your browser tools will give you a better idea of what is happening with your grids visually.

If we want to start making this more grid-like we need to add column tracks.

Grid tracks

We define rows and columns on our grid with the {{cssxref("grid-template-rows")}} and {{cssxref("grid-template-columns")}} properties. These define {{glossary("grid tracks")}}. A _grid track_ is the space between any two adjacent lines on the grid. The image below shows a highlighted track – this is the first-row track in our grid.

A box with 3 grid items. Above the three items is a solid light green area which is the track.

Grid tracks are defined in the explicit grid by using the grid-template-columns and grid-template-rows properties or the shorthand grid or grid-template properties. Tracks are also created in the implicit grid by positioning a grid item outside of the tracks created in the explicit grid.

Basic example

We can add column tracks to our earlier example by adding the grid-template-columns property, then defining the size of the column tracks.

We have now created a grid with three 200-pixel-wide column tracks. The child items will be laid out on this grid one in each grid cell.

html
<div class="wrapper">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
  <div>Four</div>
  <div>Five</div>
</div>
css
.wrapper {
  display: grid;
  grid-template-columns: 200px 200px 200px;
}
css hidden

{{ EmbedLiveSample('Basic_example', '610', '140') }}

The fr unit

Tracks can be defined using any length unit. Grid also introduces an additional length unit to help us create flexible grid tracks. The [fr](/en-US/docs/Web/CSS/Reference/Values/flex_value) unit represents a fraction of the available space in the grid container. The next grid definition would create three equal width tracks that grow and shrink according to the available space.

html
<div class="wrapper">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
  <div>Four</div>
  <div>Five</div>
</div>
css
.wrapper {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}
css hidden

{{ EmbedLiveSample('The_fr_unit', '220', '140') }}

Unequal sizes

In this example, we create a definition with a 2fr track then two 1fr tracks. The available space is split into four. Two parts are given to the first track and one part each to the next two tracks.

html
<div class="wrapper">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
  <div>Four</div>
  <div>Five</div>
</div>
css
.wrapper {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr;
}
css hidden

{{ EmbedLiveSample('Unequal_sizes', '220', '140') }}

Mixing flexible and absolute sizes

In this final example, we mix absolute sized tracks with fr units. The first track is 500px, so the fixed width is taken away from the available space. The remaining space is divided into three and assigned in proportion to the two flexible tracks.

html
<div class="wrapper">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
  <div>Four</div>
  <div>Five</div>
</div>
css
.wrapper {
  display: grid;
  grid-template-columns: 500px 1fr 2fr;
}
css hidden

{{ EmbedLiveSample('Mixing_flexible_and_absolute_sizes', '220', '140') }}

Track listings with repeat() notation

Large grids with many tracks can use the [repeat()](/en-US/docs/Web/CSS/Reference/Values/repeat) notation, to repeat all or a section of the list of grid tracks. For example the grid definition:

css
.wrapper {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}

Can also be written as:

css
.wrapper {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}

Repeat notation can be used for a part of the list of tracks. In this example, we create an 8-column grid; the initial track is 20px, then a repeating section of 6 1fr tracks, and a final 20px track.

css
.wrapper {
  display: grid;
  grid-template-columns: 20px repeat(6, 1fr) 20px;
}

Repeat notation (repeat()) uses the track listing to create a repeating pattern of tracks. In this example, the grid will have 10 tracks; a 1fr track is followed by a 2fr track, with this pattern being repeated five times.

css
.wrapper {
  display: grid;
  grid-template-columns: repeat(5, 1fr 2fr);
}

Implicit and explicit grids

When creating our example grid, we specifically defined our column tracks with the {{cssxref("grid-template-columns")}} property, with the grid creating rows as needed to fit the content. The columns define the explicit grid while the rows are part of the implicit grid.

The _explicit grid_ consists of rows and columns defined with {{cssxref("grid-template-columns")}} or {{cssxref("grid-template-rows")}}. The _implicit grid_ extends the defined explicit grid when content is placed outside of that grid, such as into the rows by drawing additional grid lines.

If you place something outside of the defined grid or, due to the amount of content, more grid tracks are needed, then the grid creates rows and columns in the _implicit grid_. These implicit tracks are auto-sized by default, meaning the size of the created rows or columns is influenced by both their content and by the available free space within the grid container. The auto keyword allows the generated tracks to accommodate content while also sharing any remaining space.

You can also define a set size for tracks created in the implicit grid with the {{cssxref("grid-auto-rows")}} and {{cssxref("grid-auto-columns")}} properties.

In this example, we set grid-auto-rows: 200px, ensuring the tracks created in this implicit grid are 200px tall.

html
<div class="wrapper">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
  <div>Four</div>
  <div>Five</div>
</div>
css
.wrapper {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-auto-rows: 200px;
}
css hidden

{{ EmbedLiveSample('implicit_and_explicit_grids', '230', '450') }}

Track sizing and minmax

When setting up an explicit grid or defining the sizing for automatically created rows or columns we may want to give tracks a minimum size, but also ensure they expand to fit any content that is added. For example, we may want our rows to never collapse smaller than 100 pixels, but if our content stretches to 300 pixels in height, then we would like the row to stretch to that height. This is solved by the {{cssxref("minmax()")}} function.

In this example, we use minmax() within the grid-auto-rows property value. By setting grid-auto-rows: minmax(100px, auto);, automatically created rows will be a minimum of 100px tall, and have a maximum of auto. Setting auto as the maximum value allows the track to grow to accommodate its content (up to its max-content size) while also sharing any available free space within the grid container.

css
.wrapper {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-auto-rows: minmax(100px, auto);
}
css hidden
html hidden

{{ EmbedLiveSample('Track_sizing_and_minmax', '240', '270') }}

Grid lines

It should be noted that when we define a grid we define the grid tracks, not the lines. Grid then gives us numbered lines to use when positioning items. In our three column, two row grid we have four column lines.

Diagram showing numbered grid lines.

Lines are numbered according to the writing mode of the document. In a left-to-right language, line 1 is on the left-hand side of the grid. In a right-to-left language, it is on the right-hand side of the grid. Lines can also be named, which is discussed in the grid layout using named grid lines guide.

Positioning items against lines

The following example demonstrates basic line-based placement; when placing an item, we target the line rather than the track. We explore this in greater detail in the grid layout using line-based placement guide.

In this example, the first two items on our three column track grid are placed using the {{cssxref("grid-column-start")}}, {{cssxref("grid-column-end")}}, {{cssxref("grid-row-start")}} and {{cssxref("grid-row-end")}} properties. Working from left to right, the first item is placed against column line 1, and spans to column line 4, which in our case is the far-right line on the grid. It begins at row line 1 and ends at row line 3, therefore spanning two row tracks.

The second item starts on grid column line 1, and spans one track. This is the default, so we do not need to specify the end line. It also spans two row tracks from row line 3 to row line 5. The other items will place themselves into empty spaces on the grid.

html
<div class="wrapper">
  <div class="box1">One</div>
  <div class="box2">Two</div>
  <div class="box3">Three</div>
  <div class="box4">Four</div>
  <div class="box5">Five</div>
</div>
css
.wrapper {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-auto-rows: 100px;
}

.box1 {
  grid-column-start: 1;
  grid-column-end: 4;
  grid-row-start: 1;
  grid-row-end: 3;
}

.box2 {
  grid-column-start: 1;
  grid-row-start: 3;
  grid-row-end: 5;
}
css hidden

{{ EmbedLiveSample('Positioning_items_against_lines', '230', '450') }}

Use the grid inspector in your developer tools to see how the items are positioned against the lines of the grid.

Line-positioning shorthands

The longhand values used above can be compressed onto one line for columns with the {{cssxref("grid-column")}} shorthand, and one line for rows with the {{cssxref("grid-row")}} shorthand. The following example would give the same positioning as in the previous code, but with far less CSS. The value before the forward slash character (/) is the start line, the value after the end line.

You can omit the end value if the area only spans one track.

css
.wrapper {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-auto-rows: 100px;
}

.box1 {
  grid-column: 1 / 4;
  grid-row: 1 / 3;
}

.box2 {
  grid-column: 1;
  grid-row: 3 / 5;
}

Grid cells

A _grid cell_ is the smallest unit on a grid. Conceptually it is like a table cell. As we saw in our earlier examples, once a grid is defined as a parent the child items will lay themselves out in one cell each of the defined grid. In the below image, the first cell of the grid is highlighted.

The first cell of the grid highlighted

Grid areas

Items can span one or more cells both by row or by column, and this creates a _grid area_. Grid areas must be rectangular – it isn't possible to create an L-shaped area for example. The highlighted grid area spans two row and two column tracks.

A grid area

Gutters

_Gutters_ or _alleys_ between grid cells can be created using the {{cssxref("column-gap")}} and {{cssxref("row-gap")}} properties, or the shorthand {{cssxref("gap")}}. In the below example, we add a 10-pixel gap between columns and a 1em gap between rows.

css
.wrapper {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  column-gap: 10px;
  row-gap: 1em;
}
html
<div class="wrapper">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
  <div>Four</div>
  <div>Five</div>
</div>
css hidden

{{ EmbedLiveSample('Gutters') }}

Any space used by gaps will be accounted for before space is assigned to the flexible length fr tracks, and gaps act for sizing purposes like a regular grid track, however you cannot place anything into a gap. In terms of line-based positioning, the gap acts like a thick, transparent line.

Nesting grids

A grid item can become a grid container. In the following example, we extend the three-column grid with two positioned items seen earlier, adding sub-items to the first grid item. As these nested items are not direct children of the grid they do not participate in grid layout and so display in a normal document flow.

Nested grid in flow

Nesting without subgrid

If we set box1 to display: grid, we can give it a track definition and it too will become a grid. The items then lay out on this new grid.

html
<div class="wrapper">
  <div class="box box1">
    <div class="nested">a</div>
    <div class="nested">b</div>
    <div class="nested">c</div>
  </div>
  <div class="box box2">Two</div>
  <div class="box box3">Three</div>
  <div class="box box4">Four</div>
  <div class="box box5">Five</div>
</div>
css
* {
  box-sizing: border-box;
}

.wrapper {
  border: 2px solid #f76707;
  border-radius: 5px;
  gap: 3px;
  background-color: #fff4e6;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}

.box {
  border: 2px solid #ffa94d;
  border-radius: 5px;
  background-color: #ffd8a8;
  padding: 1em;
  color: #d9480f;
}

.box1 {
  grid-column-start: 1;
  grid-column-end: 4;
  grid-row-start: 1;
  grid-row-end: 3;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}

.nested {
  border: 2px solid #ffec99;
  border-radius: 5px;
  background-color: #fff9db;
  padding: 1em;
}

{{ EmbedLiveSample('Nesting_without_subgrid', '600', '250') }}

In this case the nested grid has no relationship to the parent. As you can see in the example it has not inherited the {{cssxref("gap")}} of the parent and the lines in the nested grid do not align to the lines in the parent grid.

Subgrid

In addition to regular grids, we can create _subgrid_. The subgrid value lets us create nested grids that use the track definition of the parent grid.

To use them, we edit the above nested grid example to change the track definition of grid-template-columns: repeat(3, 1fr), to grid-template-columns: subgrid. The nested grid then uses the parent grid tracks to lay out items.

css
.box1 {
  grid-column-start: 1;
  grid-column-end: 4;
  grid-row-start: 1;
  grid-row-end: 3;
  display: grid;
  grid-template-columns: subgrid;
}

Layering items with z-index

Grid items can occupy the same cell, and in this case we can use the {{cssxref("z-index")}} property to control the order in which overlapping items stack.

Overlapping without z-index

If we return to our example with items positioned by line number, we can change this to make two items overlap.

html
<div class="wrapper">
  <div class="box box1">One</div>
  <div class="box box2">Two</div>
  <div class="box box3">Three</div>
  <div class="box box4">Four</div>
  <div class="box box5">Five</div>
</div>
css
.wrapper {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-auto-rows: 100px;
}

.box1 {
  grid-column-start: 1;
  grid-column-end: 4;
  grid-row-start: 1;
  grid-row-end: 3;
}

.box2 {
  grid-column-start: 1;
  grid-row-start: 2;
  grid-row-end: 4;
}
css hidden

{{ EmbedLiveSample('Overlapping_without_z-index', '230', '460') }}

The item box2 is now overlapping box1, it displays on top as it comes later in the source order.

Controlling the order

We can control the order in which items stack up by using the z-index property - just like positioned items. If we give box2 a lower z-index than box1 it will display below box1 in the stack.

css
.wrapper {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-auto-rows: 100px;
}

.box1 {
  grid-column-start: 1;
  grid-column-end: 4;
  grid-row-start: 1;
  grid-row-end: 3;
  z-index: 2;
}

.box2 {
  grid-column-start: 1;
  grid-row-start: 2;
  grid-row-end: 4;
  z-index: 1;
}
html hidden
css hidden

{{ EmbedLiveSample('Controlling_the_order', '230', '420') }}

Next steps

In this overview, we took a very quick look at the possibilities of grid layouts. Explore and play with the code examples, and then move on to the guide, relationship of grid layout with other layout methods, where we will really start to dig into the details of CSS grid layout.

توابع JavaScript

{{PreviousNext("Web/JavaScript/Guide/Loops_and_iteration", "Web/JavaScript/Guide/Expressions_and_operators")}}

Functions are one of the fundamental building blocks in JavaScript. A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output. To use a function, you must define it somewhere in the scope from which you wish to call it.

See also the exhaustive reference chapter about JavaScript functions to get to know the details.

Defining functions

Function declarations

A function definition (also called a function declaration, or function statement) consists of the [function](/en-US/docs/Web/JavaScript/Reference/Statements/function) keyword, followed by:

  • The name of the function.
  • A list of parameters to the function, enclosed in parentheses and separated by commas.
  • The JavaScript statements that define the function, enclosed in curly braces, { /* … */ }.

For example, the following code defines a function named square:

js
function square(number) {
  return number * number;
}

The function square takes one parameter, called number. The function consists of one statement that says to return the parameter of the function (that is, number) multiplied by itself. The [return](/en-US/docs/Web/JavaScript/Reference/Statements/return) statement specifies the value returned by the function, which is number * number.

Parameters are essentially passed to functions by value — so if the code within the body of a function assigns a completely new value to a parameter that was passed to the function, the change is not reflected globally or in the code which called that function.

When you pass an object as a parameter, if the function changes the object's properties, that change is visible outside the function, as shown in the following example:

js
function myFunc(theObject) {
  theObject.make = "Toyota";
}

const myCar = {
  make: "Honda",
  model: "Accord",
  year: 1998,
};

console.log(myCar.make); // "Honda"
myFunc(myCar);
console.log(myCar.make); // "Toyota"

When you pass an array as a parameter, if the function changes any of the array's values, that change is visible outside the function, as shown in the following example:

js
function myFunc(theArr) {
  theArr[0] = 30;
}

const arr = [45];

console.log(arr[0]); // 45
myFunc(arr);
console.log(arr[0]); // 30

Function declarations and expressions can be nested, which forms a _scope chain_. For example:

js
function addSquares(a, b) {
  function square(x) {
    return x * x;
  }
  return square(a) + square(b);
}

See function scopes and closures for more information.

Function expressions

While the function declaration above is syntactically a statement, functions can also be created by a function expression.

Such a function can be anonymous; it does not have to have a name. For example, the function square could have been defined as:

js
const square = function (number) {
  return number * number;
};

console.log(square(4)); // 16

However, a name _can_ be provided with a function expression. Providing a name allows the function to refer to itself, and also makes it easier to identify the function in a debugger's stack traces:

js
const factorial = function fac(n) {
  return n < 2 ? 1 : n * fac(n - 1);
};

console.log(factorial(3)); // 6

Function expressions are convenient when passing a function as an argument to another function. The following example defines a map function that should receive a function as first argument and an array as second argument. Then, it is called with a function defined by a function expression:

js
function map(f, a) {
  const result = new Array(a.length);
  for (let i = 0; i < a.length; i++) {
    result[i] = f(a[i]);
  }
  return result;
}

const numbers = [0, 1, 2, 5, 10];
const cubedNumbers = map(function (x) {
  return x * x * x;
}, numbers);
console.log(cubedNumbers); // [0, 1, 8, 125, 1000]

In JavaScript, a function can be defined based on a condition. For example, the following function definition defines myFunc only if num equals 0:

js
let myFunc;
if (num === 0) {
  myFunc = function (theObject) {
    theObject.make = "Toyota";
  };
}

In addition to defining functions as described here, you can also use the {{jsxref("Function")}} constructor to create functions from a string at runtime, much like {{jsxref("Global_Objects/eval", "eval()")}}.

A method is a function that is a property of an object. Read more about objects and methods in Working with objects.

Calling functions

_Defining_ a function does not _execute_ it. Defining it names the function and specifies what to do when the function is called.

Calling the function actually performs the specified actions with the indicated parameters. For example, if you define the function square, you could call it as follows:

js
square(5);

The preceding statement calls the function with an argument of 5. The function executes its statements and returns the value 25.

Functions must be _in scope_ when they are called, but the function declaration can be hoisted (appear below the call in the code). The scope of a function declaration is the function in which it is declared (or the entire program, if it is declared at the top level).

The arguments of a function are not limited to strings and numbers. You can pass whole objects to a function. The showProps() function (defined in Working with objects) is an example of a function that takes an object as an argument.

A function can call itself. For example, here is a function that computes factorials recursively:

js
function factorial(n) {
  if (n === 0 || n === 1) {
    return 1;
  }
  return n * factorial(n - 1);
}

You could then compute the factorials of 1 through 5 as follows:

js
console.log(factorial(1)); // 1
console.log(factorial(2)); // 2
console.log(factorial(3)); // 6
console.log(factorial(4)); // 24
console.log(factorial(5)); // 120

There are other ways to call functions. There are often cases where a function needs to be called dynamically, or the number of arguments to a function vary, or in which the context of the function call needs to be set to a specific object determined at runtime.

It turns out that _functions are themselves objects_ — and in turn, these objects have methods. (See the {{jsxref("Function")}} object.) The [call()](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) and [apply()](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply) methods can be used to achieve this goal.

Function hoisting

Consider the example below:

js
console.log(square(5)); // 25

function square(n) {
  return n * n;
}

This code runs without any error, despite the square() function being called before it's declared. This is because the JavaScript interpreter hoists the entire function declaration to the top of the current scope, so the code above is equivalent to:

js
// All function declarations are effectively at the top of the scope
function square(n) {
  return n * n;
}

console.log(square(5)); // 25

Function hoisting only works with function _declarations_ — not with function _expressions_. The following code will not work:

js example-bad
console.log(square(5)); // ReferenceError: Cannot access 'square' before initialization
const square = function (n) {
  return n * n;
};

Recursion

A function can refer to and call itself. It can be referred to either by the function expression or declaration's name, or via any in-scope variable that refers to the function object. For example, consider the following function definition:

js
const foo = function bar() {
  // statements go here
};

Within the function body, you can refer to the function itself either as bar or foo, and call itself using bar() or foo().

A function that calls itself is called a _recursive function_. In some ways, recursion is analogous to a loop. Both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case).

For example, consider the following loop:

js
let x = 0;
// "x < 10" is the loop condition
while (x < 10) {
  // do stuff
  x++;
}

It can be converted into a recursive function declaration, followed by a call to that function:

js
function loop(x) {
  // "x >= 10" is the exit condition (equivalent to "!(x < 10)")
  if (x >= 10) {
    return;
  }
  // do stuff
  loop(x + 1); // the recursive call
}
loop(0);

However, some algorithms cannot be simple iterative loops. For example, getting all the nodes of a tree structure (such as the DOM) is easier via recursion:

js
function walkTree(node) {
  if (node === null) {
    return;
  }
  // do something with node
  for (const child of node.childNodes) {
    walkTree(child);
  }
}

Compared to the function loop, each recursive call itself makes many recursive calls here.

It is possible to convert any recursive algorithm to a non-recursive one, but the logic is often much more complex, and doing so requires the use of a stack.

In fact, recursion itself uses a stack: the function stack. The stack-like behavior can be seen in the following example:

js
function foo(i) {
  if (i < 0) {
    return;
  }
  console.log(`begin: ${i}`);
  foo(i - 1);
  console.log(`end: ${i}`);
}
foo(3);

// Logs:
// begin: 3
// begin: 2
// begin: 1
// begin: 0
// end: 0
// end: 1
// end: 2
// end: 3

Immediately Invoked Function Expressions (IIFE)

An Immediately Invoked Function Expression (IIFE) is a code pattern that directly calls a function defined as an expression. It looks like this:

js
(function () {
  // Do something
})();

const value = (function () {
  // Do something
  return someValue;
})();

Instead of saving the function in a variable, the function is immediately invoked. This is almost equivalent to just writing the function body, but there are a few unique benefits:

  • It creates an extra scope of variables, which helps to confine variables to the place where they are useful.
  • It is now an _expression_ instead of a sequence of _statements_. This allows you to write complex computation logic when initializing variables.

For more information, see the IIFE glossary entry.

Function scopes and closures

Functions form a scope for variables—this means variables defined inside a function cannot be accessed from anywhere outside the function. The function scope inherits from all the upper scopes. For example, a function defined in the global scope can access all variables defined in the global scope. A function defined inside another function can also access all variables defined in its parent function, and any other variables to which the parent function has access. On the other hand, the parent function (and any other parent scope) does _not_ have access to the variables and functions defined inside the inner function. This provides a sort of encapsulation for the variables in the inner function.

js
// The following variables are defined in the global scope
const num1 = 20;
const num2 = 3;
const name = "Chamakh";

// This function is defined in the global scope
function multiply() {
  return num1 * num2;
}

console.log(multiply()); // 60

// A nested function example
function getScore() {
  const num1 = 2;
  const num2 = 3;

  function add() {
    return `${name} scored ${num1 + num2}`;
  }

  return add();
}

console.log(getScore()); // "Chamakh scored 5"

Closures

We also refer to the function body as a _closure_. A closure is any piece of source code (most commonly, a function) that refers to some variables, and the closure "remembers" these variables even when the scope in which these variables were declared has exited.

Closures are usually illustrated with nested functions to show that they remember variables beyond the lifetime of its parent scope; but in fact, nested functions are unnecessary. Technically speaking, all functions in JavaScript form closures—some just don't capture anything, and closures don't even have to be functions. The key ingredients for a _useful_ closure are the following:

  • A parent scope that defines some variables or functions. It should have a clear lifetime, which means it should finish execution at some point. Any scope that's not the global scope satisfies this requirement; this includes blocks, functions, modules, and more.
  • An inner scope defined within the parent scope, which refers to some variables or functions defined in the parent scope.
  • The inner scope manages to survive beyond the lifetime of the parent scope. For example, it is saved to a variable that's defined outside the parent scope, or it's returned from the parent scope (if the parent scope is a function).
  • Then, when you call the function outside of the parent scope, you can still access the variables or functions that were defined in the parent scope, even though the parent scope has finished execution.

The following is a typical example of a closure:

js
// The outer function defines a variable called "name"
const pet = function (name) {
  const getName = function () {
    // The inner function has access to the "name" variable of the outer function
    return name;
  };
  return getName; // Return the inner function, thereby exposing it to outer scopes
};
const myPet = pet("Vivie");

console.log(myPet()); // "Vivie"

It can be much more complex than the code above. An object containing methods for manipulating the inner variables of the outer function can be returned.

js
const createPet = function (name) {
  let sex;

  const pet = {
    // setName(newName) is equivalent to setName: function (newName)
    // in this context
    setName(newName) {
      name = newName;
    },

    getName() {
      return name;
    },

    getSex() {
      return sex;
    },

    setSex(newSex) {
      if (
        typeof newSex === "string" &&
        (newSex.toLowerCase() === "male" || newSex.toLowerCase() === "female")
      ) {
        sex = newSex;
      }
    },
  };

  return pet;
};

const pet = createPet("Vivie");
console.log(pet.getName()); // Vivie

pet.setName("Oliver");
pet.setSex("male");
console.log(pet.getSex()); // male
console.log(pet.getName()); // Oliver

In the code above, the name variable of the outer function is accessible to the inner functions, and there is no other way to access the inner variables except through the inner functions. The inner variables of the inner functions act as safe stores for the outer arguments and variables. They hold "persistent" and "encapsulated" data for the inner functions to work with. The functions do not even have to be assigned to a variable, or have a name.

js
const getCode = (function () {
  const apiCode = "0]Eal(eh&2"; // A code we do not want outsiders to be able to modify…

  return function () {
    return apiCode;
  };
})();

console.log(getCode()); // "0]Eal(eh&2"

In the code above, we use the IIFE pattern. Within this IIFE scope, two values exist: a variable apiCode and an unnamed function that gets returned and gets assigned to the variable getCode. apiCode is in the scope of the returned unnamed function but not in the scope of any other part of the program, so there is no way for reading the value of apiCode apart from via the getCode function.

Multiply-nested functions

Functions can be multiply-nested. For example:

  • A function (A) contains a function (B), which itself contains a function (C).
  • Both functions B and C form closures here. So, B can access A, and C can access B.
  • In addition, since C can access B which can access A, C can also access A.

Thus, the closures can contain multiple scopes; they recursively contain the scope of the functions containing it. This is called _scope chaining_. Consider the following example:

js
function A(x) {
  function B(y) {
    function C(z) {
      console.log(x + y + z);
    }
    C(3);
  }
  B(2);
}
A(1); // Logs 6 (which is 1 + 2 + 3)

In this example, C accesses B's y and A's x. This can be done because:

  1. B forms a closure including A (i.e., B can access A's arguments and variables).
  2. C forms a closure including B.
  3. Because C's closure includes B and B's closure includes A, then C's closure also includes A. This means C can access _both_ B _and_ A's arguments and variables. In other words, C _chains_ the scopes of B and A, _in that order_.

The reverse, however, is not true. A cannot access C, because A cannot access any argument or variable of B, which C is a variable of. Thus, C remains private to only B.

Name conflicts

When two arguments or variables in the scopes of a closure have the same name, there is a _name conflict_. More nested scopes take precedence. So, the innermost scope takes the highest precedence, while the outermost scope takes the lowest. This is the scope chain. The first on the chain is the innermost scope, and the last is the outermost scope. Consider the following:

js
function outside() {
  const x = 5;
  function inside(x) {
    return x * 2;
  }
  return inside;
}

console.log(outside()(10)); // 20 (instead of 10)

The name conflict happens at the statement return x * 2 and is between inside's parameter x and outside's variable x. The scope chain here is inside => outside => global object. Therefore, inside's x takes precedences over outside's x, and 20 (inside's x) is returned instead of 10 (outside's x).

Using the arguments object

The arguments of a function are maintained in an array-like object. Within a function, you can address the arguments passed to it as follows:

js
arguments[i];

where i is the ordinal number of the argument, starting at 0. So, the first argument passed to a function would be arguments[0]. The total number of arguments is indicated by arguments.length.

Using the arguments object, you can call a function with more arguments than it is formally declared to accept. This is often useful if you don't know in advance how many arguments will be passed to the function. You can use arguments.length to determine the number of arguments actually passed to the function, and then access each argument using the arguments object.

For example, consider a function that concatenates several strings. The only formal argument for the function is a string that specifies the characters that separate the items to concatenate. The function is defined as follows:

js
function myConcat(separator) {
  let result = ""; // initialize list
  // iterate through arguments
  for (let i = 1; i < arguments.length; i++) {
    result += arguments[i] + separator;
  }
  return result;
}

You can pass any number of arguments to this function, and it concatenates each argument into a string "list":

js
console.log(myConcat(", ", "red", "orange", "blue"));
// "red, orange, blue, "

console.log(myConcat("; ", "elephant", "giraffe", "lion", "cheetah"));
// "elephant; giraffe; lion; cheetah; "

console.log(myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley"));
// "sage. basil. oregano. pepper. parsley. "

توجه: The arguments variable is "array-like", but not an array. It is array-like in that it has a numbered index and a length property. However, it does _not_ possess all of the array-manipulation methods.

See the {{jsxref("Function")}} object in the JavaScript reference for more information.

Function parameters

There are two special kinds of parameter syntax: _default parameters_ and _rest parameters_.

Default parameters

In JavaScript, parameters of functions default to undefined. However, in some situations it might be useful to set a different default value. This is exactly what default parameters do.

In the past, the general strategy for setting defaults was to test parameter values in the body of the function and assign a value if they are undefined.

In the following example, if no value is provided for b, its value would be undefined when evaluating a*b, and a call to multiply would normally have returned NaN. However, this is prevented by the second line in this example:

js
function multiply(a, b) {
  b = typeof b !== "undefined" ? b : 1;
  return a * b;
}

console.log(multiply(5)); // 5

With _default parameters_, a manual check in the function body is no longer necessary. You can put 1 as the default value for b in the function head:

js
function multiply(a, b = 1) {
  return a * b;
}

console.log(multiply(5)); // 5

For more details, see default parameters in the reference.

Rest parameters

The rest parameter syntax allows us to represent an indefinite number of arguments as an array.

In the following example, the function multiply uses _rest parameters_ to collect arguments from the second one to the end. The function then multiplies these by the first argument.

js
function multiply(multiplier, ...theArgs) {
  return theArgs.map((x) => multiplier * x);
}

const arr = multiply(2, 1, 2, 3);
console.log(arr); // [2, 4, 6]

Arrow functions

An arrow function expression (also called a _fat arrow_ to distinguish from a hypothetical -> syntax in future JavaScript) has a shorter syntax compared to function expressions and does not have its own [this](/en-US/docs/Web/JavaScript/Reference/Operators/this), [arguments](/en-US/docs/Web/JavaScript/Reference/Functions/arguments), [super](/en-US/docs/Web/JavaScript/Reference/Operators/super), or [new.target](/en-US/docs/Web/JavaScript/Reference/Operators/new.target). Arrow functions are always anonymous.

Two factors influenced the introduction of arrow functions: _shorter functions_ and _non-binding_ of this.

Shorter functions

In some functional patterns, shorter functions are welcome. Compare:

js
const a = ["Hydrogen", "Helium", "Lithium", "Beryllium"];

const a2 = a.map(function (s) {
  return s.length;
});

console.log(a2); // [8, 6, 7, 9]

const a3 = a.map((s) => s.length);

console.log(a3); // [8, 6, 7, 9]

No separate this

Until arrow functions, every new function defined its own [this](/en-US/docs/Web/JavaScript/Reference/Operators/this) value (a new object in the case of a constructor, undefined in strict mode function calls, the base object if the function is called as an "object method", etc.). This proved to be less than ideal with an object-oriented style of programming.

js
function Person() {
  // The Person() constructor defines `this` as itself.
  this.age = 0;

  setInterval(function growUp() {
    // In nonstrict mode, the growUp() function defines `this`
    // as the global object, which is different from the `this`
    // defined by the Person() constructor.
    this.age++;
  }, 1000);
}

const p = new Person();

In ECMAScript 3/5, this issue was fixed by assigning the value in this to a variable that could be closed over.

js
function Person() {
  // Some choose `that` instead of `self`.
  // Choose one and be consistent.
  const self = this;
  self.age = 0;

  setInterval(function growUp() {
    // The callback refers to the `self` variable of which
    // the value is the expected object.
    self.age++;
  }, 1000);
}

Alternatively, a bound function could be created so that the proper this value would be passed to the growUp() function.

An arrow function does not have its own this; the this value of the enclosing execution context is used. Thus, in the following code, the this within the function that is passed to setInterval has the same value as this in the enclosing function:

js
function Person() {
  this.age = 0;

  setInterval(() => {
    this.age++; // `this` properly refers to the person object
  }, 1000);
}

const p = new Person();

{{PreviousNext("Web/JavaScript/Guide/Loops_and_iteration", "Web/JavaScript/Guide/Expressions_and_operators")}}