You are on page 1of 62

Cheatsheets / Learn HTML

Elements and Structure


<em> Emphasis Element
The <em> emphasis element emphasizes text and
browsers will usually italicize the emphasized text by <p>This <em>word</em> will be emphasized
default. in italics.</p>

HTML
HTML (HyperText Markup Language) is used to give
content to a web page and instructs web browsers on
how to structure that content.

Element Content
The content of an HTML element is the information
between the opening and closing tags of an element. <h1>Codecademy is awesome! 🙂</h1>

<li> List Item Element


The <li> list item element create list items inside:
<ol>
Ordered lists <ol>   <li>Head east on Prince St</li>
Unordered lists <ul>   <li>Turn left on Elizabeth</li>
</ol>

<ul>
  <li>Cookies</li>
  <li>Milk</li>
</ul>

<video> Video Element


The <video> element embeds a media player for video
playback. The src attribute will contain the URL to the <video src="test-video.mp4" controls>
video. Adding the controls attribute will display video   Video not supported
controls in the media player. </video>
Note: The content inside the opening and closing tag is
shown as a fallback in browsers that don’t support the
element.
<ol> Ordered List Element
The <ol> ordered list element creates a list of items in
sequential order. Each list item appears numbered by <ol>
default.   <li>Preheat oven to 325 F 👩‍🍳</li>
  <li>Drop cookie dough 🍪</li>
  <li>Bake for 15 min ⏰</li>
</ol>

<div> Div Element


The <div> element is used as a container that divides
an HTML document into sections and is short for <div>
“division”. <div> elements can contain flow content   <h1>A section of grouped elements</h1>
such as headings, paragraphs, links, images, etc.   <p>Here’s some text for the section</p>
</div>
<div>
  <h1>Second section of grouped
elements</h1>
  <p>Here’s some text</p>
</div>

HTML Structure
HTML is organized into a family tree structure. HTML
elements can have parents, grandparents, siblings, <body>
children, grandchildren, etc.   <div>
    <h1>It's div's child and body's
grandchild</h1>
    <h2>It's h1's sibling</h2>
  </div>
</body>

Closing Tag
An HTML closing tag is used to denote the end of an
HTML element. The syntax for a closing tag is a left <body>
angle bracket < followed by a forward slash / then   ...
the element name and a right angle bracket to close </body>
> .

Attribute Name and Values


HTML attributes consist of a name and a value using the
following syntax: name="value" and can be added to <elementName name="value"></elementName>
the opening tag of an HTML element to configure or
change the behavior of the element.
<br> Line Break Element
The <br> line break element will create a line break in
text and is especially useful where a division of text is A line break haiku.<br>
required, like in a postal address. The line break Poems are a great use case.<br>
element requires only an opening tag and must not Oh joy! A line break.
have a closing tag.

<img> Image Element


HTML image <img> elements embed images in
documents. The src attribute contains the image URL <img src="image.png">
and is mandatory. <img> is an empty element meaning
it should not have a closing tag.

<h1>-<h6> Heading Elements


HTML can use six different levels of heading elements.
The heading elements are ordered from the highest <h1>Breaking News</h1>
level <h1> to the lowest level <h6> . <h2>This is the 1st subheading</h2>
<h3>This is the 2nd subheading</h3>
...
<h6>This is the 5th subheading</h6>

<p> Paragraph Element


The <p> paragraph element contains and displays a
block of text. <p>This is a block of text! Lorem ipsum
dolor sit amet, consectetur adipisicing
elit.</p>

HTML Attributes
HTML attributes are values added to the opening tag of
an element to configure the element or change the <p id="my-paragraph" style="color:
element’s default behavior. In the provided example, we green;">Here’s some text for a paragraph
are giving the <p> (paragraph) element a unique that is being altered by HTML
identifier using the id attribute and changing the attributes</p>
color of the default text using the style attribute.

<ul> Unordered List Element


The <ul> unordered list element is used to create a
list of items in no particular order. Each individual list <ul>
item will have a bullet point by default.   <li>Play more music 🎸</li>
  <li>Read more books 📚</li>
</ul>
alt Attribute
An <img> element can have alternative text via the
alt attribute. The alternative text will be displayed if <img src="path/to/image" alt="text
an image fails to render due to an incorrect URL, if the describing image" />
image format is not supported by the browser, if the
image is blocked from being displayed, or if the image
has not been received from the URL.
The text will be read aloud if screen reading software is
used and helps support visually impaired users by
providing a text descriptor for the image content on a
webpage.

Unique ID Attributes
In HTML, specific and unique id attributes can be
assigned to different elements in order to differentiate <h1 id="A1">Hello World</h1>
between them.
When needed, the id value can be called upon by
CSS and JavaScript to manipulate, format, and perform
specific instructions on that element and that element
only. Valid id attributes should begin with a letter and
should only contain letters ( a-Z ), digits ( 0-9 ),
hyphens ( - ), underscores ( _ ), and periods ( . ).

<body> Body Element


The <body> element represents the content of an
HTML document. Content inside <body> tags are <body>
rendered on the web browsers.   <h1>Learn to code with Codecademy :)
Note: There can be only one <body> element in a </h1>
document. </body>

<span> Span Element


The <span> element is an inline container for text and
can be used to group text for styling purposes. <p><span>This text</span> may be styled
However, as <span> is a generic container to separate differently than the surrounding text.
pieces of text from a larger body of text, its use should </p>
be avoided if a more semantic element is available.

<strong> Strong Element


The <strong> element highlights important, serious, or
urgent text and browsers will normally render this <p>This is <strong>important</strong>
highlighted text in bold by default. text!</p>
HTML Element
An HTML element is a piece of content in an HTML
document and uses the following syntax: opening tag + <p>Hello World!</p>
content + closing tag. In the code provided:

<p> is the opening tag.

Hello World! is the content.

</p> is the closing tag.

HTML Tag
The syntax for a single HTML tag is an opening angle
bracket < followed by the element name and a closing <div>
angle bracket > . Here is an example of an opening
<div> tag.

<a> Anchor Element


The <a> anchor element is used to create hyperlinks
in an HTML document. The hyperlinks can point to <!-- Creating text links -->
other webpages, files on the same server, a location on <a href="http://www.codecademy.com">Visit
the same page, or any other URL via the hyperlink this site</a>
reference attribute, href . The href determines the
location the anchor element points to.
<!-- Creating image links -->
<a href="http://www.codecademy.com">
    <img src="logo.jpg">Click this image
</a>

<head> Head Element


The <head> element contains general information
about an HTML page that isn’t displayed on the page <!DOCTYPE html>
itself. This information is called metadata and includes <html>
things like the title of the HTML document and links to   <head>
stylesheets.     <!-- Metadata is contained in this
element-->
  </head>
</html>

<target> Target Attribute


The target attribute on an <a> anchor element
specifies where a hyperlink should be opened. A <a href="https://www.google.com"
target value of "_blank" will tell the browser to open target="_blank">This anchor element links
the hyperlink in a new tab in modern browsers, or in a to google and will open in a new tab or
new window in older browsers or if the browser has had window.</a>
settings changed to open hyperlinks in a new window.
Indentation
HTML code should be formatted such that the
indentation level of text increases once for each level <div>
of nesting.   <h1>Heading</h1>
It is a common convention to use two or four

space per level of nesting.   <ul>


    <li>Item 1</li>
    <li>Item 2</li>
  </ul>
</div>

Link to a Different Part of the Page #


The anchor element <a> can create hyperlinks to
different parts of the same HTML document using the <div>
href attribute to point to the desired location with #   <p id="id-of-element-to-link-to">A
followed by the id of the element to link to. different part of the page!</p>
</div>

<a href="#id-of-element-to-link-to">Take
me to a different part of the page</a>

<html> HTML Element


The <html> element, the root of an HTML document,
should be added after the !DOCTYPE declaration. All <!DOCTYPE html>
content/structure for an HTML document should be <html>
contained between the opening and closing <html>   <!-- I'm a comment -->
tags. </html>

Comments
In HTML, comments can be added between an opening
<!-- and closing --> . Content inside of comments <!-- Main site content -->
will not be rendered by browsers, and are usually used <div>Content</div>
to describe a part of code or provide other details.
Comments can span single or multiple lines. <!--
  Comments can be
  multiple lines long.
-->
Whitespace
Whitespace, such as line breaks, added to an HTML
document between block-level elements will generally <p>Test paragraph</p>
be ignored by the browser and are not added to
increase spacing on the rendered HTML page. Rather, <!-- The whitespace created by this line,
whitespace is added for organization and easier reading and above/below this line is ignored by
of the HTML document itself.
the browser-->

<p>Another test paragraph, this will sit


right under the first paragraph, no extra
space between.</p>

Document Type Declaration


The document type declaration <!DOCTYPE html> is
required as the first line of an HTML document. The <!DOCTYPE html>
doctype declaration is an instruction to the browser
about what type of document to expect and which
version of HTML is being used, in this case it’s HTML5.

