JavaScript exercises - Basics

This collection of 77 exercises is about the basics of the JavaScript language. It is of great value for beginners and intermediate programmers who want to be quite good at JavaScript.

Bite-sized, tested and vetted exercises only: no storytelling, no riddle, minimal use of math (basic arithmetic).

Arrays 01

  1. Create 3 empty arrays e1, e2, e3, in 3 different ways.
  2. Create 2 arrays a1 and a2, containing a single element 1, in 2 different ways.

To see the solution, enter a valid code or purchase one:


Arrays 02

const a = [1, 2, 3, 4, 5];

Create 3 arrays a1, a2 and a3 in 3 different ways so that they contain the same elements as a and so that they are independent from one another. Mutating the array a should not mutate any of the 3 other arrays.

To see the solution, enter a valid code or purchase one:


Arrays 03

let letters = [...'Elephant'];

Iterate through the letters array to display each letter to the screen. Do it in 5 different ways.

To see the solution, enter a valid code or purchase one:


Arrays 04

const numbers_1 = [1, 2, 3];
const numbers_2 = [4, 5, 6];

Concatenate the 2 arrays numbers_1 and numbers_2 and assign the result to a new variable called numbers.

To see the solution, enter a valid code or purchase one:


Arrays 05

const numbers = [0, 1, 2, 3, 4, 5];

Create 3 new arrays doubled_1, doubled_2, doubled_3 that have doubled values compared to numbers. Use 4 different ways to do so.

To see the solution, enter a valid code or purchase one:


Arrays 06

const a = [5, 4, 3, 2, 1];

Create a new array b that contains the values from a that are even.

To see the solution, enter a valid code or purchase one:


Arrays 07

const a = [1, 2, 3, 4, 5];

Find the 1st element in a that is greater or equal to 3 and assign the value to a new variable b.

To see the solution, enter a valid code or purchase one:


Arrays 08

const a = [1, 2, 3, 4, 5];

Find the index of the 1st element that is even and assign the value to a new variable b.

To see the solution, enter a valid code or purchase one:


Arrays 09

const a = [1, 2, 3, 4, 5];

Check if all values of a are greater or equal to 10 and store the resulting value into a new variable all.

To see the solution, enter a valid code or purchase one:


Arrays 10

const numbers = [0, 1, 2, 3, 4, 5];
const words = ['Pizza', 'Cheesy Cannelloni', 'Osso buco'];
  1. Use the method reduce() to calculate the sum of all values contained in the array numbers. Assign the result to a new variable sum.
  2. Use the method reduce() to find the longest word in the array words. Assign the result to a new variable longest.

To see the solution, enter a valid code or purchase one:


Arrays 11

const numbers = [0, 1, 2, 3, 4, 5];

Create a new array selected that contains all values of numbers from index 1 to index 3.

To see the solution, enter a valid code or purchase one:


Arrays 12

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

Delete the values 2 and 3 in numbers and replace them with 'a' and 'b'.

To see the solution, enter a valid code or purchase one:


Arrays 13

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

Delete all values from numbers, starting at index 4. numbers should only contain the values of indices 0, 1, 2 and 3.

To see the solution, enter a valid code or purchase one:


Arrays 14

const a = [1, 2, 3, 4, 5];

Check if any value of a is negative and store the resulting value into a new variable any.

To see the solution, enter a valid code or purchase one:


Classes 01: classy cat

  1. Declare a constuctor function named Cat(), that can set the properties _age and _name of any instance of a cat.
  2. Add a function jump() that can be common to all cat instances. Do not modify the code of the Cat()constructor function you already declared. The jump() method should log the string 'Fiuuuuu!'.
  3. Create a cat felix named 'Felix' and aged 3.
  4. Create a cat tom named 'Tom' and aged 5.
  5. Add a getter method for getting any cat name. The getter should be defined in the prototype of Cat.
  6. Use the getter function to print to the screen the names of felix an tom in 2 separate statements.

To see the solution, enter a valid code or purchase one:


Classes 02: classy dog

  1. Use a factory function to create a class of dogs that have a _name, an _age and that can bark. The bark() method should display the string 'Woof!'.
  2. Create a dog toby named 'Toby' and aged 2.
  3. Create a dog fox named 'Fox' and aged 4.
  4. Display the names of the dogs by using a getter method.

To see the solution, enter a valid code or purchase one:


