Professional Documents
Culture Documents
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>
<ul>
<li>Cookies</li>
<li>Milk</li>
</ul>
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>
> .
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.
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 ( . ).
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 href="#id-of-element-to-link-to">Take
me to a different part of the page</a>
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-->
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>
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>
<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.
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.
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 .
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.
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.
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.
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;
}
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.
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 .
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
.block-two {
margin: 30px;
}
.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. }
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;
}
.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.
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
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';
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.
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
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
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');
}
if Statement
An if statement accepts an expression with a set of
parentheses: const isMailSent = true;
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
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
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.
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. }
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),
console.log(statusMessage);
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.
}
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');
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.
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.
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.
// 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);
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-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}.`)
}
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
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'
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.
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.
console.log(person);
/*
{
firstName: "Matilda"
age: 27
goal: "learning JavaScript"
}
*/
changeItUp(origNum, origObj);
engine.start('noisily');
engine.sputter();
/* Console output:
The engine starts up noisily...
The engine sputters...
*/
console.log(cat.whatName());
// Output: Pipey