<title> Title Element


The <title> element contains a text that defines the
title of an HTML document. The title is displayed in the <!DOCTYPE html>
browser’s title bar or tab in which the HTML page is <html>
displayed. The <title> element can only be contained   <head>
inside a document’s <head> element.     <title>Title of the HTML page</title>
  </head>
</html>

File Path
URL paths in HTML can be absolute paths, like a full
URL, for example: https://developer.mozilla.org/en- <a
US/docs/Learn or a relative file path that links to a local href="https://developer.mozilla.org/en-
file in the same folder or on the same server, for US/docs/Web">The URL for this anchor
example: ./style.css . Relative file paths begin with element is an absolute file path.</a>
./ followed by a path to the local file. ./ tells the
browser to look for the file path from the current
<a href="./about.html">The URL for this
folder.
anchor element is a relative file path.
</a>
Cheatsheets / Learn HTML

Tables
<td> Table Data Element
The table data element, <td> , can be nested inside a
table row element, <tr> , to add a cell of data to a <table>
table.   <tr>
    <td>cell one data</td>
    <td>cell two data</td>
  </tr>
</table>

<tr> Table Row Element


The table row element, <tr> , is used to add rows to a
table before adding table data and table headings. <table>
  <tr>
    ...
  </tr>
</table>

<thead> Table Head Element


The table head element, <thead> , defines the headings
of table columns encapsulated in table rows. <table>
<thead>
   <tr>
     <th>heading 1</th>
     <th>heading 2</th>
   </tr>
</thead>
<tbody>
   <tr>
     <td>col 1</td>
     <td>col 2</td>
   </tr>
</tbody>
</table>
rowspan Attribute
Similar to colspan , the rowspan attribute on a table
header or table data element indicates how many rows <table>
that particular cell should span within the table. The   <tr>
rowspan value is set to 1 by default and will take any     <th>row 1:</th>
positive integer up to 65534.     <td>col 1</td>
    <td>col 2</td>
  </tr>
  <tr>
    <th rowspan="2">row 2 (this row will
span 2 rows):</th>
    <td>col 1</td>
    <td>col 2</td>
  </tr>
  <tr>
    <td>col 1</td>
    <td>col 2</td>
  </tr>
   <tr>
    <th>row 3:</th>
    <td>col 1</td>
    <td>col 2</td>
  </tr>
</table>

<tbody> Table Body Element


The table body element, <tbody> , is a semantic
element that will contain all table data other than table <table>
heading and table footer content. If used, <tbody> will <tbody>
contain all table row <tr> elements, and indicates that    <tr>
<tr> elements make up the body of the table.
     <td>row 1</td>
<table> cannot have both <tbody> and <tr> as
   </tr>
direct children.
   <tr>
     <td>row 2</td>
   </tr>
   <tr>
     <td>row 3</td>
   </tr>
</tbody>
</table>
colspan Attribute
The colspan attribute on a table header <th> or
table data <td> element indicates how many columns <table>
that particular cell should span within the table. The   <tr>
colspan value is set to 1 by default and will take any     <th>row 1:</th>
positive integer between 1 and 1000.     <td>col 1</td>
    <td>col 2</td>
    <td>col 3</td>
  </tr>
  <tr>
    <th>row 2:</th>
    <td colspan="2">col 1 (will span
2 columns)</td>
    <td>col 2</td>
    <td>col 3</td>
  </tr>
</table>

<tfoot> Table Footer Element


The table footer element, <tfoot> , uses table rows to
give footer content or to summarize content at the end <table>
of a table. <thead>
   <tr>
     <th>heading 1</th>
     <th>heading 2</th>
   </tr>
</thead>
<tbody>
   <tr>
     <td>col 1</td>
     <td>col 2</td>
   </tr>
</tbody>
<tfoot>
   <tr>
     <td>summary of col 1</td>
     <td>summary of col 2</td>
   </tr>
</tfoot>
</table>

<table> Table Element


In HTML, the <table> element has content that is used
to represent a two-dimensional table made of rows and <table>
columns.   <!-- rows and columns will go here -->
</table>
<th> Table Heading Element
The table heading element, <th> , is used to add titles
to rows and columns of a table and must be enclosed in <table>
a table row element, <tr> .   <tr>
    <th>column one</th>
    <th>column two</th>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
  </tr>
</table>
Cheatsheets / Learn HTML

Forms
<input>: Checkbox Type
When using an HTML input element, the
type="checkbox" attribute will render a single checkbox <input type="checkbox" name="breakfast"
item. To create a group of checkboxes related to the value="bacon">Bacon 🥓<br>
same topic, they should all use the same name <input type="checkbox" name="breakfast"
attribute. Since it’s a checkbox, multiple checkboxes
value="eggs">Eggs 🍳<br>
can be selected for the same topic.
<input type="checkbox" name="breakfast"
value="pancakes">Pancakes 🥞<br>

<textarea> Element
The textarea element is used when creating a text-
box for multi-line input (e.g. a comment section). The <textarea rows="10" cols="30"
element supports the rows and cols attributes name="comment"></textarea>
which determine the height and width, respectively, of
the element.
When rendered by the browser, textarea fields can be
stretched/shrunk in size by the user, but the rows and
cols attributes determine the initial size.
Unlike the input element, the <textarea> element
has both opening and closing tags. The value of the
element is the content in between these tags (much like
a <p> element). The code block shows a <textarea>
of size 10x30 and with a name of "comment" .

<form> Element
The HTML <form> element is used to collect and send
information to an external source. <form method="post"
<form> can contain various input elements. When a action="http://server1">
user submits the form, information in these input   Enter your name:
elements is passed to the source which is named in the   <input type="text" name="fname">
action attribute of the form.
  <br/>
  Enter your age:
  <input type="text" name="age">
  <br/>
  <input type="submit" value="Submit">
</form>

<input>: Number Type


HTML input elements can be of type number . These
input fields allow the user to enter only numbers and a <input type="number" name="balance" />
few special characters inside the field.
The example code block shows an input with a type of
number and a name of balance . When the input field
is a part of a form, the form will receive a key-value pair
with the format: name: value after form submission.
<input> Element
The HTML <input> element is used to render a variety
of input fields on a webpage including text fields, <label for="fname">First name:</label>
checkboxes, buttons, etc. <input> element have a <input type="text" name="fname"
type attribute that determines how it gets rendered to id="fname"><br>
a page.
The example code block will create a text input field
<input type="checkbox" name="vehicle"
and a checkbox input field on a webpage.
value="Bike"> I own a bike

<input>: Range Type


A slider can be created by using the type="range"
attribute on an HTML input element. The range slider <input type="range" name="movie-rating"
will act as a selector between a minimum and a min="0" max="10" step="0.1">
maximum value. These values are set using the min
and max attributes respectively. The slider can be
adjusted to move in different steps or increments using
the step attribute.
The range slider is meant to act more as a visual widget
to adjust between 2 values, where the relative position
is important, but the precise value is not as important.
An example of this can be adjusting the volume level of
an application.

<select> Element
The HTML <select> element can be used to create a
dropdown list. A list of choices for the dropdown list <select name="rental-option">
can be created using one or more <option> elements.   <option value="small">Small</option>
By default, only one <option> can be selected at a   <option value="family">Family
time.
Sedan</option>
The value of the selected <select> ’s name and the
  <option value="lux">Luxury</option>
<option> ’ s value attribute are sent as a key-value
</select>
pair when the form is submitted.

Submitting a Form
Once we have collected information in a form we can
send that information somewhere else by using the <form action="/index3.html" method="PUT">
action and method attribute. The action attribute </form>
tells the form to send the information. A URL is assigned
that determines the recipient of the information. The
method attribute tells the form what to do with that
information once it’s sent. An HTTP verb is assigned to
the method attribute that determines the action to be
performed.

<input>: Text Type


HTML <input> elements can support text input by
setting the attribute type="text" . This renders a single <input type="text" name="username">
row input field that users can type text inside.
The value of the <input> ‘s name and value attribute
of the element are sent as a key-value pair when the
form is submitted.
<datalist> Element
When using an HTML input, a basic
search/autocomplete functionality can be achieved by <input list="ide">
pairing an <input> with a <datalist> . To pair a   
<input> with a <datalist> the <input> ’s list value <datalist id="ide">
must match the value of the id of the <datalist> .   <option value="Visual Studio Code" />
The datalist element is used to store a list of
  <option value="Atom" />
<option> s.
  <option value="Sublime Text" />
The list of data is shown as a dropdown on an input
</datalist>
field when a user clicks on the input field. As the user
starts typing, the list will be updated to show elements
that best match what has been typed into the input
field. The actual list items are specified as multiple
option elements nested inside the datalist .
datalist s are ideal when providing users a list of pre-
defined options, but to also allow them to write
alternative inputs as well.

<input>: Radio Button Type