Classes 03: classy rabbit

  1. Declare a constructor function named Rabbit, with the keyword class to create a class of rabbits that have a _name, an _age and that can eat. The eat() method should log the string 'Crr crr crr'. The class should also have a getter method name to get the _name of a rabbit.
  2. Create a rabbit bugs named 'Bugs' and aged 1.
  3. Create a rabbit Roger named 'Roger' and aged 3.
  4. Display the names of the rabbits by using a getter method.

To see the solution, enter a valid code or purchase one:


Control structures 01: All of the lights

const light = 'green';
let action = '';

if (light === 'green') {
  action = 'Go';
} else if (light === 'yellow') {
  action = 'Slow down';
} else if (light === 'red') {
  action = 'Stop';
} else if (light === 'blue') {
  action = 'Pull over';
} else {
  action = 'Look at the sky';
}

Rewrite the previous code by using a switch statement.

To see the solution, enter a valid code or purchase one:


Control structures 02: ternary

const light = 'green';
let action = '';

if (light === 'green') {
  action = 'Go';
} else {
  action = 'Stay still';
}

Rewrite the previous code by using the ternary operator.

To see the solution, enter a valid code or purchase one:


Data types 01: lie detector

let a;
if (a) {
  console.log('a');
}

let b = a;

if (b = {}) {
  console.log('b'); 
}

let c = [''];

if (!c) {
  console.log('c');
}

if (!c[0]) {
  console.log('d');
}

if (0) {
  console.log('e');
}

What does the previous code display to the screen?

To see the solution, enter a valid code or purchase one:


Data types 02

const text = 'Elephant';

Convert the variable text into a Boolean and store the new value into a another variable called bool.

Display to the screen the value of bool.

To see the solution, enter a valid code or purchase one:


Data types 03

const text = '3.1415';

Convert variable text into a number and store the new value into another variable called num.

To see the solution, enter a valid code or purchase one:


Data types 04

const bool = true;

Convert the variable bool into a String and store the new value into another variable called text.

To see the solution, enter a valid code or purchase one:


Data types 05

const num = 10;

Convert the variable num into a String and store the new value into another variable called text.

To see the solution, enter a valid code or purchase one:


Data types 06

const num = 3.1415;

Convert the variable num into a String that represents the value with only 2 digits after the decimal point. Store the new value to another variable called text.

To see the solution, enter a valid code or purchase one:


Data types 07

const text = '22';

Convert variable text into a number and store the new value into another variable called num.

To see the solution, enter a valid code or purchase one:


Functions 01

Define 3 functions f1, f2 and f3 that have 1 parameter text and that display text to the screen. Use 3 different ways to do it.

To see the solution, enter a valid code or purchase one:


Functions 02

Create an arrow function basic() that simply returns the object { a: 1 }.

To see the solution, enter a valid code or purchase one:


Functions 03

Define a function print that can take an undefined number of arguments, and that logs each argument to the console.

To see the solution, enter a valid code or purchase one:


Functions 04

const singSong_1 = (song) => {
  console.log(`This song "${song}" is great!`);
};

const singSong_2 = (song = 'Billy Jean') => {
  console.log(`This song "${song}" is great!`);
};

singSong_1();
singSong_2();

What does the previous code display to the screen?

To see the solution, enter a valid code or purchase one:


Modules 01

// file-1.js
const sum = (x, y) => x + y;
const square = x => x * x;
const mean = data => data.reduce(sum) / data.length;

Export the function sum by using the native node.js syntax (also known as the CommonJS syntax).

To see the solution, enter a valid code or purchase one:


Modules 02

// file-1.js
const sum = (x, y) => x + y;
const square = x => x * x;
const mean = data => data.reduce(sum) / data.length;

Export the functions sum and square by using the native node.js syntax (also known as the CommonJS syntax).

To see the solution, enter a valid code or purchase one:


Modules 03

// file-1.js
const sum = (x, y) => x + y;
const square = x => x * x;
const mean = data => data.reduce(sum) / data.length;

module.exports = { sum, square };

Let us assume that there is a file file-2.js in the same directory as file-1.js. Import the function sum from file-1.js into file-2.js by using the native node.js syntax (also known as the CommonJS syntax).

To see the solution, enter a valid code or purchase one:


Modules 04

// file-1.js
const sum = (x, y) => x + y;
const square = x => x * x;
const mean = data => data.reduce(sum) / data.length;

Export the function sum by using the ES6 syntax.

To see the solution, enter a valid code or purchase one:


Modules 05

// file-1.js
const sum = (x, y) => x + y;
const square = x => x * x;
const mean = data => data.reduce(sum) / data.length;

Export the functions sum and square by using the ES6 syntax.

To see the solution, enter a valid code or purchase one:


Modules 06

