JavaScript Exercises
Fill in the blanks to check your knowledge. Each exercise belongs to a lesson.
JavaScript Introduction
Exercise
Print the text Hello.
console.("Hello");
Where to Put JavaScript
Exercise
Load the file after the page is parsed.
<script src="app.js" ></script>
JavaScript Output
Exercise
Write the text onto the page element.
demo. = "Hi";
JavaScript Syntax
Exercise
End the statement.
let x = 5JavaScript Comments
Exercise
Start a single line comment.
this line is ignoredVariables
Exercise
Declare a constant called age with the value 20.
age = 20;Scope
Exercise
Which keyword gives a block scoped variable that can change?
count = 0;Hoisting
Exercise
Which kind of function can be called before its line?
greet() {}Data Types
Exercise
Find the type of the value.
console.log( 42);
Type Conversion
Exercise
Convert the text to a number.
const n = ("42");
Operators
Exercise
Check that a is strictly equal to 5.
console.log(a 5);
Logical, Ternary and Nullish Operators
Exercise
Use a default only when the value is null or undefined.
const n = value 5;
Booleans and Truthiness
Exercise
Turn the value into a boolean.
const ok = ("hi");
JavaScript Statements
Exercise
Name the keyword that declares a changeable variable.
x = 1;Keywords and Identifiers
Exercise
Valid name start.
let name = 1;
let, const and var
Exercise
Never reassigned.
rate = 0.1;The typeof Operator
Exercise
Check a type.
xnull and undefined
Exercise
Default for null or undefined.
x "none"
== versus ===
Exercise
Strict equality.
1 "1"
Truthy and Falsy Values
Exercise
Convert to boolean.
(value)Operator Precedence and Assignment
Exercise
Add and assign.
n 5
Increment, Decrement and Bitwise
Exercise
Shift left by 3.
1 3
Exponent, Modulo and Integer Division
Exercise
Remainder.
17 5
Strings
Exercise
Get the number of characters.
"hello".String Methods
Exercise
Remove spaces from both ends.
" hi ".()
Template Literals
Exercise
Which character wraps a template literal?
const s = Hello;
Numbers
Exercise
What does dividing a number by zero give?
console.log(5 / 0); // Number Methods
Exercise
Round to 2 decimal places.
(3.14159).(2)
The Math Object
Exercise
Always round down.
Math.(4.9)
Random Numbers
Exercise
Get a random decimal between 0 and 1.
Math.()
String Basics
Exercise
Length of a string.
s.slice, substring and substr
Exercise
Take the first 4 characters.
s.slice(0, )
Searching Strings
Exercise
Test for a part.
s.("fast")
replace, replaceAll, split and join
Exercise
Replace every match.
s.("a", "b")
Trim, Pad, Repeat and Case
Exercise
Pad with zeros at the start.
"7".(3, "0")
Unicode, Emoji and localeCompare
Exercise
Compare for sorting text.
a.(b)
Parsing Numbers
Exercise
Strict conversion.
("12")Formatting Numbers
Exercise
Two decimals.
n.toFixed()
More Math Functions
Exercise
Largest value.
Math.(1, 5)
Random Numbers in Practice
Exercise
Secure random source.
crypto.(arr)
Number Limits and Precision
Exercise
Safe integer limit.
Number.MAX_SAFEConditions
Exercise
Run the code when age is at least 18.
(age >= 18) {
console.log("Adult");
}The switch Statement
Exercise
Stop the switch from falling through.
case 1: console.log("one"); ;
Loops
Exercise
Count from 0 to 4.
for (let i = 0; i 5; i++) { console.log(i); }
for...of and for...in
Exercise
Loop over the values of the array.
for (const item items) {}
while, do...while, break and continue
Exercise
Leave the loop early.
while (true) { ; }
if, else if and else
Exercise
Alternative branch.
if (x) {} {}
Ternary and switch
Exercise
Ternary symbol.
cond yes : no
Loop Control: break, continue and labels
Exercise
Skip this round.
;Functions
Exercise
Send a value back from the function.
function add(a, b) { a + b; }
Function Parameters
Exercise
Collect any number of arguments.
function total(nums) {}
Arrow Functions
Exercise
Write the arrow.
const double = (x) x * 2;
Callbacks and Higher-Order Functions
Exercise
Run the callback.
function run(cb) { (); }
Closures
Exercise
Return the inner function.
function outer() { let n = 0; () => ++n; }
Recursion
Exercise
Name the part that stops the recursion.
if (n <= 1) return 1; // the case
Declarations, Expressions and Hoisting
Exercise
Return a value.
function f() { 1; }
Default and Rest Parameters
Exercise
Gather the rest.
function f(a, b) {}
Arrow Functions and this
Exercise
Short function.
const f = (x) x * 2;
IIFE and Higher Order Functions
Exercise
Run immediately.
(function () {})call, apply and bind
Exercise
Fix this for later.
fn.(obj)
Recursion Patterns
Exercise
Stop condition.
The case stops recursion
Objects
Exercise
Read the city from the object.
const place = { city: "Lagos" }; console.log(place.);
Object Methods and this
Exercise
Refer to the current object.
greet() { return .name; }
Destructuring
Exercise
Unpack the name property.
const { } = { name: "Ada" };
Spread and Rest
Exercise
Copy the array using spread.
const copy = [original];
Classes
Exercise
Create an instance.
const s = Student("Ada");
Class Inheritance
Exercise
Make Dog inherit from Animal.
class Dog Animal {}
JSON
Exercise
Turn the object into JSON text.
JSON.(obj)
Objects: Properties and Methods
Exercise
Read a key by name.
user[]
Object.keys, values, entries and assign
Exercise
List the keys.
Object.(o)
Optional Chaining and Defaults
Exercise
Safe property access.
user.name
Freeze, Seal and Property Descriptors
Exercise
Stop all changes.
Object.(obj)
Classes: Constructors and Methods
Exercise
Create an instance.
const d = Dog("Rex");
Inheritance with extends and super
Exercise
Call the parent constructor.
(name);Getters, Setters and Static in Classes
Exercise
Class level method.
create() {}JSON in Practice
Exercise
Pretty print.
JSON.stringify(x, null, )
Arrays
Exercise
Add an item to the end of the array.
const fruits = ["apple"]; fruits.("mango");
Array Methods
Exercise
Add an item to the end.
list.("x");
map, filter and reduce
Exercise
Keep only the items that pass the test.
nums.((n) => n > 2)
Sorting Arrays
Exercise
Sort numbers from low to high.
nums.sort((a, b) => a b);
Sets
Exercise
Create a new Set.
const s = Set([1, 2]);
Maps
Exercise
Read a value from the map.
stock.("apple")
Array Basics
Exercise
Add to the end.
a.(5)
slice, splice and concat
Exercise
Remove 2 items from index 1.
a.splice(1, )
Finding Items in Arrays
Exercise
First matching item.
n.((x) => x > 10)
Looping Over Arrays
Exercise
Loop over values.
for (const v a)
reduce in Practice
Exercise
Starting value for a sum.
arr.reduce((s, n) => s + n, )
Sorting Arrays Correctly
Exercise
Numeric ascending order.
sort((a, b) => a b)
Set and Map in Practice
Exercise
Remove duplicates.
[...new (arr)]
Array Destructuring and Spread
Exercise
Collect the rest.
const [x, ...] = arr;
Array.from, Array.of and fill
Exercise
Make an array of 5 zeros.
new Array(5).(0)
Dates
Exercise
Create the current date and time.
const now = new ();
Regular Expressions
Exercise
Find all matches, not just the first.
const re = /cat/;
Working with Dates
Exercise
Month numbers start at.
getMonth() starts at Regular Expressions in Practice
Exercise
Global flag.
/a/Errors and try...catch
Exercise
Which block runs when an error is thrown?
try { risky(); } (e) { console.log(e); }
Debugging
Exercise
Pause the code in the debugger.
;try, catch and finally
Exercise
Always runs.
try {} {}
Debugging with the Console
Exercise
Pause in dev tools.
;The DOM
Exercise
Change the text of the element.
const box = document.getElementById("demo"); box. = "Hello";
Selecting Elements
Exercise
Select every paragraph.
document.("p")
Changing Content and Attributes
Exercise
Set plain, safe text.
el. = userInput;
Changing Styles
Exercise
Switch a class on or off.
box.classList.("active");
Creating and Removing Elements
Exercise
Create a new paragraph element.
document.("p")
Events
Exercise
Run the function on click.
button.addEventListener("", () => { alert("Hi"); });
Event Listeners
Exercise
Stop the default action of the event.
event.();
Forms and User Input
Exercise
Which event fires when a form is sent?
form.addEventListener("", handler);
Navigating the DOM
Exercise
Parent element.
el.Element
Attributes, Classes and Dataset
Exercise
Toggle a class.
el.classList.("on")
Event Delegation
Exercise
Which element was clicked.
e.Forms and Validation in JavaScript
Exercise
Stop the page reload.
e.()
localStorage, sessionStorage and Cookies
Exercise
Save a value.
localStorage.Item("a", "1")
Intersection and Resize Observers
Exercise
Watch an element.
observer.(el)
Window, Location and History
Exercise
Current page address.
location.Fetch in Practice
Exercise
Check success.
if (!res.)
Timers
Premium exercise. See plans
Promises
Premium exercise. See plans
async and await
Premium exercise. See plans
Fetch and APIs
Premium exercise. See plans
Web Storage
Premium exercise. See plans
Project: Calculator Logic
Exercise
Look up an operation.
ops[]
Project: A Quiz Game
Exercise
Count correct answers.
scoreProject: Countdown Timer
Exercise
Stop an interval.
(id)Modules
Premium exercise. See plans
Best Practices
Premium exercise. See plans
Common Mistakes
Premium exercise. See plans
Iterators and the for...of Protocol
Premium exercise. See plans
Generator Functions
Premium exercise. See plans
Symbols
Premium exercise. See plans
Getters, Setters and defineProperty
Premium exercise. See plans
Prototypes and the Prototype Chain
Premium exercise. See plans
Private Fields and Static Members
Premium exercise. See plans
Tagged Template Literals
Premium exercise. See plans
Proxy and Reflect
Premium exercise. See plans
WeakMap, WeakSet and WeakRef
Premium exercise. See plans
Modern Array Methods
Premium exercise. See plans
Internationalisation with Intl
Premium exercise. See plans
BigInt and Numeric Precision
Premium exercise. See plans
Typed Arrays and ArrayBuffer
Premium exercise. See plans
Promise Combinators
Premium exercise. See plans
Async Iterators and for await
Premium exercise. See plans
Cancelling with AbortController
Premium exercise. See plans
The Event Loop in Depth
Premium exercise. See plans
Custom Events and Pub Sub
Premium exercise. See plans
Debounce and Throttle
Premium exercise. See plans
Memoization and Caching
Premium exercise. See plans
Currying and Function Composition
Premium exercise. See plans
Immutable Data and Freezing
Premium exercise. See plans
Custom Errors and Error Handling Patterns
Premium exercise. See plans
Security: XSS and Safe DOM Updates
Premium exercise. See plans
Testing JavaScript
Premium exercise. See plans
Measuring Performance
Premium exercise. See plans
Modelling State with a State Machine
Premium exercise. See plans
Project: To Do List
Premium exercise. See plans