HTML <input> elements can be given a type="radio"
attribute that renders a single radio button. Multiple <input name="delivery_option"
radio buttons of a related topic are given the same type="radio" value="pickup" />
name attribute value. Only a single option can be <input name="delivery_option"
chosen from a group of radio buttons.
type="radio" value="delivery" />
The value of the selected/checked <input> ’s name
and value attribute of this element are sent as a key-
value pair when the form is submitted.

Submittable Input
HTML <input> elements can have a type attribute set
to submit, by adding type="submit" . With this attribute
included, a submit button will be rendered and, by
default, will submit the <form> and execute its action.
The text of a submit button is set to Submit by default
but can also be changed by modifying the value
attribute.

<input> name Attribute


In order for a form to send data, it needs to be able to
put it into key-value pairs. This is achieved by setting <input name="username" id="username" />
the name attribute of the input element. The name <input id="address" />
will become the key and the value of the input will
become the value the form submits corresponding to
the key.
It’s important to remember that the name is not the
same as the ID in terms of form submission. The ID and
the name of the input may be the same, but the value
will only be submitted if the name attribute is specified.
In the code example, the first input will be submitted by
the form, but the second one will not.
<label> Element
The HTML <label> element provides identification for
a specific <input> based on matching values of the <label for="password ">Password:</label>
<input> ‘s id attribute and the <label> ‘s for <input type="text" id="password"
attribute. By default, clicking on the <label> will focus name="password">
the field of the related <input> .
The example code will create a text input field with the
label text “Password: “ next to it. Clicking on “Password:
“ on the page will focus the field for the related
<input> .

<input> Password Type


The HTML <input> element can have the attribute
type="password" that renders a single row input field <input type="text" name="username" />
which allows the user to type censored text inside the <input type="password" name="password" />
field. It is used to type in sensitive information.
The value of this <input> ’s name and value (actual
value and not the censored version) attribute of this
element are sent as a key-value pair when the form is
submitted.
The code block shows an example of the fields for a
basic login form - the username and password fields.

required Attribute
In HTML, input fields have an attribute called required
which specifies that the field must include a value. <input type="password" name="password"
The example code block shows an input field that is required >
required. The attribute can be written as
required="true" or simply required .

max Attribute
HTML <input> s of type number have an attribute
called max that specifies the maximum value for the <input type="number" max="20">
input field.
The code block shows an input number field that is
set to have a maximum value of 20 . Any value larger
than 20 will mark the input field as having an error.

maxlength Attribute
In HTML, input fields with type text have an attribute
called maxlength that specifies the maximum number <input type="text" name="tweet"
of characters that can be entered into the field. The maxlength="140">
code block shows an input text field that accepts text
that has a maximum length of 140 characters.
pattern Attribute
In a text input element, the pattern attribute uses a
regular expression to match against (or validate) the <form action="/action_page.php">
value of the <input> , when the form is submitted.   Country code:
  <input type="text" name="country_code"
         pattern="[A-Za-z]{3}"
         title="Three letter country
code">
  <input type="submit">
</form>

minlength Attribute
In HTML, an input field of type text has an attribute
that supports minimum length validation. To check that <input type="text" name="username"
the input text has a minimum length, add the minlength="6" />
minlength attribute with the character count.
The example code block shows an example of a text
field that has a minimum length of 6 .

HTML Form Validators


HTML forms allow you to specify different kinds of
validation for your input fields to make sure that data is
entered correctly before being submitted. HTML
supports a number of different validators, including
things like minimum value, minimum/maximum length,
etc. The validators are specified as attributes on the
input field.

min Attribute
In HTML, input fields with type number have an
attribute called min that specifies the minimum value <input type="number" name="rating"
that can be entered into the field. The code block min="1" max="10">
provided shows an input number field that accepts a
number with minimum value 1.
Cheatsheets / Learn HTML

Semantic HTML
Semantic HTML
Semantic HTML introduces meaning to the code we
write. Before Semantic HTML the elements didn’t have <!--Non Semantic HTML-->
any meaning as to what it does or what content goes in <div id="footer">
it. An element such as <div> was used as a general- <p>this is a footer</p>
purpose element to create things from headers to
</div>
footers to articles. With Semantic HTML we were
introduced to elements that tell developers and
<!--Semantic HTML-->
browsers exactly what it does and what content should
<footer>
go in it.
<p>this is a footer</p>
</footer>

Element Placement
Semantic HTML introduces elements that can tell
developers exactly what the element does or where it’s
placed based on the name of that element. Some of
these elements are <header> , <nav> , <main> , and
<footer> . <header> describes the content at the top
of the page <body> . It may include a logo, navigational
links or a search bar. <nav> encapsulates the page’s
navigational links. It is often placed inside the <header>
or <footer> . <main> encapsulates the main content of
a page between the header/navigation and the footer
areas. <footer> includes the page’s footer content at
the bottom of the <body> .

Embedding media
Semantic HTML introduces us to <video> , <audio>
and <embed> . <video> allows us to add videos to our <!--Video Tag-->
website. <audio> allows us to implement audio into <video src="4kvideo.mp4">video not
our website. <embed> can be used to implement any supported</video>
type of media. These elements are universal in that
they all use the src attribute to link the source of the
<!--Audio Tag-->
content. <video> and <audio> requires a closing tag
<audio src="koreanhiphop.mp3"></audio>
while <embed> is a self-closing tag.

<!--Embed tag-->
<embed src="babyyoda.gif"/>
<figure> and <figcaption>
The <figure> element is used to encapsulate media
such as an image, diagram. or code snippet. The <figure>
<figcaption> element is used to describe the media <img src="qwerty.jpg">
encapsulated within the <figure> element. Developers <figcaption>The image shows the layout
will normally use <figcaption> within the <figure> of a qwerty keyboard.</figcaption>
element to group the media and description. This way,
</figure>
if a developer decides to change the position of the
media, the description will follow along with it.

<section> and <article>


<section> defines elements in a document, such as
chapters, headings, or any other area of the document <section>
with the same theme. <article> holds content that   <!--defines theme-->
makes sense on its own such as articles, blogs, and   <h2>Top Sports league in America</h2>
comments. Generally developers will use <section> to
<!--writes independent content relating
define a theme for the webpage and use <article> to
to that theme-->
write independent content for that theme. This does
  <article>
not mean that <article> has to be used with
    <p>One of the top sports league is
<section> .
the nba.</p>
  </article>
</section>

<aside> Aside Element


The <aside> element is used to mark additional
information that can enhance another element but isn’t <article>
required in order to understand the main content. <!--Main Content-->
Usually, this information would be in a sidebar or a </article>
location where it doesn’t obstruct the main piece of <aside>
content. An example of this would be an article that
<!--Additional information-->
discusses how to take care of a dog and next to the
</aside>
article an ad would appear advertising a dog grooming
product.
Cheatsheets / Learn CSS

Syntax and Selectors


<link> Link Element
The <link> element is used to link HTML documents
to external resources like CSS files. It commonly uses: <!-- How to link an external stylesheet
with href, rel, and type attributes -->
href attribute to specify the URL to the external
resource
<link
rel attribute to specify the relationship of the href="./path/to/stylesheet/style.css"
linked document to the current document rel="stylesheet" type="text/css">
type attribute to define the type of content
being linked

Purpose of CSS
CSS, or Cascading Style Sheets, is a language that is
used in combination with HTML that customizes how
HTML elements will appear. CSS can define styles and
change the layout and design of a sheet.

Write CSS in Separate Files


CSS code can be written in its own files to keep it
separate from the HTML code. The extension for CSS <head>
files is .css. These can be linked to an HTML file using a   <link href="style.css" type="text/css"
<link> tag in the <head> section. rel="stylesheet">
</head>

Write CSS in HTML File


CSS code can be written in an HTML file by enclosing
the code in <style> tags. Code surrounded by <head>
<style> tags will be interpreted as CSS syntax.   <style>
    h1 {
      color: blue;
    }
  </style>
</head>

Inline Styles
CSS styles can be directly added to HTML elements by
using the style attribute in the element’s opening tag. <h2 style="text-align: center;">Centered
Each style declaration is ended with a semicolon. Styles text</h2>
added in this manner are known as inline styles.

<p style="color: blue; font-size:


18px;">Blue, 18-point text</p>
Separating HTML code from CSS code
It is common practice to separate content code in
HTML files from styling code in CSS files. This can help
make the code easier to maintain, by keeping the syntax
for each file separate, and any changes to the content
or styling can be made in their respective files.

Class and ID Selectors


CSS classes can be reusable and applied to many
elements. Class selectors are denoted with a period . /* Selects all elements with
followed by the class name. CSS ID selectors should be class="column" */
unique and used to style only a single element. ID .column {
selectors are denoted with a hash sign # followed by }
the id name.

/* Selects element with id="first-item"


*/
#first-item {
}

Groups of CSS Selectors


Match multiple selectors to the same CSS rule, using a
comma-separated list. In this example, the text for both h1, h2 {
h1 and h2 is set to red.   color: red;
}