// file-1.js
const sum = (x, y) => x + y;
const square = x => x * x;
const mean = data => data.reduce(sum) / data.length;

export { sum };

Let us assume that there is a file file-2.js in the same directory as file-1.js. Import the function sum from file-1.js into file-2.js by using the ES6 syntax.

To see the solution, enter a valid code or purchase one:


Modules 07

// file-1.js
const sum = (x, y) => x + y;
const square = x => x * x;
const mean = data => data.reduce(sum) / data.length;

export default sum;

Let us assume that there is a file file-2.js in the same directory as file-1.js. Import the function sum from file-1.js into file-2.js by using the ES6 syntax.

To see the solution, enter a valid code or purchase one:


Modules 08

// file-1.js
const sum = (x, y) = > x + y;
const square = x = > x * x;
const mean = data => data.reduce(sum) / data.length;

export { sum, square };

Let us assume that there is a file file-2.js in the same directory as file-1.js. Import the functions sum and square from file-1.js into file-2.js by using the ES6 syntax.

To see the solution, enter a valid code or purchase one:


Modules 09

Let us assume that the following files module.js, module-brand.js, module-city.js, module-name.js and main.js are the same directory:

// module.js
console.log('module is executed');

const brand = 'Coke Boys';
const city = 'New York';
const name = 'French Montana';

export { brand, city, name };
// module-brand.js
import { brand } from './module.js';

console.log('module-brand is executed');

export { brand };
// module-city.js
import { city } from './module.js';

console.log('module-city is executed');

export { city };
// module-name.js
import { name } from './module.js';

console.log('module-name is executed');

export { name };
// main.js
import { brand } from './module-brand.js';
import { city } from './module-city.js';
import { name } from './module-name.js';

console.log(brand);
console.log(city);
console.log(name);

What is printed to the screen when we execute the file main.js, i.e. in the browser, by loading an html page located in the same directory and containting the code in main.js, or in Node.js, by typing node main.js?

To see the solution, enter a valid code or purchase one:


Modules 10

Let us assume that the following files module.js and main.js are the same directory:

// module.js
export const name = 'Doja Cat';

const flag = true;

if (flag) {
    export const job = 'singer';
}
// main.js
import { name, job } from './module.js';

console.log(name);
console.log(job);

What is printed to the screen when we execute the file main.js, i.e. in the browser, by loading an html page located in the same directory and containting the code in main.js, or in Node.js, by typing node main.js?

To see the solution, enter a valid code or purchase one:


Numbers 01: decimal fiesta

const a = 0.4 - 0.3;
const b = 0.3 - 0.2;

console.log (a === b);

What does the previous code display to the screen?

To see the solution, enter a valid code or purchase one:


Numbers 02: Math prohibition

const a = ('a' / 1);
const b = (5 / 0);
const c = (-5 / 0);

console.log(a);
console.log(b);
console.log(c);

console.log(typeof a);
console.log(typeof b);
console.log(typeof c);

What does the previous code display to the screen?

To see the solution, enter a valid code or purchase one:


Numbers 03: in da club

  1. We have a variable b. Check if b is equal to NaN.
  2. We have a variable c. Check if c is a regular number (different than NaN, Infinity and -Infinity).

To see the solution, enter a valid code or purchase one:


Numbers 04: Chance the function

Define a function randomIntegerBetween() that has 2 integers as parameters, min and max, and returns a random integer between min and max inclusive.

To see the solution, enter a valid code or purchase one:


Object celebration 01

Create 3 empty objects a, b and c in 3 different ways.

To see the solution, enter a valid code or purchase one:


Object celebration 02

const a = { a1: 1, a2: 2, a3: 3 };
a[Symbol.for("a4")] = 4;

let b = Object.create(a);
b.b1 = 5;
b[Symbol.for("b2")] = 6;

for (let p in b) {
  console.log(p, b[p]);
}

What does the previous code display to the sreen?

To see the solution, enter a valid code or purchase one:


Object celebration 03

const a = {
  a1: 1,
  a2: 2,
  countryCallingCodes: { US: 1, UK: 44 }
};

Create a new object b, which is a deep copy of the object a. In other words, if we ever mutate object a, it does not affect object b.

To see the solution, enter a valid code or purchase one:


Object celebration 04

const a = 1, b = 2, c= 3, d = 4, e = 5;
  1. Use the ES6/ES2015 shorthand property names syntax to create an object o that has property names a, b, c, d, e, and property values 1, 2, 3, 4, 5.
  2. Create a similar object p, but without using ES6/ES2015 shorthand property names syntax.

To see the solution, enter a valid code or purchase one:


