Javascript Codecademy
Javascript Codecademy
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>
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');
document.getElementById('list').appendChil
d(newElement);
};
HTML 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
Print Share
Cheatsheets / Building Interactive JavaScript Websites
.addEventListener()
.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
Keyboard events
javascript event
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
Print Share
Cheatsheets / Building Interactive JavaScript Websites
Handlebars.compile()
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>
*/
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
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
`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
Declaring Variables
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
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
String Concatenation
console.log(displayText);
// Prints: Your credit card bill is due on
May 30th.
console.log()
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
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
Booleans
Booleans are a primitive data type. They can be either let lateToWork = true;
true or false .
Math.random()
Math.floor()
In JavaScript, single-line comments are created with two // This line will denote a comment
consecutive forward slashes // .
Null
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
Multi-line Comments
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);
Print Share
Cheatsheets / Learn JavaScript
Conditionals
Control Flow
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
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
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
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
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
Print Share
Cheatsheets / Learn JavaScript
Functions
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
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 function
const rocketToMars = function() {
return 'BOOM!';
}
Function Expressions
Function Parameters
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.
Function Declaration
Calling Functions
Scope
Scope
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);
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.
}
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 .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
// 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
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. }
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
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 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 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 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
console.log(announcements);
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
Higher-Order Functions
Print Share
Cheatsheets / Learn JavaScript
Objects
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
console.log(cat.whatName());
// Output: Pipey
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" .
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 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.
}
Objects
console.log(classElection.place); //
undefined
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
console.log(person);
/*
{
firstName: "Matilda"
age: 27
goal: "learning JavaScript"
}
*/
javascript passing objects as arguments
changeItUp(origNum, origObj);
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
assert.ok()
landAnimals.push('frog');
waterAnimals.push('frog');
assert.equal(landAnimals[2],
waterAnimals[2]);
assert.strictEqual()
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
after() Hooks
afterEach() Hooks
Why Test?
Test Frameworks
it() functions
});
});
Setup Phase
Verify 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 = '';
Tests in Isolation
Print Share
Cheatsheets / Learn JavaScript: Error Handling
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 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
}
ReferenceError
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
Print Share
Cheatsheets / Learn JavaScript: Asynchronous Programming
Promises
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.
}
});
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()
Promise.all([promise1,
promise2]).then((res) => {
console.log(res[0]);
console.log(res[1]);
});
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
promise.then((res) => {
console.log(res);
}, (err) => {
alert(err);
});
setTimeout()
setTimeout(loginAlert, 6000);
Avoiding nested Promise and .then()
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.
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
Promise.all([promise1, promise2,
promise3]).then(function(values) {
console.log(values);
});
// expected output: Array [5, 44, "foo"]
Creating async Function
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
Print Share
Cheatsheets / Learn JavaScript: Classes and Modules
Classes
Static Methods
introduce() {
console.log('This is ' + this._name +
' !');
}
// A static method
static bark() {
console.log('Woof!');
}
}
Class Constructor
stop() {
console.log('Stopping!');
}
}
extends
// Child class
class Song extends Media {
constructor(songData) {
super(songData);
this.artist = songData.artist;
}
}
Requests
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