Selector Chaining
CSS selectors define the set of elements to which a
CSS rule set applies. For instance, to select all <p>
elements, the p selector can be used to create style
rules.

Chaining Selectors
CSS selectors can be chained so that rule sets apply
only to elements that match all criteria. For instance, to /* Select h3 elements with the section-
select <h3> elements that also have the section- heading class */
heading class, the selector h3.section-heading can be h3.section-heading {
used.   color: blue;
}

/* Select elements with the section-


heading and button class */
.section-heading.button {
  cursor: pointer;
}
CSS Type Selectors
CSS type selectors are used to match all elements of a
given type or tag name. Unlike for HTML syntax, we do /* Selects all <p> tags */
not include the angle brackets when using type p {
selectors for tag names. When using type selectors, }
elements are matched regardless of their nesting level
in the HTML.

CSS class selectors


The CSS class selector matches elements based on the
contents of their class attribute. For selecting .calendar-cell {
elements having calendar-cell as the value of the   color: #fff;
class attribute, a . needs to be prepended. }

HTML attributes with multiple values


Some HTML attributes can have multiple attribute
values. Multiple attribute values are separated by a <div class="value1 value2 value3"></div>
space between each attribute.

Selector Specificity
Specificity is a ranking system that is used when there
are multiple conflicting property values that point to h1#header {
the same element. When determining which rule to   color: blue;
apply, the selector with the highest specificity wins out. } /* implemented */
The most specific selector type is the ID selector,
followed by class selectors, followed by type selectors.
h1 {
In this example, only color: blue will be implemented
  color: red;
as it has an ID selector whereas color: red has a type
} /* Not implemented */
selector.

CSS ID selectors
The CSS ID selector matches elements based on the
contents of their id attribute. The values of id #job-title {
attribute should be unique in the entire DOM. For   font-weight: bold;
selecting the element having job-title as the value of }
the id attribute, a # needs to be prepended.

CSS descendant selector


The CSS descendant selector combinator is used to
match elements that are descended from another div p { }
matched selector. They are denoted by a single space
between each selector and the descended selector. All section ol li { }
matching elements are selected regardless of the
nesting level in the HTML.
Cheatsheets / Learn CSS

Visual Rules
CSS declarations
In CSS, a declaration is the key-value pair of a CSS
property and its value. CSS declarations are used to set /*
style properties and construct rules to apply to CSS declaration format:
individual or groups of elements. The property name property-name: value;
and value are separated by a colon, and the entire
*/
declaration must be terminated by a semi-colon.

/* CSS declarations */
text-align: center;
color: purple;
width: 100px;

Font Size
The font-size CSS property is used to set text sizes.
Font size values can be many different units or types font-size: 30px;
such as pixels.

Background Color
The background-color CSS property controls the
background color of elements. background-color: blue;

!important Rule
The CSS !important rule is used on declarations to
override any other declarations for a property and #column-one {
ignore selector specificity. !important rules will ensure   width: 200px !important;
that a specific declaration always applies to the }
matched elements. However, generally it is good to
avoid using !important as bad practice.
.post-title {
  color: blue !important;
}

Opacity
The opacity CSS property can be used to control the
transparency of an element. The value of this property opacity: 0.5;
ranges from 0 (transparent) to 1 (opaque).

Font Weight
The font-weight CSS property can be used to set the
weight (boldness) of text. The provided value can be a font-weight: bold;
keyword such as bold or normal .
Text Align
The text-align CSS property can be used to set the
text alignment of inline contents. This property can be text-align: right;
set to these values: left , right , or center .

CSS Rule Sets


A CSS rule set contains one or more selectors and one
or more declarations. The selector(s), which in this h1 {
example is h1 , points to an HTML element. The   color: blue;
declaration(s), which in this example are color: blue   text-align: center;
and text-align: center style the element with a }
property and value. The rule set is the main building
block of a CSS sheet.

Setting foreground text color in CSS


Using the color property, foreground text color of an
element can be set in CSS. The value can be a valid p {
color name supported in CSS like green or blue .   color : #2a2aff ;
Also, 3 digit or 6 digit color code like #22f or #2a2aff }
can be used to set the color.

span {
  color : green ;
}

Resource URLs
In CSS, the url() function is used to wrap resource
URLs. These can be applied to several properties such background-image:
as the background-image . url("../resources/image.png");

Font Family
The font-family CSS property is used to specify the
typeface in a rule set. Fonts must be available to the h2 {
browser to display correctly, either on the computer or   font-family: Verdana;
linked as a web font. If a font value is not available, }
browsers will display their default font. When using a
multi-word font name, it is best practice to wrap them
#page-title {
in quotes.
  font-family: "Courier New";
}
Color Name Keywords
Color name keywords can be used to set color
property values for elements in CSS. h1 {
  color: aqua;
}

li {
  color: khaki;
}

Background Image
The background-image CSS property sets the
background image of an element. An image URL should background-image: url("nyan-cat.gif");
be provided in the syntax url("moon.jpg") as the value
of the property.
Cheatsheets / Learn CSS

The Box Model


CSS Margin Collapse
CSS margin collapse occurs when the top and bottom
margins of blocks are combined into a single margin /* The vertical margins will collapse to
equal to the largest individual block margin. 30 pixels
Margin collapse only occurs with vertical margins, not instead of adding to 50 pixels. */
for horizontal margins.
.block-one {
  margin: 20px;
}

.block-two {
  margin: 30px;
}

CSS auto keyword


The value auto can be used with the property margin
to horizontally center an element within its container. div {
The margin property will take the width of the element   margin: auto;
and will split the rest of the space equally between the }
left and right margins.

Dealing with overflow


If content is too large for its container, the CSS
overflow property will determine how the browser small-block {
handles the problem.   overflow: scroll;
By default, it will be set to visible and the content will }
take up extra space. It can also be set to hidden , or to
scroll , which will make the overflowing content
accessible via scroll bars within the original container.

Height and Width Maximums/Minimums


The CSS min-width and min-height properties can be
used to set a minimum width and minimum height of an /* Any element with class "column" will
element’s box. CSS max-width and max-height be at most 200 pixels wide, despite the
properties can be used to set maximum widths and width property value of 500 pixels. */
heights for element boxes.

.column {
  max-width: 200px;
  width: 500px;
}
The visibility Property
The CSS visibility property is used to render
hidden objects invisible to the user, without removing .invisible-elements {
them from the page. This ensures that the page   visibility: hidden;
structure and organization remain unchanged. }

The property box-sizing of CSS box model


The CSS box model is a box that wraps around an HTML
element and controls the design and layout. The .container {
property box-sizing controls which aspect of the box   box-sizing: border-box;
is determined by the height and width properties. }
The default value of this property is content-box ,
which renders the actual size of the element including
the content box; but not the paddings and borders. The
value border-box , on the other hand, renders the
actual size of an element including the content box,
paddings, and borders.

CSS box-sizing: border-box


The value border-box of the box-sizing property for
an element corresponds directly to the element’s total #box-example {
rendered size, including padding and border with the   box-sizing: border-box;
height and width properties. }
The default value of the border-box property is
content-box . The value border-box is recommended
when it is necessary to resize the padding and border
but not just the content. For instance, the value
border-box calculates an element’s height as follows:
height = content height + padding + border .
Cheatsheets / Learn CSS

Display and Positioning


CSS z-index property
The CSS z-index property specifies how far back or
how far forward an element will appear on a web page //`element1` will overlap `element2`
when it overlaps other elements. .element1 {
The z-index property uses integer values, which can   position: absolute;
be positive or negative values. The element with the
  z-index: 1;
highest z-index value will be at the foreground, while
}
the element with the lowest z-index value will be at
the back.
.element2 {
  position: absolute;
  z-index: -1;
}

Fixed CSS Positioning


Positioning in CSS provides designers and developers
options for positioning HTML elements on a web page. navbar {
The CSS position can be set to static , relative , postion : fixed;
absolute or fixed . When the CSS position has a value }
of fixed , it is set/pinned to a specific spot on a page.
The fixed element stays the same regardless of
scrolling. The navigation bar is a great example of an
element that is often set to position:fixed; , enabling
the user to scroll through the web page and still access
the navigation bar.

CSS display property


The CSS display property determines the type of
render block for an element. The most common values .container1 {
for this property are block , inline , and inline-   display: block;
block . }
Block-level elements take up the full width of their
container with line breaks before and after, and can
.container2 {
have their height and width manually adjusted.
  display: inline;
Inline elements take up as little space as possible, flow
}
horizontally, and cannot have their width or height
manually adjusted.
Inline-block elements can appear next to each other, .container3 {
and can have their width and height manually adjusted.   display: inline-block;
}
CSS position: absolute
The value absolute for the CSS property position
enables an element to ignore sibling elements and .element {
instead be positioned relative to its closest parent   position: absolute;
element that is positioned with relative or absolute . }
The absolute value removes an element entirely from
the document flow. By using the positioning attributes
top , left , bottom and right , an element can be
positioned anywhere as expected.