Object celebration 05

const PROPERTY_NAME = 'p1';
const propertyValue = () => 'p' + 2;

Create an object o that has properties names of p1 and p2 and values of 1 and 2. Use PROPERTY_NAME and propertyValue() to do so.

To see the solution, enter a valid code or purchase one:


Object celebration 06

Create an object o that has a property _color with a value of 'green', a simple getter method and a simple setter method.

Display to the screen the color of o, then change it to 'blue' and finally display the new color of o to the screen.

To see the solution, enter a valid code or purchase one:


Object celebration 07

Display to the screen all the properties of the global object of your environment.

To see the solution, enter a valid code or purchase one:


Object celebration 08

const array = [...'abc'];
const object = { k1: 1, k2: 2, k3: 3 };

Without running the code, what does each of the following loop print to the screen?

// Loop 1
for (let value in array) {
  console.log(value);
}
// Loop 2
for (let value of array) {
  console.log(value);
}
// Loop 3
for (let value in object) {
  console.log(value);
}
// Loop 4
for (let value of object) {
  console.log(value);
}

To see the solution, enter a valid code or purchase one:


Object celebration 09

const letters = [...'abcdefghijklmnopqrstuvwxyz'];
const randomIndex = Math.floor(Math.random() * letters.length);
const khaled = Object.assign(
  {},
  {
    [letters[randomIndex]]: 'major key'
  }
);

console.log(khaled);

Write some code to check if the object khaled has the key 'b'. If it does, display to the screen 'Another one'. Otherwise, display to the screen "Don't play yourself".

To see the solution, enter a valid code or purchase one:


String party 01: Twister

const twister = 'Betty Botter bought some butter';

Assign the first 3 characters of the string twister to a variable first_3.

To see the solution, enter a valid code or purchase one:


String party 02: Crocodile

const danger = 'Croco-croco-dile';
  1. Assign the index of the first letter 'o' of the string danger to a variable a.
  2. Assign the index of the last 'co' of the string danger to a variable b.

To see the solution, enter a valid code or purchase one:


String party 03: Giraffe

const tall = 'Giraffe-raffe-gi';
  1. Check if the string tall starts with 'Gir' and assign the return value to a variable a.
  2. Check if the string string tall ends with '-gi' and assign the return value to a variable b.

To see the solution, enter a valid code or purchase one:


String party 04: 123

const numbers = '12345 34567 56789';

Check if the string numbers includes the characters '345' and assign the return value to a variable t.

To see the solution, enter a valid code or purchase one:


String party 05: Symetry

const symetry = '--------0|0--------';

Replace the '-' with '_' in the string symetry and assign the return value to a variable t.

To see the solution, enter a valid code or purchase one:


String party 06: Bob

const bob = 'I shot the sheriff';
  1. Transform the string bob to lower case and assign the return value to a variable lower.
  2. Transform the string bob to upper case and assign the return value to a variable upper.

To see the solution, enter a valid code or purchase one:


String party 07: Franck

const franck = 'Singing in the rain';

Assign the character at index 5 of the string franck to a variable t.

To see the solution, enter a valid code or purchase one:


String party 08: Snoop

const snoop = 'Calvin';

Asign the ASCII code of the character at index 4 of the string snoop to a new variable t.

To see the solution, enter a valid code or purchase one:


String party 09: Heisenberg

const heisenberg = "I'm in the empire business";
  1. Add 3 white spaces at the beginning of heisenberg and assign the new value to a variable a.
  2. Add 3 white spaces at the end of heisenberg and assign the new value to a variable b.
  3. Add 3 '*' at the beginning of heisenberg and assign the new value to a variable c.
  4. Add 3 '!' at the end of heisenberg and assign the new value to a variable d.

To see the solution, enter a valid code or purchase one:


String party 10: Flying pelican

const birdy = "   Flying pelican   ";
  1. Use a built-in JavaScript method to remove all white spaces at the start and the end of birdy and assign the new value to a variable a.
  2. Use a built-in JavaScript method to remove all white spaces only at the start of birdy and assign the new value to a variable b.
  3. Use a built-in JavaScript method to remove all white spaces only at the end of birdy and assign the new value to a variable c.

To see the solution, enter a valid code or purchase one:


String party 11: Talk that talk

const u = 'Talk ';
const v = 'that talk RiRi! '
  1. Concatenate strings u and v and assign the value to a new variable a1.
  2. Concatenate strings u and v in a different way and assign the value to a new variable a2.
  3. Use a built-in JavaScript method to concatenate string a 3 times and assign the value to a new variable b.

