0% found this document useful (0 votes)
14 views

Javascript Codecademy

The document provides a comprehensive guide on building interactive JavaScript websites, detailing the use of HTML script elements, DOM manipulation methods, event handling, and templating with Handlebars. Key concepts include attributes like src, defer, and async for script loading, methods such as .removeChild(), .createElement(), and event handling with .addEventListener(). Additionally, it covers Handlebars.js for creating reusable templates in web development.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Javascript Codecademy

The document provides a comprehensive guide on building interactive JavaScript websites, detailing the use of HTML script elements, DOM manipulation methods, event handling, and templating with Handlebars. Key concepts include attributes like src, defer, and async for script loading, methods such as .removeChild(), .createElement(), and event handling with .addEventListener(). Additionally, it covers Handlebars.js for creating reusable templates in web development.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

Cheatsheets / Building Interactive JavaScript Websites

JavaScript Interactive Websites

HTML script element src attribute

The src attribute of a <script> element is used <!-- Using a relative path -->
to point to the location of a script file.
<script src="./script.js"></script>
The file referenced can be local (using a relative path) or
hosted elsewhere (using an absolute path).
<!-- Using an absolute path -->
<script
src="https://code.jquery.com/jquery-
3.3.1.min.js"></script>

HTML script element defer attribute

The defer attribute of a <script> tag is a <body>


boolean attribute used to indicate that the script can be
<script src="main.js" defer></script>
loaded but not executed until after the HTML document
is fully parsed. It will only work for externally linked scripts <h1>Hello</h1>
(with a src attribute), and will have no effect if it is </body>
applied to an inline script.
In the example code block, the <h1> tag will be loaded
and parsed before the script is executed due to the
defer attribute.

HTML script tag async attribute

Scripts are loaded synchronously as they appear in an <body>


HTML file, before the following HTML is loaded and
<script src="main.js" async></script>
parsed. The async attribute can be used to load the
scripts asynchronously, such that they will load in the <h1>Hello world!</h1>
background without blocking the HTML parser from </body>
continuing.
In the example code block, the script will load
asynchronously in the background, without blocking the
HTML parser.
HTML script element

The HTML <script> element can contain or <script>


reference JavaScript code in an HTML file. The
console.log("Hello world!");
<script> element needs both an opening and a
closing tag, and JavaScript code can be embedded </script>
between the tags.

The removeChild() Method

The .removeChild() method removes a specified const groceryList =


child from a parent element. We can use this method by
document.getElementById('groceryList');
calling .removeChild() on the parent node whose
child we want to remove, and passing in the child node as const iceCream =
the argument. document.getElementById('iceCream');
In the example code block, we are removing
iceCream from our groceryList element.
groceryList.removeChild(iceCream);

The element.parentNode Property

The .parentNode property of an element can be <div id="parent">


used to return a reference to its direct parent node.
<p id ="first-child">Some child text</p>
.parentNode can be used on any node.
In the code block above, we are calling on the <p id ="second-child">Some more child
parentNode of the #first-child element to text</p>
get a reference to the #parent div element. </div>
<script>
const firstChild =
document.getElementById('first-child');
firstChild.parentNode; // reference to
the #parent div
</script>
The document.createElement() Method

The document.createElement() method const newButton =


creates and returns a reference to a new Element Node
document.createElement("button");
with the specified tag name.
document.createElement() does not actually
add the new element to the DOM, it must be attached
with a method such as
element.appendChild() .

The element.InnerHTML Property

The element.innerHTML property can be used to <box>


access the HTML markup that makes up an element’s
<p>Hello there!</p>
contents.
element.innerHTML can be used to access the </box>
current value of an element’s contents or to reassign it.
In the code block above, we are reassigning the box
<script>
element’s inner HTML to a paragraph element with the
text “Goodbye”. const box =
document.querySelector('box');
// Outputs '<p>Hello there!</p>':
console.log(box.innerHTML)
// Reassigns the value:
box.innerHTML = '<p>Goodbye</p>'
</script>

The document Object

The document object provides a Javascript interface const body = document.body;


to access the DOM. It can be used for a variety of
purposes including referencing the <body> element,
referencing a specific element with ID, creating new HTML
elements, etc.
The given code block can be used to obtain the reference
to the <body> element using the document
object.
The document.getElementById() Method

The document.getElementById() method // Save a reference to the element with id


returns the element that has the id attribute with the
'demo':
specified value.
document.getElementById() returns null const demoElement =
if no elements with the specified ID exists. document.getElementById('demo');
An ID should be unique within a page. However, if more
than one element with the specified ID exists, the
.getElementById() method returns the first
element in the source code.

The .querySelector() Method

The .querySelector() method selects the first // Select the first <div>
child/descendant element that matches its selector
const firstDiv =
argument.
It can be invoked on the document object to search document.querySelector('div');
the entire document or on a single element instance to
search that element’s descendants.
// Select the first .button element inside
In the above code block, we are using
.querySelector() to select the first div .main-navigation
element on the page, and to select the first element with const navMenu =
a class of button , inside the .main- document.getElementById('main-
navigation element.
navigation');
const firstButtonChild =
navMenu.querySelector('.button');

The document.body Object

document.body returns a reference to the


contents of the <body> HTML element of a
document/HTML page. The <body> element contains
all the visible contents of the page.
The element.onclick Property

The element.onclick property can be used to let element =


set a function to run when an element is clicked. For
document.getElementById('addItem');
instance, the given code block will add an <li>
element each time the element with ID addItem is element.onclick = function() {
clicked by the user. let newElement =
document.createElement('li');

document.getElementById('list').appendChil
d(newElement);
};

The element.appendChild() Method

The element.appendChild() method appends var node1 = document.createElement('li');


an element as the last child of the parent.
document.getElementById('list').appendChil
In the given code block, a newly created <li> element
will be appended as the last child of the HTML element d(node1);
with the ID list .

The element.style Property

The element.style property can be used to let blueElement =


access or set the CSS style rules of an element. To do so,
document.getElementById('colorful-
values are assigned to the attributes of
element.style . element');
In the example code, blueElement contains the blueElement.style.backgroundColor =
HTML element with the ID colorful-element . By
'blue';
setting the backgroundColor attribute of the
style property to blue, the CSS property
background-color becomes blue.
Also note that, if the CSS property contains a hyphen,
such as font-family or background-
color , Camel Case notation is used in Javascript for
the attribute name, so background-color
becomes backgroundColor .
Nodes in DOM tree

A node in the DOM tree is the intersection of two


branches containing data. Nodes can represent HTML
elements, text, attributes, etc. The root node is the top-
most node of the tree. The illustration shows a
representation of a DOM containing different types of
nodes.

HTML DOM

The DOM is an interface between scripting languages and


a web page’s structure. The browser creates a Document
Object Model or DOM for each webpage it renders. The
DOM allows scripting languages to access and modify a
web page. With the help of DOM, JavaScript has the
ability to create dynamic HTML.

Accessing HTML attributes in DOM

The DOM nodes of type Element allow access to the same <h1 id="heading">Welcome!</h1>
attributes available to HTML elements. For instance, for
the given HTML element, the id attribute will be
accessible through the DOM.
The Document Object Model

The Document Object Model, or DOM is a representation


of a document (like an HTML page) as a group of objects.
While it is often used to represent HTML documents, and
most web browsers use JavaScript interfaces to the DOM,
it is language agnostic as a model.
The DOM is tree-like and heirarchical, meaning that there
is a single top-level object, and other objects descend
from it in a branching structure.

The DOM Parent-Child Relationship

The parent-child relationship observed in the DOM is <body>


reflected in the HTML nesting syntax.
<p>first child</p>
Elements that are nested inside the opening and closing
tag of another element are the children of that element <p>second child</p>
in the DOM. </body>
In the code block, the two <p> tags are children of the
<body> , and the <body> is the parent of both
<p> tags.

Print Share
Cheatsheets / Building Interactive JavaScript Websites

DOM Events with JavaScript

.addEventListener()

The .addEventListener() method attaches an eventTarget.addEventListener("event",


event handler to a specific event on an event target. The
eventHandlerFunction);
advantage of this is that you can add many events to the
event target without overwriting existing events. Two
arguments are passed to this method: an event name as a
string, and the event handler function. Here is the syntax:

.removeEventListener()

We can tell our code to listen for an event to fire using the eventTarget.addEventListener("event",
.addEventListener() method. To tell the code
eventHandlerFunction);
to stop listening for that event to fire, we can use the
.removeEventListener() method. This
method takes the same two arguments that were passed eventTarget.removeEventListener("event",
to .addEventListener() , the event name as a
eventHandlerFunction);
string and the event handler function. See their
similarities in syntax:

Event handler

When an event fires in JavaScript (such as a keystroke or


mouse movement), an event handler runs in response.
Each event handler is registered to an element,
connecting the handler to both an element and a type of
event (keystroke, eg.). A method called an event listener
“listens” for an event to occur, specifies what should
happen as a response, and calls the event handler.
Event object

Event handler functions are passed an argument called an


event object, which holds information about the event
that was fired.
Event objects store information about the event target,
the event type, and associated listeners in properties and
methods. For example, if we wanted to know which key
was pressed, the event object would store that
information.

Keyboard events

Keyboard events describe a user interaction with the


keyboard. Each event describes a separate interaction
with a key on the keyboard by the user, which are then
stored with the .key property.
keydown events are fired when the key is first
pressed.
keyup events are fired when the key is
released.
keypress events are fired when the user
presses a key that produces a character value (aka
is not a modifier key such as CapsLock).

javascript event

On a webpage, a trigger such as a user interaction or // An event is triggered when a user


browser manipulation can cause a client-side JavaScript
clicks on the #button element,
event to be created. Events can be used to manipulate
the DOM by executing a JavaScript function. // which then sets the #button element's
Events can include anything from a click to hovering a background-color to blue.
mouse over an element to a webpage loading or being
$('#button').on('click', event => {
refreshed. Events are defined as a part of the JavaScript
API built into the web browser. $(event.currentTarget).css('background-
color', 'blue');
});
JS Event Handlers

The goal of JavaScript is to make a page dynamic, which //Assuming there is an element with
frequently means responding to certain events (for
ID='test' on the page
example, button clicks, user scrolls, etc). DOM elements
can have functions hook onto events. The functions are
called event handlers and the DOM element is known as document.getElementById('test').onclick =
an event target.
function(e) {
The example code block shows how to register a function
as an event handler. The property name for event alert('Element clicked!');
handlers starts with ‘on’ with the event appended };
afterwards. Examples: onload , onclick ,
onfocus , onscroll .

Mouse events

A mouse event fires when a user interacts with the


mouse, either by clicking or moving the mouse device.
click events are fired when the user presses
and releases a mouse button on an element.
mouseout events are fired when the mouse
leaves an element.
mouseover events are fired when the mouse
enters an element’s content.
mousedown events are fired when the user
presses a mouse button.
mouseup events are fired when the user
releases the mouse button.

Print Share
Cheatsheets / Building Interactive JavaScript Websites

Templating With Handlebars

Handlebars.compile()

Handlebar.compile() can be used to produce const template = '<span>{{greetingMsg}}


a templating function. A template string with expressions
</span>';
must be passed into Handlebar.compile() .
That function then takes an object as an argument, const templateFunction =
interpolates the object’s values into the template Handlebars.compile(template);
expressions, and returns a completed HTML string.
const html = templateFunction({
greetingMsg: 'Greetings from the club!'
});
console.log(html); // <span>Greetings from
the club!</span>
Handlebars {{each}} block helper

Handlebars {{each}} block helper is a built-in const template = `<ul>


helper expression that can accept an array to iterate
{{#each serialList}}
through. Inside an {{each}} block, this serves as
a placeholder for the current iteration value. <li>{{this}}</li>
{{/each}}
</ul>`;

const templateFunction =
Handlebars.compile(template);
const htmlStr = templateFunction({
serialList: [202, 204, 338, 342, 400] });
console.log(completedHtml);
/* Output:
<ul>
<li>202</li>
<li>204</li>
<li>338</li>
<li>342</li>
<li>400</li>
</ul>
*/

Handlebars block helpers

Handlebars comes with built-in block helpers which allow {{#blockName}}


us to embed HTML or other expressions in between
Block text content
helper expression tags.
The starting expression of the block helper will have a # <p>An HTML paragraph element</p>
that appears before a keyword, and the ending expression {{/blockName}}
will have a / followed by the same keyword to denote
the end.
The Handlebars.js JavaScript Library

Handlebars.js is a Javascript library used to create <script id="spaceCraft" type="text/x-


reusable webpage templates. The templates are
handlebars-template">
combination of HTML, text, and expressions. The
expressions are included in the html document and <p>{{spacecraftName}} landed the
surrounded by double curly braces. first human on the Moon.</p>
These expressions are placeholders for content to be
</script>
inserted by our Handlebars.js code in our js document.
When the compiled templated function is called, values
are substituted into the expressions.

Handlebars.js and the <script> Element

An HTML <script> element with type value of <script id="handlebars-template"


text/x-handelbars-template can be used
type="text/x-handlebars-template">
to contain Handlebars.js template text and expressions.
This allows writing Handlebars.js templates in an HTML <p>Hello {{loggedInUser}}</p>
document. </script>

Handlebars {{if}} block helper

The Handlebars {{if}} block helper is one of the const template = `<h1>
built-in helpers that will conditionally render a block of
{{#if quotaFull}}
code. The given block of code contains an example of the
usage of it. Please come back tomorrow.
{{/if}}
</h1>`;

const templateFunction =
Handlebars.compile(template);
const completedHtml = templateFunction({
quotaFull: true });
console.log(completedHtml); // <h1>Please
come back tomorrow.</h1>
The Handlebars {{else}} expression

The Handlebars {{else}} expression can be const template = `<span>


inserted into an {{if}} block helper. Template
{{#if isAdult}}
contents inside the else section comes into play when the
previous condition(s) are falsy. In the given example, You can enter the ride.
isAdult is set to false . Hence, You can {{else}}
enter the ride. will not be in the returned A guardian must accompany you.
template string.
{{/if}}
</span>`;

const templateFunction =
Handlebars.compile(template);
const htmlStr = templateFunction({
isAdult: false });
console.log(htmlStr); // <span>A guardian
must accompany you.</span>

Print Share
Cheatsheets / Learn JavaScript

Introduction

Assignment Operators

An assignment operator assigns a value to its left operand let number = 100;
based on the value of its right operand. Here are some of
them:
+= addition assignment // Both statements will add 10
-= subtraction assignment number = number + 10;
*= multiplication assignment
number += 10;
/= division assignment

console.log(number);
// Prints: 120

String Interpolation

String interpolation is the process of evaluating string let age = 7;


literals containing one or more placeholders (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 const currency = '$';
piece of data. A variable contains data that can be used in
let userIncome = 85000;
the program elsewhere. Using variables also ensures 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 var a;


represents lack of defined value. Variables that are
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 // Examples of variables


computer memory. It is referenced by a descriptive name
let name = "Tammy";
that a programmer can call to assign a specific value and
retrieve it. const found = false;
var age = 3;
console.log(name, found, age);
// Prints: Tammy false 3

Declaring Variables

To declare a variable in JavaScript, any of these three var age;


keywords can be used along with a variable name:
let weight;
var is used in pre-ES6 versions of JavaScript.
let is the preferred way to declare a variable const numberOfFingers = 20;
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 let name = "Codecademy";
expressions, ${expression} . While regular strings
console.log(`Hello, ${name}`);
use single ' or double " quotes, template literals use
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- let count;
assigned. Initialization during the declaration of a let
console.log(count); // Prints: undefined
variable is optional. A let variable will contain
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 numberOfColumns = 4;


const . It must have an assignment. Any attempt of re-
numberOfColumns = 8;
assigning a const variable will result in JavaScript
runtime error. // TypeError: Assignment to constant
variable.

String Concatenation

In JavaScript, multiple strings can be concatenated let service = 'credit card';


together using the + operator. In the example, multiple
let month = 'May 30th';
strings and variables containing string values have been
concatenated. After execution of the code block, the let displayText = 'Your ' + service + '
displayText variable will contain the concatenated bill is due on ' + month + '.';
string.

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

console.log()

The console.log() method is used to log or print console.log('Hi there!');


messages to the console. It can also be used to print
// Prints: Hi there!
objects and other info.
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 // Returns a number between 0 and 1
called by appending an instance with a period . , the
Math.random();
method name, and parentheses.

Built-in Objects

Built-in objects contain methods that can be called by Math.random();


appending the object name with a period . , the method
name, and a set of parentheses.
// ☝️ Math is the built-in object

Numbers

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

String .length

The .length property of a string returns the number let message = 'good nite';
of characters that make up the string.
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 let lateToWork = true;
true or false .

Math.random()

The Math.random() method returns a floating- console.log(Math.random());


point, random number in the range from 0 (inclusive) up
// Prints: 0 - 0.9999999999999999
to but not including 1.

Math.floor()

The Math.floor() function returns the largest console.log(Math.floor(5.95));


integer less than or equal to the given number.
// Prints: 5

Single Line Comments

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

Null

Null is a primitive data type. It represents the intentional let x = null;


absence of value. In code, it is represented as null .
Strings

Strings are a primitive data type. They are any grouping of let single = 'Wheres my bandit hat?';
characters (letters, spaces, numbers, or symbols)
let double = "Wheres my bandit hat?";
surrounded by single quotes ' or double quotes " .

Arithmetic Operators

JavaScript supports arithmetic operators for: // Addition


+ addition
5 + 5
- subtraction
* multiplication // Subtraction
/ division 10 - 5
% modulo // Multiplication
5 * 10
// 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 */
The below configuration must be
at the end. Comments are good ways for a variety of
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, // calculates # of weeks in a year, rounds
returns the number that remains after the right-hand
down to nearest integer
number divides into the left-hand number as many 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");

Print Share
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 true || false; // true
returns a boolean. If one or both values are truthy, it
10 > 5 || 10 > 20; // true
returns true . If both values are falsy, it returns
false . false || false; // false

A B A || B 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 let price = 10.5;
case of binary (choosing between two choices) decisions.
let day = "Monday";
It accepts a condition followed by a ? operator, and
then two expressions separated by a : . If the condition
evaluates to truthy, the first expression is executed, day === "Monday" ? price -= 1.5 : price +=
otherwise, the second expression is executed.
1.5;
else Statement

An else block can be added to an if block or series const isTaskCompleted = false;


of if - else if blocks. The else block will be
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 true && true; // true
returns a boolean. If both values are truthy, then it returns
1 > 2 && 2 > 1; // false
true . If one, or both, of the values is falsy, then it
returns false . true && false; // false
4 === 4 && 3 > 1; // true

switch Statement

The switch statements provide a means of checking const food = 'salad';


an expression against multiple case clauses. If a case
matches, the code inside that clause is executed.
The case clause should finish with a break switch (food) {
keyword. If no case matches but a default clause is case 'oyster':
included, 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
🦪');
case values until a break is encountered or the flow is break;
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 const isMailSent = true;


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

Logical Operator !

The logical NOT operator ! can be used to do one of let lateToWork = true;
the following:
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 1 > 3 // false


and return true or false depending on the validity
3 > 1 // true
of the comparison:
=== strict equal 250 >= 250 // true
!== strict not equal 1 === 1 // true
> greater than 1 === 2 // false
>= greater than or equal
1 === '1' // false
< less than
<= less than or equal
else if Clause

After an initial if block, else if blocks can each const size = 10;
check an additional condition. An optional else block
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

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.

Print Share
Cheatsheets / Learn JavaScript

Functions

Arrow Functions (ES6)

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

// Arrow functions with a single parameter


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 // Defining the function:
JavaScript. A function is a reusable set of statements to
function sum(num1, num2) {
perform a task or calculate a value. Functions can be
passed one or more values and can return a value at the return num1 + num2;
end of their execution. In order to use a function, you }
must define it somewhere in the scope where you wish to
call it.
The example code provided contains a function that // Calling the function:
takes in 2 values and returns the sum of those numbers. sum(3, 6); // 9

Anonymous Functions

Anonymous functions in JavaScript do not have a name // Named function


property. They can be defined using the function
function rocketToMars() {
keyword, or as an arrow function. See the code example
for the difference between a named function and an return 'BOOM!';
anonymous function. }

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

Function Expressions

Function expressions create functions inside an const dog = function() {


expression instead of as a function declaration. They can
return 'Woof!';
be anonymous and/or assigned to a variable.
}

Function Parameters

Inputs to functions are known as parameters when a // The parameter is name


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

Functions return (pass back) values using the return // With return
keyword. return ends function execution and returns
function sum(num1, num2) {
the specified value to the location where it was called. 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 function add(num1, num2) {


functions. These functions can be called using their
return num1 + num2;
declared name. Function declarations are built from:
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 // Defining the function


using parentheses following the function name. When a
function sum(num1, num2) {
function is called, the code inside its function body runs.
Arguments are values passed into a function when it is return num1 + num2;
called. }

// Calling the function


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

Scope

Scope

Scope is a concept that refers to where values and function myFunction() {


functions can be accessed.
Various scopes include:
Global scope (a value/function in the global var pizzaName = "Volvo";
scope can be used anywhere in the entire // Code here can use pizzaName
program)
File or module scope (the value/function can only
be accessed from within the file) }
Function scope (only visible within the function),
Code block scope (only visible within a { ...
// Code here can't use pizzaName
} codeblock)

Block Scoped Variables

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

console.log(statusMessage);

// Uncaught ReferenceError: statusMessage


is not defined
Global Variables

JavaScript variables that are declared outside of blocks // Variable declared globally
or functions can exist in the global scope, which means
const color = 'blue';
they are accessible throughout a program. Variables
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

Print Share
Cheatsheets / Learn JavaScript

Arrays

Property .length

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

numbers.length // 4

Index

Array elements are arranged by index values, starting at // Accessing an array element
0 as the first element index. Elements can be accessed
const myArray = [100, 200, 300];
by their index using the array name, and the 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 // Adding a single element:


used to add one or more elements to the end of an array.
const cart = ['apple', 'orange'];
.push() mutates the original array and returns the
new 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 const ingredients = ['eggs', 'flour',
an array and returns that element.
'chocolate'];

const poppedIngredient =
ingredients.pop(); // 'chocolate'
console.log(ingredients); // ['eggs',
'flour']

Mutable

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

Arrays

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

Print Share
Cheatsheets / Learn JavaScript

Loops

Reverse Loop

A for loop can iterate “in reverse” by initializing the const items = ['apricot', 'banana',
loop variable to the starting value, testing for when the
'cherry'];
variable hits the ending value, and decrementing
(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 x = 0


executes a block of code once, checks if a condition is
i = 0
true, and then repeats the loop as long as the condition is
true. They are used when you want the code to always
execute at least once. The loop ends when the condition do {
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 for (let i = 0; i < 4; i += 1) {
important pieces of information separated by semicolons
console.log(i);
;:
The initialization defines where to begin the loop };
by declaring (or referencing) the iterator variable
The stopping condition determines when to stop
// Output: 0, 1, 2, 3
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 for (let i = 0; i < array.length; i++){
property. This is extremely helpful for looping through
console.log(array[i]);
arrays, as the .length of the array can be used as the
stopping condition in the loop. }

// Output: Every item in the array

Break Keyword

Within a loop, the break keyword may be used to exit for (let i = 0; i < 99; i += 1) {
the loop immediately, continuing execution after the loop
if (i > 5) {
body.
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 for (let outer = 0; outer < 2; outer += 1)
another for loop.
{
The inner loop will run all its iterations for each 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.
While Loop

The while loop creates a loop that is executed as long while (condition) {
as a specified condition evaluates to true . The loop
// code block to be executed
will continue to run until the condition evaluates to
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++;
}

Print Share
Cheatsheets / Learn JavaScript

Iterators

The .reduce() Method

The .reduce() method iterates through an array const arrayOfNumbers = [1, 2, 3, 4];
and returns a single value.
In the above code example, the .reduce() method
will sum up all the elements of the array. It takes a const sum =
callback function with two parameters arrayOfNumbers.reduce((accumulator,
(accumulator, currentValue) as currentValue) => {
arguments. On each iteration, accumulator is the
value returned by the last iteration, and the return accumulator + currentValue;
currentValue is the current element. Optionally, a });
second argument can be passed which acts as the initial
value of the accumulator.
console.log(sum); // 10

The .forEach() Method

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

The .filter() Method

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

The .map() method executes a callback function on const finalParticipants = ['Taylor',


each element in an array. It returns a new array made up
'Donald', 'Don', 'Natasha', 'Bobby'];
of the return values from the callback function.
The original array does not get altered, and the returned
array may contain different elements than the original // add string after each final participant
array.
const announcements =
In the example code above, the .map() method is
used to add ' joined the contest.' string at finalParticipants.map(member => {
the end of each element in the return member + ' joined the contest.';
finalParticipants array. })

console.log(announcements);

Functions Assigned to Variables

In JavaScript, functions are a data type just as strings, let plusFive = (number) => {
numbers, and arrays are data types. Therefore, functions
return number + 5;
can be assigned as values to variables, but are 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 const isEven = (n) => {


passed into another function as an argument. This
return n % 2 == 0;
function can then be invoked during the execution of 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.
JavaScript Functions: First-Class Objects

JavaScript functions are first-class objects. Therefore: //Assign a function to a variable


They have built-in properties and methods, such
originalFunc
as the name property and the
.toString() method. const originalFunc = (num) => { return num
Properties and methods can be added to them. + 2 };
They can be passed as arguments and returned
from other functions.
They can be assigned to variables, array elements, //Re-assign the function to a new variable
and other objects. newFunc
const newFunc = originalFunc;

//Access the function's name property


newFunc.name; //'originalFunc'

//Return the function's body as a string


newFunc.toString(); //'(num) => { return
num + 2 }'

//Add our own isMathFunction property to


the function
newFunc.isMathFunction = true;

//Pass the function as an argument


const functionNameLength = (func) => {
return func.name.length };
functionNameLength(originalFunc); //12

//Return the function


const returnFunc = () => { return newFunc
};
returnFunc(); //[Function: originalFunc]

Print Share
Cheatsheets / Learn JavaScript

Objects

JavaScript destructuring assignment shorthand syntax

The JavaScript destructuring assignment is a shorthand const rubiksCubeFacts = {


syntax that allows object properties to be extracted into
possiblePermutations:
specific variable values.
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 const activity = 'Surfing';
creating objects without explicitly specifying the property
const beach = { activity };
names (ie. explicitly declaring the value after the key). In
this process, an object is created where the property console.log(beach); // { activity:
names of that object match variables which already exist 'Surfing' }
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 const cat = {


calling object, and it can be used to access properties
name: 'Pipey',
belonging to that object.
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 const restaurant = {


context. For a function defined inside of an object,
numCustomers: 45,
this will refer to that object itself. For a function
defined outside of an object, this will refer to the seatCapacity: 100,
global object ( window in a browser, global in availableSeats() {
Node.js).
// 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 const myObj = {
context, but use the this of the surrounding lexical
data: 'abc',
context. Thus, they are generally a poor choice for 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 myObj.loggerA(); // undefined
the enclosing object, the value of the data property is
myObj.loggerB(); // 'abc'
accessed as expected, returning "abc" .

getters and setters intercept property access

JavaScript getter and setter methods are helpful in part const myCat = {
because they offer a way to intercept property access
_name: 'Snickers',
and assignment, and allow for additional actions to be
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 // A factory function that accepts 'name',
factory function. Factory functions often accept
// 'age', and 'breed' parameters to return
parameters in order to customize the returned object.
// 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. const myCat = {


Since JavaScript objects are passed by reference, there is
_name: 'Dottie',
no way to fully prevent incorrect interactions with object
properties. get name() {
One way to implement more restricted interactions with return this._name;
object properties is to use getter and setter methods.
},
Typically, the internal value is stored as a property with an
identifier that matches the getter and setter method set name(newName) {
names, but begins with an underscore ( _ ). this._name = newName;
}
};

// Reference invokes the getter


console.log(myCat.name);

// Assignment invokes the setter


myCat.name = 'Yankee';
Restrictions in Naming Properties

JavaScript object key names must adhere to some // Example of invalid key names
restrictions to be valid. Key names must either be strings
const trainSchedule = {
or valid identifier or variable names (i.e. special
characters such as - are not allowed in key names that platform num: 10, // Invalid because of
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.
}

Dot Notation for Accessing Object Properties

Properties of a JavaScript object can be accessed using const apple = {


the dot notation in this manner:
color: 'Green',
object.propertyName . Nested properties of an
object can be accessed by chaining key names in the price: {
correct 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.
Accessing non-existent JavaScript properties

When trying to access a JavaScript object property that const classElection = {


has not been defined yet, the value of undefined
date: 'January 12'
will be returned by default.
};

console.log(classElection.place); //
undefined

JavaScript Objects are Mutable

JavaScript objects are mutable, meaning their contents const student = {


can be changed, even when they are declared as
name: 'Sheldon',
const . New properties can be added, and existing
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 let mobile = {


over the keys of an object. In each iteration, one of the
brand: 'Samsung',
properties from the object is assigned to the variable of
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 const classOf2018 = {


{} . Values are mapped to keys in the object with a
students: 38,
colon ( : ), and the key-value pairs are separated by
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 const person = {


remove properties from the object using the delete
firstName: "Matilda",
operator. The delete keyword deletes both the value
of the property and the property itself from the object. age: 27,
The delete operator only works on properties, not hobby: "knitting",
on 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 const origNum = 8;


functions or methods, they are passed by reference, not
const origObj = {color: 'blue'};
by value. This means that the object itself (not a 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 const engine = {
functions. These are referred to as object methods.
// method shorthand, with one argument
Methods may be defined using anonymous arrow 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...
*/

Print Share
Cheatsheets / Learn JavaScript Unit Testing

Write Good Tests With Mocha

The assert Library

The assert library is used to make assertions. It describe('+', () => {


contains numerous functions that enable the tester to
it('returns the sum of its arguments',
write easily readable assertions and throw
AssertionError s within a test. () => {
// Write assertion here
assert.ok(3 + 4 === 7)
});
});

assert.ok()

The assert.ok() function is be used to evaluate a describe('+', () => {


boolean expression within a test. If the expression
it('returns the sum of its arguments',
evaluates to false , an AssertionError is
thrown. () => {
// Write assertion here
assert.ok(3 + 4 === 7)
});
});
assert.equal()

assert.equal() verifies a loose equality (==) comparison. const landAnimals = ['giraffe',


Using assert.equal() is more expressive, it’s more clear
'squirrel'];
that it’s verifying equality than assert.ok().
const waterAnimals = ['shark',
'stingray'];

landAnimals.push('frog');
waterAnimals.push('frog');

assert.equal(landAnimals[2],
waterAnimals[2]);

assert.strictEqual()

assert.strictEqual() verifies a strict equality (===) const a = 3;


comparison.
const b = '3';
assert.equal(a, b);
assert.strictEqual(a, b);

assert.deepEqual()

assert.deepEqual() compares values within two objects. It const a = {relation: 'twin', age: '17'};
will compare the values using loose (==) equality.
const b = {relation: 'twin', age: '17'};

assert.deepEqual(a, b);

before() Hooks

In a test file, the function before() will be executed before(() => {


first, regardless of it’s placement in the code block.
path = './message.txt';
before() is often used to set up code, like variables
and values, for other function calls to use in their });
execution.
beforeEach() Hooks

In a test file, the function beforeEach() will be beforeEach(() => {


executed before each test. beforeEach() is often
testCounter++;
used to set up or reset code, like variables and values, for
other function calls to use in their execution. });

after() Hooks

In a test file, the function after() will be executed after(() => {


last, regardless of its placement in the code block.
console.log(""number of tests: "" +
after() is often used to print out results from the
tests that were run in the suite or to reset variables and testCounter);
values. });

afterEach() Hooks

In a test file, the function afterEach() will be afterEach(() => {


executed after each test. afterEach() is often
path = './message.txt';
used to print out results from a particular test that was
run in the suite or to reset variables and values. });

Why Test?

Testing can catch and identify issues with your


implementation code before you deploy it to users

Test Frameworks

Test frameworks are used to organize and automate tests


that provide useful feedback when errors occur.
describe() functions

In Mocha, the describe() function is used to group describe('group of tests', () => {


tests. It accepts a string to describe the group of tests
//Write it functions here
and a callback function which contains it() tests.
Calls to describe() are commonly nested to
resemble the structure of the code being tested. });

it() functions

In Mocha, the it() function is used to execute describe('+', () => {


individual tests. It accepts a string to describe the test
it('returns the sum of its arguments',
and a callback function to execute assertions. Calls to
it() are commonly nested within describe() () => {
blocks. // Write assertions here

});
});

Setup Phase

In testing, the Setup phase is where objects, variables, describe('.pop', () => {


and set conditions that tests depend on are created.
it('returns the last element in the
array [3phase]', () => {
// Setup
const knightString = 'knight';
const jediPath = ['padawan',
knightString];
// Exercise
const popped = jediPath.pop();
// Verify
assert.ok(popped === knightString);
});
});
Exercise Phase

In testing, the Exercise phase is where the functionality describe('.pop', () => {


under test is executed.
it('returns the last element in the
array [3phase]', () => {
// Setup
const knightString = 'knight';
const jediPath = ['padawan',
knightString];
// Exercise
const popped = jediPath.pop();
// Verify
assert.ok(popped === knightString);
});
});

Verify Phase

In testing, the Verify phase is where expectations are describe('.pop', () => {


checked against the result of the exercise phase.
it('returns the last element in the
assert would be used here.
array [3phase]', () => {
// Setup
const knightString = 'knight';
const jediPath = ['padawan',
knightString];
// Exercise
const popped = jediPath.pop();
// Verify
assert.ok(popped === knightString);
});
});
Teardown Phase

In testing, the Teardown phase is where the environment it('creates a new file with a string of
is reset before the next test runs. The teardown phase
text', () => {
ensures that a test is isolated from other tests.
// Setup
path = './message.txt';
str = '';

// Exercise: write to file


fs.appendFileSync(path, str);

// Verify: compare file contents to


string
const contents = fs.readFileSync(path);
assert.equal(contents.toString(), str);

// Teardown: restore file


fs.unlinkSync(path);
});

Tests in Isolation

A project’s tests should run in isolation from one another.


One test shouldn’t affect another. Tests should be able to
run in any order.

Print Share
Cheatsheets / Learn JavaScript: Error Handling

Errors and Error Handling

Runtime Error in JavaScript

A JavaScript runtime error is an error that occurs within


code while its being executed. Some runtime errors are
built-in objects in JavaScript with a name and message
property. Any code after a thrown runtime error will not
be evaluated.

The throw Keyword in JavaScript

The JavaScript throw keyword is placed before an // The program will raise and output this
Error() function call or object in order to construct
Error object with message 'Something went
and raise an error. Once an error has been thrown, the
program will stop running and any following code will not wrong'
be executed. throw Error('Something went wrong');

//The program will stop running after an


error has been raised, and any following
code will not be executed.
console.log('This will not be printed');

Javascript Error Function

The JavaScript Error() function creates an error object console.log(Error('Your password is too
with a custom message. This function takes a string
weak.')); //Error: Your password is too
argument which becomes the value of the error’s
message property. An error created with this function weak.
will not stop a program from running unless the throw
keyword is used to raise the error.
javascript try catch

A JavaScript try … catch statement can anticipate // A try...catch statement that throws a
and handle thrown errors (both built-in errors as well as
constructed Error()
those constructed with Error() ) while allowing a
program to continue running. Code that may throw an try {
error(s) when executed is written within the try block, throw Error('This constructed error will
and actions for handling these errors are written within
be caught');
the catch block.
} catch (e) {
console.log(e); // Prints the thrown
Error object
}

// A try...catch statement that throws a


built-in error
const fixedString = 'Cannot be
reassigned';
try {
fixedString = 'A new string'; // A
TypeError will be thrown
} catch (e) {
console.log('An error occurred!'); //
Prints 'An error occurred!'
}

console.log('Prints after error'); //


Program continues running after the error
is handled and prints 'Prints after error'

ReferenceError

A ReferenceError is a type of error thrown when a // Example of a ReferenceError in


variable is used that does not exist.
JavaScript
To prevent this error, all variables should be properly
declared beforehand. let firstName = "John";

// Here, we get a ReferenceError because


lastName has not been declared
console.log(firstName + lastName);
MDN JavaScript error documentation

The MDN JavaScript error documentation contains


information about JavaScript error types, properties, and
Methods. The document shows how to prevent and
create these errors. This document is most helpful when
developers come across an error they are not familiar
with.

SyntaxError

A SyntaxError is a type of error that is thrown when there # Example of a SyntaxError in Python
is a typo in the code, creating invalid code - code which
cannot be interpreted by the compiler.
Some common causes of a SyntaxError are: # A colon is missing after the closing
Missing opening or closing brackets, braces, or parenthesis
parentheses
def sum(a, b)
Missing or invalid semicolons
Misspelling of variable names or functions return a + b

TypeError

A TypeError is a type of error thrown when an attempt is # Example of a TypeError in Python


made to perform an operation on a value of the incorrect
number = 1
type.
One example of a TypeError is using a string method on a string = "one"
numerical value.

# Here, we try to concatenate the number


and string which will yield a TypeError
print(number + string)

Javascript error stack trace

An error stack trace tells a developer that it has detected


an error within the code. Along with, which line to find the
error, what type of error has occurred and a description
of the error.
Javascript documentation

Many times we can track down bugs, but still, be confused


about how to solve it. During these situations, we can look
at documentation. For JavaScript, the MDN JavaScript
web docs is a powerful resource. If we are still confused
after looking at this we can go to StackOverflow - a
question and answer forum where programmers post
issues and other programmers discuss and vote for
solutions.

Print Share
Cheatsheets / Learn JavaScript: Asynchronous Programming

Promises

States of a JavaScript Promise

A JavaScript Promise object can be in one of three const promise = new Promise((resolve,
states: pending , resolved , or rejected .
reject) => {
While the value is not yet available, the Promise stays
in the pending state. Afterwards, it transitions to one
const res = true;
of the two states: resolved or rejected . // An asynchronous operation.
A resolved promise stands for a successful if (res) {
completion. Due to errors, the promise may go in the
resolve('Resolved!');
rejected state.
In the example code block, if the Promise is on }
resolved state, the first parameter holding a else {
callback function of the .then() method will print reject(Error('Error'));
the resolved value. Otherwise, an alert will be shown.
}
});

promise.then((res) => console.log(res),


(err) => alert(err));
The .catch() method for handling rejection

The function passed as the second argument to a const promise = new Promise((resolve,
.then() method of a promise object is used when
reject) => {
the promise is rejected. An alternative to this approach is
to use the JavaScript .catch() method of the setTimeout(() => {
promise object. The information for the rejection is reject(Error('Promise Rejected
available to the handler supplied in the .catch()
Unconditionally.'));
method.
}, 1000);
});

promise.then((res) => {
console.log(value);
});

promise.catch((err) => {
alert(err);
});
JavaScript Promise.all()

The JavaScript Promise.all() method can be const promise1 = new Promise((resolve,


used to execute multiple promises in parallel. The
reject) => {
function accepts an array of promises as an argument. If
all of the promises in the argument are resolved, the setTimeout(() => {
promise returned from Promise.all() will resolve resolve(3);
to an array containing the resolved values of all the
}, 300);
promises in the order of the initial array. Any rejection
from the list of promises will cause the greater promise to });
be rejected. const promise2 = new Promise((resolve,
In the code block, 3 and 2 will be printed respectively
reject) => {
even though promise1 will be resolved after
promise2 . setTimeout(() => {
resolve(2);
}, 200);
});

Promise.all([promise1,
promise2]).then((res) => {
console.log(res[0]);
console.log(res[1]);
});

Executor function of JavaScript Promise object

A JavaScript promise’s executor function takes two const executorFn = (resolve, reject) => {
functions as its arguments. The first parameter represents
resolve('Resolved!');
the function that should be called to resolve the promise
and the other one is used when the promise should be };
rejected. A Promise object may use any one or both
of them inside its executor function.
const promise = new Promise(executorFn);
In the given example, the promise is always resolved
unconditionally by the resolve function. The
reject function could be used for a rejection.
.then() method of a JavaScript Promise object

The .then() method of a JavaScript Promise const promise = new Promise((resolve,


object can be used to get the eventual result (or error) of
reject) => {
the asynchronous operation.
.then() accepts two function arguments. The first setTimeout(() => {
handler supplied to it will be called if the promise is resolve('Result');
resolved. The second one will be called if the promise is
}, 200);
rejected.
});

promise.then((res) => {
console.log(res);
}, (err) => {
alert(err);
});

setTimeout()

setTimeout() is an asynchronous JavaScript const loginAlert = () =>{


function that executes a code block or evaluates an
alert('Login');
expression through a callback function after a delay set in
milliseconds. };

setTimeout(loginAlert, 6000);
Avoiding nested Promise and .then()

In JavaScript, when performing multiple asynchronous const promise = new Promise((resolve,


operations in a sequence, promises should be composed
reject) => {
by chaining multiple .then() methods. This is better
practice than nesting. setTimeout(() => {
Chaining helps streamline the development process resolve('*');
because it makes the code more readable and easier to
}, 1000);
debug.
});

const twoStars = (star) => {


return (star + star);
};

const oneDot = (star) => {


return (star + '.');
};

const print = (val) => {


console.log(val);
};

// Chaining them all together


promise.then(twoStars).then(oneDot).then(p
rint);

Creating a Javascript Promise object

An instance of a JavaScript Promise object is created const executorFn = (resolve, reject) => {
using the new keyword.
console.log('The executor function of
The constructor of the Promise object takes a
function, known as the executor function, as the the promise!');
argument. This function is responsible for resolving or };
rejecting the promise.

const promise = new Promise(executorFn);


The Promise Object

A Promise is an object that can be used to get the


outcome of an asynchronous operation when that result
is not instantly available.
Since JavaScript code runs in a non-blocking manner,
promises become essential when we have to wait for
some asynchronous operation without holding back the
execution of the rest of the code.

Chaining multiple .then() methods

The .then() method returns a Promise, even if one const promise = new Promise(resolve =>
or both of the handler functions are absent. Because of
setTimeout(() => resolve('dAlan'), 100));
this, multiple .then() methods can be chained
together. This is known as composition.
In the code block, a couple of .then() methods are promise.then(res => {
chained together. Each method deals with the resolved
return res === 'Alan' ?
value of their respective promises.
Promise.resolve('Hey Alan!') :
Promise.reject('Who are you?')
}).then((res) => {
console.log(res)
}, (err) => {
alert(err)
});

Print Share
Cheatsheets / Learn JavaScript: Asynchronous Programming

Async-Await

Resolving JavaScript Promises

When using JavaScript async...await , multiple let promise1 = Promise.resolve(5);


asynchronous operations can run concurrently. If the
let promise2 = 44;
resolved value is required for each promise initiated,
Promise.all() can be used to retrieve the let promise3 = new
resolved value, avoiding unnecessary blocking. Promise(function(resolve, reject) {
setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2,
promise3]).then(function(values) {
console.log(values);
});
// expected output: Array [5, 44, "foo"]
Creating async Function

An asynchronous JavaScript function can be created with function helloWorld() {


the async keyword before the function name, or
return new Promise(resolve => {
before () when using the arrow function syntax. An
async function returns a promise. setTimeout(() => {
resolve('Hello World!');
}, 2000);
});
}

const msg = async function() { //Async


Function Expression
const msg = await helloWorld();
console.log('Message:', msg);
}

const msg1 = async () => { //Async Arrow


Function
const msg = await helloWorld();
console.log('Message:', msg);
}

msg(); // Message: Hello World! <-- after


2 seconds
msg1(); // Message: Hello World! <-- after
2 seconds
Async Await Promises

The async...await syntax in ES6 offers a new way function helloWorld() {


write more readable and scalable code to handle
return new Promise(resolve => {
promises. It uses the same features that were already
built into JavaScript. setTimeout(() => {
resolve('Hello World!');
}, 2000);
});
}

async function msg() {


const msg = await helloWorld();
console.log('Message:', msg);
}

msg(); // Message: Hello World! <-- after


2 seconds

Using async await syntax

Constructing one or more promises or calls without


await can allow multiple async functions to
execute simultaneously. Through this approach, a
program can take advantage of concurrency, and
asynchronous actions can be initiated within an async
function. Since using the await keyword halts the
execution of an async function, each async function
can be awaited once its value is required by program
logic.
JavaScript async…await advantage

The JavaScript async...await syntax allows


multiple promises to be initiated and then resolved for
values when required during execution of the program. As
an alternate to chaining .then() functions, it offers
better maintainablity of the code and a close
resemblance synchronous code.

Async Function Error Handling

JavaScript async functions uses try...catch let json = '{ "age": 30 }'; // incomplete
statements for error handling. This method allows shared
data
error handling for synchronous and asynchronous code.

try {
let user = JSON.parse(json); // <-- no
errors
alert( user.name ); // no name!
} catch (e) {
alert( "Invalid JSON data!" );
}
The aysnc and await Keywords

The async … await ES6 JavaScript syntax offers a function helloWorld() {


new way to write more readable and scalable code to
return new Promise(resolve => {
handle promises. A JavaScript async function can
contain statements preceded by an await operator. setTimeout(() => {
The operand of await is a promise. At an await resolve('Hello World!');
expression, the execution of the async function is }, 2000);
paused and waits for the operand promise to resolve. The
});
await operator returns the promise’s resolved value.
An await operand can only be used inside an }
async function.
async function msg() {
const msg = await helloWorld();
console.log('Message:', msg);
}

msg(); // Message: Hello World! <-- after


2 seconds

Print Share
Cheatsheets / Learn JavaScript: Classes and Modules

Classes

Static Methods

Within a JavaScript class, the static keyword defines class Dog {


a static method for a class. Static methods are not called
constructor(name) {
on individual instances of the class, but are called on the
class itself. Therefore, they tend to be general (utility) this._name = name;
methods. }

introduce() {
console.log('This is ' + this._name +
' !');
}

// A static method
static bark() {
console.log('Woof!');
}
}

const myDog = new Dog('Buster');


myDog.introduce();

// Calling the static method


Dog.bark();
Class

JavaScript supports the concept of classes as a syntax for class Song {


creating objects. Classes specify the shared properties
constructor() {
and methods that objects produced from the class will
have. this.title;
When an object is created based on the class, the new this.author;
object is referred to as an instance of the class. New
}
instances are created using the new keyword.
The code sample shows a class that represents a Song .
A new object called mySong is created underneath play() {
and the .play() method on the class is called. The console.log('Song playing!');
result would be the text Song playing! printed in
the console.
}
}

const mySong = new Song();


mySong.play();

Class Constructor

Classes can have a constructor method. This is a class Song {


special method that is called when the object is created
constructor(title, artist) {
(instantiated). Constructor methods are usually used to
set initial values for the object. this.title = title;
this.artist = artist;
}
}

const mySong = new Song('Bohemian


Rhapsody', 'Queen');
console.log(mySong.title);
Class Methods

Properties in objects are separated using commas. This is class Song {


not the case when using the class syntax. Methods in
play() {
classes do not have any separators between them.
console.log('Playing!');
}

stop() {
console.log('Stopping!');
}
}

extends

JavaScript classes support the concept of inheritance — // Parent class


a child class can extend a parent class. This is
class Media {
accomplished by using the extends keyword as part
of the class definition. constructor(info) {
Child classes have access to all of the instance properties this.publishDate = info.publishDate;
and methods of the parent class. They can add their own
this.name = info.name;
properties and methods in addition to those. A child class
constructor calls the parent class constructor using the }
super() method. }

// Child class
class Song extends Media {
constructor(songData) {
super(songData);
this.artist = songData.artist;
}
}

const mySong = new Song({


artist: 'Queen',
name: 'Bohemian Rhapsody',
publishDate: 1975
});
Print Share
Cheatsheets / Learn JavaScript: Requests

Requests

JSON-Formatted Response Body

The .json() method will resolve a returned promise fetch('url')


to a JSON object, parsing the body text as JSON.
.then(
In the example code, the .json() method is used on
the response object which returns a promise to a response => response.json()
JSON-formatted response body as jsonResponse . ).then(jsonResponse => {
console.log(jsonResponse);
});

HTTP GET Request

HTTP GET requests are made with the intention of


retrieving information or data from a source (server) over
the web.
GET requests have no body, so the information that the
source requires, in order to return the proper response,
must be included in the request URL path or query string.

The fetch() Function

The JavaScript Fetch API is used to write HTTP requests fetch('url')


using Promises. The main fetch() function accepts a
.then(
URL parameter and returns a promise that resolves to a
response object or rejects with an error message if a response => {
network error occurs. console.log(response);
The example code begins by calling the fetch()
},
function. Then a then() method is chained to the
end of the fetch() . It ends with the response
rejection => {
callback to handle success and the rejection callback to console.error(rejection.message);
handle failure.
);
Customizing Fetch Requests

The fetch() function accepts an optional second fetch('https://api-to-call.com/endpoint',


argument, an options object, used to customize the
{
request. This can be used to change the request type,
headers, specify a request body, and much more. method: 'POST',
In the example code below, the fetch() function as body: JSON.stringify({id: "200"})
a second argument—an object containing options for the
}).then(response => {
fetch request specifying the method and the body .
if(response.ok){
return response.json();
}
throw new Error('Request
failed!');
}, networkError => {
console.log(networkError.message);
}).then(jsonResponse => {
console.log(jsonResponse);
})

HTTP POST Request

HTTP POST requests are made with the intention of


sending new information to the source (server) that will
receive it.
For a POST request, the new information is stored in
the body of the request.
Using async … await with Fetch

The async … await syntax is used with the Fetch const getSuggestions = async () => {
API to handle promises.
const wordQuery = inputField.value;
In the example code, the async keyword is used to
make the getSuggestions() function an async const endpoint =
function. This means that the function will return a `${url}${queryParams}${wordQuery}`;
promise. The await keyword used before the try{
fetch() call makes the code wait until the promise is
const response = await fetch(endpoint,
resolved.
{cache: 'no-cache'});
if(response.ok){
const jsonResponse = await
response.json()
}
}
catch(error){
console.log(error)
}
}

Print Share

You might also like