CSS position: relative


The value relative of the CSS position property
enables an element to be positioned relative to where .element {
it would have originally been on a web page. The offset   position: relative;
properties can be used to determine the actual }
position of the element relative to its original position.
Without the offset properties, this declaration will have
no effect on its positioning, it will act as the default
value static of the position property.

CSS float property


The CSS float property determines how far left or
how far right an element should float within its parent /* The content will float to the left
element. The value left floats an element to the left side of the container. */
side of its container and the value right floats an .left {
element to the right side of its container. For the
  float: left;
property float , the width of the container must be
}
specified or the element will assume the full width of its
containing element.
/* The content will float to the right
side of the container. */
.right {
  float: right;
}
The CSS clear property
The CSS clear property specifies how an element
should behave when it bumps into another element /*This determines that no other elements
within the same containing element.The clear is within the same containing element are
usually used in combination with elements having the allowed to float on the left side of this
CSS float property. This determines on which sides element.*/
floating elements are allowed to float.
.element {
  clear: left;
}

/*This determines that no other elements


within the same containing element are
allowed to float on the right side of
this element.*/
.element {
  clear: right;
}

/*This determines that no elements within


the same containing element are allowed
to float on either side of this
element.*/
.element {
  clear: both;
}

/*This determines that other elements


within the same containing element are
allowed to float on both side of this
element.*/
.element {
  clear: none;
}
Cheatsheets / Learn CSS

Colors
CSS Color Alpha Values
Alpha values determine the transparency of colors in
CSS. Alpha values can be set for both RGB and HSL .midground {
colors by using rgba() and hsla() and providing a   background-color: rgba(0, 255, 0, 0.5);
fourth value representing alpha. Alpha values can range }
between 0.0 (totally transparent) and 1.0 (totally
opaque).
.foreground {
The CSS transparent value can also be used to create
  background-color: hsla(34, 100%, 50%,
a fully transparent element.
0.1);
}

.transparent {
  color: transparent;
}

CSS Hexadecimal Colors


CSS colors can be represented in hexadecimal (or hex)
notation. Hexadecimal digits can represent sixteen .red {
different values using 0 - 9 and a - f .   color: #ff0000;
Hexadecimal colors are composed of 6 characters– }
each group of two represents a value between 0 and
255 for red, green, or blue. For example #ff0000 is all
.short-blue {
red, no green, and no blue.
  color: #00f;
When both characters of all three colors are repeated,
}
hex colors can be abbreviated to only three values, so
#0000ff could also be represented as #00f .

CSS HSL Colors


CSS colors can be declared with the HSL color system
using hsl() syntax. This syntax contains three values: .light-blue {
hue (the color value itself), saturation (intensity), and   background-color: hsl(200, 70%, 50%);
lightness. }
Hue values range from 0 to 360 while saturation and
lightness values are represented as percentages.

CSS rgb() Colors


CSS colors can be declared with RGB colors using
rgb() syntax. .hot-pink {
rgb() should be supplied with three values   color: rgb(249, 2, 171);
representing red, green, and blue. These values range }
can from 0 to 255.

.green {
  color: rgb(0, 255, 0);
}
Color Name Keywords
Color name keywords can be used to set color
property values for elements in CSS. h1 {
  color: aqua;
}

li {
  color: khaki;
}
Cheatsheets / Learn CSS

Typography
CSS font-weight Property
The CSS font-weight property declares how thick or
thin should be the characters of a text. Numerical /* Sets the text as bolder. */
values can be used with this property to set the p {
thickness of the text. The numeric scale range of this   font-weight: 700;
property is from 100 to 900 and accepts only multiples
}
of 100. The default value is normal while the default
numerical value is 400 . Any value less than 400 will
have text appear lighter than the default while any
numerical value greater than the 400 will appear
bolder.
In the given example, all the <p> elements will appear
in a bolder font.

CSS font-style property


The CSS font-style property determines the font
style in which text will appear. .text {
It accepts italic as a value to set the font style to   font-style: italic;
italic. }

CSS @font-face rule


The CSS @font-face rule allows external fonts or font
files to be imported directly into stylesheets.The @font-face {
location of the font file must be specified in the CSS   font-family: 'Glegoo';
rule so that the files can be loaded from that location.   src: url('../fonts/Glegoo-Regular.ttf')
This rule also allows locally hosted fonts to be added format('truetype');
using a relative file path instead of a web URL.
}

CSS Fallback Fonts


The CSS font-family property can have multiple fonts
declared in order of preference. In this case the fonts /* Here `Arial` is the fallback font for
following the initial font are known as the fallback fonts. <p> tags */
If the initial value of the property font-family fails to p {
load to the webpage, the fallback fonts will be used.   font-family: "Helvetica", "Arial";
}
The CSS line-height property
The CSS line-height property declares the vertical
spacing between lines of text.
It accepts both unitless p {
numbers as a ratio (eg. 2 ) and numbers specified by line-height: 10px;
unit as values (eg. 12px ) but it does not accept }
negative numbers.
A unitless number is an absolute
value that will compute the line height as a ratio to the
font size and a unit number can be any valid CSS unit
(eg. pixels, percents, ems, rems, etc.). To set the line-
height of the <p> elements to 10px , the given CSS
declaration can be used.

CSS Linking fonts


Linking fonts allow user to use web fonts in the
document. They can be imported in an HTML <head>
document by using the <link> tag. Once the web font   <link
URL is placed within the href attribute, the imported href="https://fonts.googleapis.com/css?
font can then be used in CSS declaration.
family=Droid%20Serif" rel="stylesheet">
</head>
Cheatsheets / Learn JavaScript

Introduction
JavaScript
JavaScript is a programming language that powers the
dynamic behavior on most websites. Alongside HTML
and CSS, it is a core technology that makes the web
run.

Methods
Methods return information about an object, and are
called by appending an instance with a period . , the // Returns a number between 0 and 1
method name, and parentheses. Math.random();

Libraries
Libraries contain methods that can be called by
appending the library name with a period . , the Math.random();
method name, and a set of parentheses. // ☝️ Math is the library

console.log()
The console.log() method is used to log or print
messages to the console. It can also be used to print console.log('Hi there!');
objects and other info. // Prints: Hi there!

Numbers
Numbers are a primitive data type. They include the set
of all integers and floating point numbers. let amount = 6;
let price = 4.99;

String .length
The .length property of a string returns the number
of characters that make up the string. let message = 'good nite';
console.log(message.length);
// Prints: 9

console.log('howdy'.length);
// Prints: 5
Data Instances
When a new piece of data is introduced into a
JavaScript program, the program keeps track of it in an
instance of that data type. An instance is an individual
case of a data type.

Booleans
Booleans are a primitive data type. They can be either
true or false . let lateToWork = true;

Math.random()
The Math.random() function returns a floating-point,
random number in the range from 0 (inclusive) up to console.log(Math.random());
but not including 1. // Prints: 0 - 0.9

Math.floor()
The Math.floor() function returns the largest integer
less than or equal to the given number. console.log(Math.floor(5.95));
// Prints: 5

Single Line Comments


In JavaScript, single-line comments are created with
two consecutive forward slashes // . // This line will denote a comment

Null
Null is a primitive data type. It represents the
intentional absence of value. In code, it is represented let x = null;
as null .

Strings
Strings are a primitive data type. They are any grouping
of characters (letters, spaces, numbers, or symbols) let single = 'Wheres my bandit hat?';
surrounded by single quotes ' or double quotes " . let double = "Wheres my bandit hat?";
Arithmetic Operators
JavaScript supports arithmetic operators for:
// Addition
+ addition 5 + 5
- subtraction // Subtraction
10 - 5
* multiplication
// Multiplication
/ division
5 * 10
% modulo // Division
10 / 5
// Modulo
10 % 5

Multi-line Comments
In JavaScript, multi-line comments are created by
surrounding the lines with /* at the beginning and */ /*  
at the end. Comments are good ways for a variety of The below configuration must be
reasons like explaining a code block or indicating some changed before deployment.
hints, etc.
*/

let baseUrl
= 'localhost/taxwebapp/country';

Remainder / Modulo Operator


The remainder operator, sometimes called modulo,
returns the number that remains after the right-hand // calculates # of weeks in a year,
number divides into the left-hand number as many rounds down to nearest integer
times as it evenly can. const weeksInYear = Math.floor(365/7);

// calcuates the number of days left over


after 365 is divded by 7
const daysLeftOver = 365 % 7 ;

console.log("A year has " + weeksInYear


+ " weeks and " + daysLeftOver + "
days");
Assignment Operators
An assignment operator assigns a value to its left
operand based on the value of its right operand. Here let number = 100;
are some of them:
// Both statements will add 10
+= addition assignment
number = number + 10;
-= subtraction assignment number += 10;
*= multiplication assignment
console.log(number);
/= division assignment
// Prints: 120

String Interpolation
String interpolation is the process of evaluating string
literals containing one or more placeholders let age = 7;
(expressions, variables, etc).
It can be performed using template literals: text // String concatenation
${expression} text . 'Tommy is ' + age + ' years old.';

// String interpolation
`Tommy is ${age} years old.`;

Variables
Variables are used whenever there’s a need to store a
piece of data. A variable contains data that can be used const currency = '$';
in the program elsewhere. Using variables also ensures let userIncome = 85000;
code re-usability since it can be used to replace the
same value in multiple places.
console.log(currency + userIncome + ' is
more than the average income.');
// Prints: $85000 is more than the
average income.

Undefined
undefined is a primitive JavaScript value that
represents lack of defined value. Variables that are var a;
declared but not initialized to a value will have the value
undefined . console.log(a);
// Prints: undefined
Learn Javascript: Variables
A variable is a container for data that is stored in
computer memory. It is referenced by a descriptive // examples of variables
name that a programmer can call to assign a specific let name = "Tammy";
value and retrieve it. const found = false;
var age = 3;
console.log(name, found, age);
// Tammy, false, 3

Declaring Variables
To declare a variable in JavaScript, any of these three
keywords can be used along with a variable name: var age;
let weight;
var is used in pre-ES6 versions of JavaScript.
const numberOfFingers = 20;
let is the preferred way to declare a variable
when it can be reassigned.

const is the preferred way to declare a variable


with a constant value.

Template Literals
Template literals are strings that allow embedded
expressions, ${expression} . While regular strings use let name = "Codecademy";
single ' or double " quotes, template literals use console.log(`Hello, ${name}`);
backticks instead. // Prints: Hello, Codecademy

console.log(`Billy is ${6+8} years


old.`);
// Prints: Billy is 14 years old.

let Keyword
let creates a local variable in JavaScript & can be re-
assigned. Initialization during the declaration of a let let count;
variable is optional. A let variable will contain console.log(count); // Prints: undefined
undefined if nothing is assigned to it. count = 10;
console.log(count); // Prints: 10

const Keyword
A constant variable can be declared using the keyword
const . It must have an assignment. Any attempt of re- const numberOfColumns = 4;
assigning a const variable will result in JavaScript numberOfColumns = 8;
runtime error. // TypeError: Assignment to constant
variable.
String Concatenation
In JavaScript, multiple strings can be concatenated
together using the + operator. In the example, let service = 'credit card';
multiple strings and variables containing string values let month = 'May 30th';
have been concatenated. After execution of the code let displayText = 'Your ' + service  + '
block, the displayText variable will contain the bill is due on ' +  month + '.';
concatenated string.

console.log(displayText);
// Prints: Your credit card bill is due
on May 30th.
Cheatsheets / Learn JavaScript

Conditionals
Control Flow
Control flow is the order in which statements are
executed in a program. The default control flow is for
statements to be read and executed in order from left-
to-right, top-to-bottom in a program file.
Control structures such as conditionals ( if
statements and the like) alter control flow by only
executing blocks of code if certain conditions are met.
These structures essentially allow a program to make
decisions about which code is executed as the program
runs.

Logical Operator ||
The logical OR operator || checks two values and
returns a boolean. If one or both values are truthy, it true || false;        // true
returns true . If both values are falsy, it returns false . 10 > 5 || 10 > 20;    // true
A B A || B false || false;       // false
10 > 100 || 10 > 20;  // false
false false false

false true true

true false true

true true true

Ternary Operator
The ternary operator allows for a compact syntax in the
case of binary (choosing between two choices) let price = 10.5;
decisions. It accepts a condition followed by a ? let day = "Monday";
operator, and then two expressions separated by a : .
If the condition evaluates to truthy, the first expression day === "Monday" ? price -= 1.5 : price
is executed, otherwise, the second expression is
+= 1.5;
executed.

else Statement
An else block can be added to an if block or series
of if - else if blocks. The else block will be const isTaskCompleted = false;
executed only if the if condition fails.
if (isTaskCompleted) {
  console.log('Task completed');
} else {
  console.log('Task incomplete');
}
Logical Operator &&
The logical AND operator && checks two values and
returns a boolean. If both values are truthy, then it true && true;      // true
returns true . If one, or both, of the values is falsy, then 1 > 2 && 2 > 1;    // false
it returns false . true && false;     // false
4 === 4 && 3 > 1;  // true

switch Statement
The switch statements provide a means of checking
an expression against multiple case clauses. If a case const food = 'salad';
matches, the code inside that clause is executed.
The case clause should finish with a break keyword. switch (food) {
If no case matches but a default clause is included,   case 'oyster':
the code inside default will be executed.
    console.log('The taste of the sea
Note: If break is omitted from the block of a case ,
🦪');
the switch statement will continue to check against
    break;
case values until a break is encountered or the flow is
broken.   case 'pizza':
    console.log('A delicious pie 🍕');
    break;
  default:
    console.log('Enjoy your meal');
}

// Prints: Enjoy your meal

if Statement
An if statement accepts an expression with a set of
parentheses: const isMailSent = true;

If the expression evaluates to a truthy value, then


if (isMailSent) {
the code within its code body executes.
  console.log('Mail sent to recipient');
If the expression evaluates to a falsy value, its }
code body will not execute.

Truthy and Falsy


In JavaScript, values evaluate to true or false when
evaluated as Booleans.

Values that evaluate to true are known as truthy

Values that evaluate to false are known as falsy

Falsy values include false , 0 , empty strings, null


undefined , and NaN . All other values are truthy.
Logical Operator !
The logical NOT operator ! can be used to do one of
the following: let lateToWork = true;
let oppositeValue = !lateToWork;
Invert a Boolean value.

Invert the truthiness of non-Boolean values. console.log(oppositeValue);


// Prints: false

Comparison Operators
Comparison operators are used to comparing two
values and return true or false depending on the 1 > 3       // false
validity of the comparison: 3 > 1       // true
250 >= 250  // true
=== strict equal
1 === 1     // true
!== strict not equal 1 === 2     // false
> greater than 1 === '1'   // false

>= greater than or equal

< less than

<= less than or equal

else if Clause
After an initial if block, else if blocks can each
check an additional condition. An optional else block const size = 10;
can be added after the else if block(s) to run by
default if none of the conditionals evaluated to truthy. if (size > 100) {
  console.log('Big');
} else if (size > 20) {
  console.log('Medium');
} else if (size > 4) {
  console.log('Small');
} else {
  console.log('Tiny');
}
// Print: Small
Cheatsheets / Learn JavaScript

Functions
Arrow Functions (ES6)
Arrow function expressions were introduced in ES6.
These expressions are clean and concise. The syntax // Arrow function with two arguments
for an arrow function expression does not require the const sum = (firstParam, secondParam) =>
function keyword and uses a fat arrow => to { 
separate the parameter(s) from the body.
  return firstParam + secondParam;
There are several variations of arrow functions:
};
Arrow functions with a single parameter do not console.log(sum(2,5)); // Prints: 7 
require () around the parameter list.
// Arrow function with no arguments
Arrow functions with a single expression can use
const printHello = () => { 
the concise function body which returns the
result of the expression without the return   console.log('hello');
keyword. };
printHello(); // Prints: hello

// Arrow functions with a single argument


const checkWeight = weight => { 
  console.log(`Baggage weight : ${weight}
kilograms.`);
};
checkWeight(25); // Prints: Baggage
weight : 25 kilograms.

// Concise arrow functions


const multiply = (a, b) => a * b;
console.log(multiply(2, 30)); // Prints:
60

Functions
Functions are one of the fundamental building blocks in
JavaScript. A function is a reusable set of statements to // Defining the function:
perform a task or calculate a value. Functions can be function sum(num1, num2) {
passed one or more values and can return a value at   return num1 + num2;
the end of their execution. In order to use a function, }
you must define it somewhere in the scope where you
wish to call it.
// Calling the function:
The example code provided contains a function that
sum(3, 6); // 9
takes in 2 values and returns the sum of those numbers.
Anonymous Functions
Anonymous functions in JavaScript do not have a name
property. They can be defined using the function // Named function
keyword, or as an arrow function. See the code function rocketToMars() {
example for the difference between a named function   return 'BOOM!';
and an anonymous function. }

// Anonymous function
const rocketToMars = function() {
  return 'BOOM!';
}

Function Expressions
Function expressions create functions inside an
expression instead of as a function declaration. They const dog = function() {
can be anonymous and/or assigned to a variable.   return 'Woof!';
}

Function Parameters
Inputs to functions are known as parameters when a
function is declared or defined. Parameters are used as // The parameter is name
variables inside the function body. When the function is function sayHello(name) {
called, these parameters will have the value of whatever   return `Hello, ${name}!`;
is passed in as arguments. It is possible to define a
}
function without parameters.

return Keyword
Functions return (pass back) values using the return
keyword. return ends function execution and returns // With return
the specified value to the location where it was called. function sum(num1, num2) {
A common mistake is to forget the return keyword, in   return num1 + num2;
which case the function will return undefined by }
default.

// Without return, so the function


doesn't output the sum
function sum(num1, num2) {
  num1 + num2;
}
Function Declaration
Function declarations are used to create named
functions. These functions can be called using their function add(num1, num2) {
declared name. Function declarations are built from:   return num1 + num2;
}
The function keyword.

The function name.

An optional list of parameters separated by


commas enclosed by a set of parentheses () .

A function body enclosed in a set of curly braces


{} .

Calling Functions
Functions can be called, or executed, elsewhere in
code using parentheses following the function name. // Defining the function
When a function is called, the code inside its function function sum(num1, num2) {
body runs. Arguments are values passed into a function   return num1 + num2;
when it is called. }

// Calling the function


sum(2, 4); // 6
Cheatsheets / Learn JavaScript

Scope
Scope
Scope is a concept that refers to where values and
functions can be accessed. function myFunction() {
Various scopes include:   
  var pizzaName = "Volvo";
Global scope (a value/function in the global
  // Code here can use pizzaName
scope can be used anywhere in the entire
  
program)
}
File or module scope (the value/function can
only be accessed from within the file)
// Code here can't use pizzaName
Function scope (only visible within the function),

Code block scope (only visible within a { ... }


codeblock)

Block Scoped Variables


const and let are block scoped variables, meaning
they are only accessible in their block or nested blocks. const isLoggedIn = true;
In the given code block, trying to print the
statusMessage using the console.log() method will if (isLoggedIn == true) {
result in a ReferenceError . It is accessible only inside   const statusMessage = 'User is logged
that if block.
in.';
}

console.log(statusMessage);

// Uncaught ReferenceError: statusMessage


is not defined

Global Variables
JavaScript variables that are declared outside of blocks
or functions can exist in the global scope, which means // Variable declared globally
they are accessible throughout a program. Variables const color = 'blue';
declared outside of smaller block or function scopes
are accessible inside those smaller scopes. function printColor() {
Note: It is best practice to keep global variables to a
  console.log(color);
minimum.
}

printColor(); // Prints: blue


Cheatsheets / Learn JavaScript

Arrays
Property .length
The .length property of a JavaScript array indicates
the number of elements the array contains. const numbers = [1, 2, 3, 4];

numbers.length // 4

Index
Array elements are arranged by index values, starting at
0 as the first element index. Elements can be // Accessing an array element
accessed by their index using the array name, and the const myArray = [100, 200, 300];
index surrounded by square brackets.

console.log(myArray[0]); // 100
console.log(myArray[1]); // 200
console.log(myArray[2]); // 300

Method .push()
The .push() method of JavaScript arrays can be used
to add one or more elements to the end of an array. // Adding a single element:
.push() mutates the original array returns the new const cart = ['apple', 'orange'];
length of the array. cart.push('pear');

// Adding multiple elements:


const numbers = [1, 2];
numbers.push(3, 4, 5);

Method .pop()
The .pop() method removes the last element from an
array and returns that element. const ingredients = ['eggs', 'flour',
'chocolate'];

const poppedIngredient
= ingredients.pop(); // 'chocolate'
console.log(ingredients); // ['eggs',
'flour']
Mutable
JavaScript arrays are mutable, meaning that the values
they contain can be changed. const names = ['Alice', 'Bob'];
Even if they are declared using const , the contents
can be manipulated by reassigning internal values or names.push('Carl');
using methods like .push() and .pop() . // ['Alice', 'Bob', 'Carl']

Arrays
Arrays are lists of ordered, stored data. They can hold
items that are of any data type. Arrays are created by // An array containing numbers
using square brackets, with individual elements const numberArray = [0, 1, 2, 3];
separated by commas.

// An array containing different data


types
const mixedArray = [1, 'chicken', false];
Cheatsheets / Learn JavaScript

Loops
While Loop
The while loop creates a loop that is executed as long
as a specified condition evaluates to true . The loop while (condition) {
will continue to run until the condition evaluates to   // code block to be executed
false . The condition is specified before the loop, and }
usually, some variable is incremented or altered in the
while loop body to determine when the loop should
let i = 0;
stop.

while (i < 5) {        


  console.log(i);
  i++;
}

Reverse Loop
A for loop can iterate “in reverse” by initializing the
loop variable to the starting value, testing for when the const items = ['apricot', 'banana',
variable hits the ending value, and decrementing 'cherry'];
(subtracting from) the loop variable at each iteration.

for (let i = items.length - 1; i >= 0; i


-= 1) {
  console.log(`${i}. ${items[i]}`);
}

// Prints: 2. cherry
// Prints: 1. banana
// Prints: 0. apricot

Do…While Statement
A do...while statement creates a loop that executes a
block of code once, checks if a condition is true, and x = 0
then repeats the loop as long as the condition is true. i = 0
They are used when you want the code to always
execute at least once. The loop ends when the
do {
condition evaluates to false.
  x = x + i;
  console.log(x)
  i++;
} while (i < 5);

// Prints: 0 1 3 6 10


For Loop
A for loop declares looping instructions, with three
important pieces of information separated by for (let i = 0; i < 4; i += 1) {
semicolons ; :   console.log(i);
};
The initialization defines where to begin the loop
by declaring (or referencing) the iterator variable
// Output: 0, 1, 2, 3
The stopping condition determines when to stop
looping (when the expression evaluates to
false )

The iteration statement updates the iterator


each time the loop is completed

Looping Through Arrays


An array’s length can be evaluated with the .length
property. This is extremely helpful for looping through for (let i = 0; i < array.length; i++){
arrays, as the .length of the array can be used as the   console.log(array[i]);
stopping condition in the loop. }

// Output: Every item in the array

Break Keyword
Within a loop, the break keyword may be used to exit
the loop immediately, continuing execution after the for (let i = 0; i < 99; i += 1) {
loop body.   if (i > 5) {
Here, the break keyword is used to exit the loop when      break;
i is greater than 5.   }
  console.log(i)
}

// Output: 0 1 2 3 4 5


Nested For Loop
A nested for loop is when a for loop runs inside
another for loop. for (let outer = 0; outer < 2; outer +=
The inner loop will run all its iterations for each 1) {
iteration of the outer loop.   for (let inner = 0; inner < 3; inner +=
1) {
    console.log(`${outer}-${inner}`);
  }
}

/*
Output:
0-0
0-1
0-2
1-0
1-1
1-2
*/

Loops
A loop is a programming tool that is used to repeat a set
of instructions. Iterate is a generic term that means “to
repeat” in the context of loops. A loop will continue to
iterate until a specified condition, commonly known as
a stopping condition, is met.
Cheatsheets / Learn JavaScript

Iterators
Functions Assigned to Variables
In JavaScript, functions are a data type just as strings,
numbers, and arrays are data types. Therefore, let plusFive = (number) => {
functions can be assigned as values to variables, but are   return number + 5;  
different from all other data types because they can be };
invoked.
// f is assigned the value of plusFive
let f = plusFive;

plusFive(3); // 8
// Since f has a function value, it can
be invoked.
f(9); // 14

Callback Functions
In JavaScript, a callback function is a function that is
passed into another function as an argument. This const isEven = (n) => {
function can then be invoked during the execution of   return n % 2 == 0;
that higher order function (that it is an argument of). }
Since, in JavaScript, functions are objects, functions
can be passed as arguments.
let printMsg = (evenFunc, num) => {
  const isNumEven = evenFunc(num);
  console.log(`The number ${num} is an
even number: ${isNumEven}.`)
}

// Pass in isEven as the callback


function
printMsg(isEven, 4);
// Prints: The number 4 is an even
number: True.

Higher-Order Functions
In Javascript, functions can be assigned to variables in
the same way that strings or arrays can. They can be
passed into other functions as parameters or returned
from them as well.
A “higher-order function” is a function that accepts
functions as parameters and/or returns a function.
Array Method .reduce()
The .reduce() method iterates through an array and
returns a single value. const arrayOfNumbers = [1, 2, 3, 4];
It takes a callback function with two parameters
(accumulator, currentValue) as arguments. On each const sum
iteration, accumulator is the value returned by the last = arrayOfNumbers.reduce((accumulator,
iteration, and the currentValue is the current element.
currentValue) => {  
Optionally, a second argument can be passed which
  return accumulator + currentValue;
acts as the initial value of the accumulator.
});
Here, the .reduce() method will sum all the elements
of the array.
console.log(sum); // 10

Array Method .forEach()


The .forEach() method executes a callback function
on each of the elements in an array in order. const numbers = [28, 77, 45, 99, 27];
Here, the callback function containing a console.log()
method will be executed 5 times, once for each numbers.forEach(number => {  
element.   console.log(number);
});

Array Method .filter()


The .filter() method executes a callback function on
each element in an array. The callback function for const randomNumbers = [4, 11, 42, 14,
each of the elements must return either true or 39];
false . The returned array is a new array with any const filteredArray
elements for which the callback function returns true . = randomNumbers.filter(n => {  
Here, the array filteredArray will contain all the
  return n > 5;
elements of randomNumbers but 4 .
});

Array Method .map()


The .map() method executes a callback function on
each element in an array. It returns a new array made const finalParticipants = ['Taylor',
up of the return values from the callback function. 'Donald', 'Don', 'Natasha', 'Bobby'];
The original array does not get altered, and the
returned array may contain different elements than the
const announcements
original array.
= finalParticipants.map(member => {
  return member + ' joined the contest.';
})

console.log(announcements);
Cheatsheets / Learn JavaScript

Objects
Dot Notation for Accessing Object Properties
Properties of a JavaScript object can be accessed
using the dot notation in this manner: const apple = {
object.propertyName . Nested properties of an object   color: 'Green',
can be accessed by chaining key names in the correct   price: {
order.
    bulk: '$3/kg',
    smallQty: '$4/kg'
  }
};
console.log(apple.color); // 'Green'
console.log(apple.price.bulk); // '$3/kg'

Restrictions in Naming Properties


JavaScript object key names must adhere to some
restrictions to be valid. Key names must either be // Example of invalid key names
strings or valid identifier or variable names (i.e. special const trainSchedule = {
characters such as - are not allowed in key names   platform num: 10, // Invalid because of
that are not strings). the space between words.
  40 - 10 + 2: 30, // Expressions cannot
be keys.
  +compartment: 'C' // The use of a +
sign is invalid unless it is enclosed in
quotations.
}

Objects
An object is a built-in data type for storing key-value
pairs. Data inside objects are unordered, and the values
can be of any type.

Accessing non-existent JavaScript properties


When trying to access a JavaScript object property
that has not been defined yet, the value of undefined const classElection = {
will be returned by default.   date: 'January 12'
};

console.log(classElection.place); //
undefined
JavaScript Objects are Mutable
JavaScript objects are mutable, meaning their contents
can be changed, even when they are declared as const student = {
const . New properties can be added, and existing   name: 'Sheldon',
property values can be changed or deleted.   score: 100,
It is the reference to the object, bound to the variable,   grade: 'A',
that cannot be changed.
}

console.log(student)
// { name: 'Sheldon', score: 100, grade:
'A' }

delete student.score
student.grade = 'F'
console.log(student)
// { name: 'Sheldon', grade: 'F' }

student = {}
// TypeError: Assignment to constant
variable.

JavaScript for...in loop


The JavaScript for...in loop can be used to iterate
over the keys of an object. In each iteration, one of the let mobile = {
properties from the object is assigned to the variable of   brand: 'Samsung',
that loop.   model: 'Galaxy Note 9'
};

for (let key in mobile) {


  console.log(`${key}: ${mobile[key]}`);
}

Properties and values of a JavaScript object


A JavaScript object literal is enclosed with curly braces
{} . Values are mapped to keys in the object with a const classOf2018 = {
colon ( : ), and the key-value pairs are separated by   students: 38,
commas. All the keys are unique, but values are not.   year: 2018
Key-value pairs of an object are also referred to as }
properties.
Delete operator
Once an object is created in JavaScript, it is possible to
remove properties from the object using the delete const person = {
operator. The delete keyword deletes both the value   firstName: "Matilda",
of the property and the property itself from the object.   age: 27,
The delete operator only works on properties, not on   hobby: "knitting",
variables or functions.
  goal: "learning JavaScript"
};

delete person.hobby; // or delete


person[hobby];

console.log(person);
/*
{
  firstName: "Matilda"
  age: 27
  goal: "learning JavaScript"
}
*/
    

javascript passing objects as arguments


When JavaScript objects are passed as arguments to
functions or methods, they are passed by reference, const origNum = 8;
not by value. This means that the object itself (not a const origObj = {color: 'blue'};
copy) is accessible and mutable (can be changed) inside
that function.
const changeItUp = (num, obj) => {
  num = 7;
  obj.color = 'red';
};

changeItUp(origNum, origObj);

// Will output 8 since integers are


passed by value.
console.log(origNum);

// Will output 'red' since objects are


passed
// by reference and are therefore
mutable.
console.log(origObj.color);
JavaScript Object Methods
JavaScript objects may have property values that are
functions. These are referred to as object methods. const engine = {
Methods may be defined using anonymous arrow   // method shorthand, with one argument
function expressions, or with shorthand method syntax.   start(adverb) {
Object methods are invoked with the syntax:
    console.log(`The engine starts up
objectName.methodName(arguments) .
${adverb}...`);
  },  
  // anonymous arrow function expression
with no arguments
  sputter: () => {
    console.log('The engine
sputters...');
  },
};

engine.start('noisily');
engine.sputter();

/* Console output:
The engine starts up noisily...
The engine sputters...
*/

JavaScript destructuring assignment shorthand syntax


The JavaScript destructuring assignment is a shorthand
syntax that allows object properties to be extracted const rubiksCubeFacts = {
into specific variable values.   possiblePermutations:
It uses a pair of curly braces ( {} ) with property names '43,252,003,274,489,856,000',
on the left-hand side of an assignment to extract values   invented: '1974',
from objects. The number of variables can be less than
  largestCube: '17x17x17'
the total properties of an object.
};
const {possiblePermutations, invented,
largestCube} = rubiksCubeFacts;
console.log(possiblePermutations); //
'43,252,003,274,489,856,000'
console.log(invented); // '1974'
console.log(largestCube); // '17x17x17'

shorthand property name syntax for object creation


The shorthand property name syntax in JavaScript
allows creating objects without explicitly specifying the const activity = 'Surfing';
property names (ie. explicitly declaring the value after const beach = { activity };
the key). In this process, an object is created where the console.log(beach); // { activity:
property names of that object match variables which
'Surfing' }
already exist in that context. Shorthand property names
populate an object with a key matching the identifier
and a value matching the identifier’s value.
this Keyword
The reserved keyword this refers to a method’s
calling object, and it can be used to access properties const cat = {
belonging to that object.   name: 'Pipey',
Here, using the this keyword inside the object   age: 8,
function to refer to the cat object and access its   whatName() {
name property.
    return this.name  
  }
};

console.log(cat.whatName());
// Output: Pipey

javascript function this


Every JavaScript function or method has a this
context. For a function defined inside of an object, const restaurant = {
this will refer to that object itself. For a function   numCustomers: 45,
defined outside of an object, this will refer to the   seatCapacity: 100,
global object ( window in a browser, global in Node.js).   availableSeats() {
    // this refers to the restaurant
object
    // and it's used to access its
properties
    return this.seatCapacity
- this.numCustomers;
  }
}

JavaScript Arrow Function this Scope


JavaScript arrow functions do not have their own this
context, but use the this of the surrounding lexical const myObj = {
context. Thus, they are generally a poor choice for     data: 'abc',
writing object methods.     loggerA: () =>
Consider the example code: { console.log(this.data); },
loggerA is a property that uses arrow notation to
    loggerB() { console.log(this.data);
define the function. Since data does not exist in the
},
global context, accessing this.data returns
};
undefined .
loggerB uses method syntax. Since this refers to the
enclosing object, the value of the data property is myObj.loggerA();    // undefined
accessed as expected, returning "abc" . myObj.loggerB();    // 'abc'
getters and setters intercept property access
JavaScript getter and setter methods are helpful in part
because they offer a way to intercept property access const myCat = {
and assignment, and allow for additional actions to be   _name: 'Snickers',
performed before these changes go into effect.   get name(){
    return this._name
  },
  set name(newName){
    //Verify that newName is a non-empty
string before setting as name property
    if (typeof newName === 'string' &&
newName.length > 0){
      this._name = newName;
    } else {
      console.log("ERROR: name must be
a non-empty string");
    }
  }
}

javascript factory functions


A JavaScript function that returns an object is known as
a factory function. Factory functions often accept // A factory function that accepts
parameters in order to customize the returned object. 'name',
// 'age', and 'breed' parameters to
return
// a customized dog object.
const dogFactory = (name, age, breed) =>
{
  return {
    name: name,
    age: age,
    breed: breed,
    bark() {
      console.log('Woof!');  
    }
  };
};
javascript getters and setters restricted
JavaScript object properties are not private or
protected. Since JavaScript objects are passed by const myCat = {
reference, there is no way to fully prevent incorrect   _name: 'Dottie',
interactions with object properties.   get name() {
One way to implement more restricted interactions     return this._name;  
with object properties is to use getter and setter
  },
methods.
  set name(newName) {
Typically, the internal value is stored as a property with
    this._name = newName;  
an identifier that matches the getter and setter method
names, but begins with an underscore ( _ ).   }
};

// Reference invokes the getter


console.log(myCat.name);

// Assignment invokes the setter


myCat.name = 'Yankee';

You might also like