To see the solution, enter a valid code or purchase one:


String party 12: Kris Kross

const a = 'one-two-three';

const b = "one-\
two-\
three";

const c = `one-
two-
three`;

const d = "one-\ntwo-\nthree";

console.log(a === b);
console.log(b === c);
console.log(c === d);

What does the previous code print to the screen?

To see the solution, enter a valid code or purchase one:


String party 13: Mula baby

const love = '❤️❤️❤️';
const mula = '$$$';

console.log(love.length);
console.log(mula.length);

What does the previous code print to the screen and why is that?

To see the solution, enter a valid code or purchase one:


String party 14: Caffeine

const a = 'caf\u{e9}';
const b = 'cafe\u{301}';

console.log(a);
console.log(b);

If you run the previous code, you see the string 'café' logged twice on the screen. If we add console.log(a === b); at the end of the previous code, what would be displayed to the screen?

To see the solution, enter a valid code or purchase one:


Values and variables 01: alphabet gumbo 1

let [a, b] = [1];
const [c, d] = [2, 3, 4];
[a, b] = [b, a];

console.log(a);
console.log(b);
console.log(c);
console.log(d);

What does the previous code display to the screen?

To see the solution, enter a valid code or purchase one:


Values and variables 02: alphabet gumbo 2

let [e, ...f] = [5, 6, 7, 8];
let [...g] = ['Pluto'];
let [first, ...last] = 'abcd';

console.log(e);
console.log(f);
console.log(g);
console.log(first);
console.log(last);

What does the previous code display to the screen?

To see the solution, enter a valid code or purchase one:


Values and variables 03: colors

const color = {red: 0, green: 10, blue: 20, alpha: 1};
let { yellow, red, blue, alpha } = color;

console.log(yellow);
console.log(red);
console.log(blue);
console.log(alpha);

What does the previous code display to the screen?

To see the solution, enter a valid code or purchase one:


Values and variables 04: gangster love

let barrow_1 = 'Bonnie';
const barrow_2 = 'Clyde';

barrow_1 = 'Raymond';
console.log(barrow_1);

barrow_2 = 'Ralph';
console.log(barrow_2);

What does the previous code display to the screen?

To see the solution, enter a valid code or purchase one:


Values and variables 05: safari

What variable name is a valid name in JavaScript?

  1. 1elephant
  2. tallGiraffe_1
  3. $crocodile
  4. nice-athletic-camel
  5. wise_small_hippo
  6. zebra2
  7. new

To see the solution, enter a valid code or purchase one:


Values and variables 06: valuechella

const a = ['Giraffe', 10, false, null];
const [b, c, d, e] = a;
const f = a[4];

const g = function() {
  return true;
};

const h = { key_1: 1, key_2: 2 };
const i = Symbol.for('Have you ever used a Symbol?');
const j = 10n;

const values = [a, b, c, d, e, f, g, h, i, j];

for (let value of values) {
  console.log(typeof value);
}

What does the previous code display to the screen?

To see the solution, enter a valid code or purchase one:


Values and variables 07: gladiators

let dog = 'Spartacus';
let cat;

{
  let dog = 'Crixus';
  cat = 'Oenomaus';
  squirrel = 'Ashur';
}

const reassign = cat => cat = 'Barca';
const changeName = newDog => dog = 'Agron';

reassign(cat);
changeName(dog);

console.log(dog);
console.log(cat);
console.log(squirrel);

Without running it, what does the previous code print to the screen?

To see the solution, enter a valid code or purchase one:


Values and variables 08: what's new?

const object_1 = {
  a: 1,
  b: 2,
};

const object_2 = {
  a: 11,
  b: 22,
};

let {
  a: new_a,
  b: new_b,
} = object_1;

{
  a: new_a,
  b: new_b,
} = object_2;

console.log(new_a, new_b);

Without running it, what does the previous code print to the screen?

To see the solution, enter a valid code or purchase one:


Values and variables 09: who am I?

function displayArguments(
  first_name,
  last_name,
  {
    age,
    height,
    weight,
  }
) {
  console.log(first_name);
  console.log(last_name);
  console.log(age);
  console.log(height);
  console.log(weight);
}

displayArguments('Pamela', 'Isley')

Without running it, what does the previous code print to the screen?

To see the solution, enter a valid code or purchase one:


Non-blocking JS

let shouldContinue = true;

setTimeout(() => { shouldContinue = false; }, 200);
  
while(shouldContinue === true) {
  console.log('Looping, looping, looping...')
};

What does the previous code display to the screen?

To see the solution, enter a valid code or purchase one: