Skip to content

CyrusKabir/js-challenger

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

js challenger logo

Welcome ! 👋

Thanks for checking out this js-challenger solutions repo.

What is JSchallenger ? 🙂

JSchallenger is a cool and great site to practice most of the JS fundamentals and JS dom. It's a very helpful Javascript resource for beginners. JSchallenger created by Erik Kückelheim. thanks Erik.

Why this repo ? 😶

In this repo, you can find available solutions for a challenge.

Also for leetcode challenges you can check this repo : Leetcode solutions

Table of solutions

Javascript Basics :

  • variables

    • Reassign a value to a variable

      scenario :

      Assign a new value to the variable num. The code will not work the way it is. Find the 
      mistake and fix it. Execute the corrected code.

      code scenario :

      let num = 1;
      let num = 2;
      console.log(num);
      Solution 1

      js :

      let num = 1;
      num = 2;
      console.log(num);

      Back to table ⬆

    • Assign a value to a variable

      scenario :

      Here, we declare the variable num. But, it has no value yet. Assign a value to it and run 
      the code.

      code scenario :

      let num;
      console.log(num);
      Solution 1

      js :

      let num;
      num = 2;
      console.log(num);

      Back to table ⬆

    • Assign the value of another variable

      scenario :

      Here, we have two variables numOne and numTwo. numOne already has a value. Assign 
      numTwo the value of numOne and run the code.

      code scenario :

      let numOne = 5;
      let numTwo;
      console.log(numTwo);
      Solution 1

      js :

      let numOne = 5;
      let numTwo = numOne;
      console.log(numTwo);

      Back to table ⬆

    • Create the missing variable

      scenario :

      Below, we attempt to assign the value of a variable named numOne to the variable 
      numTwo. But, that variable has not been declared yet. Declare a variable named numOne 
      and run the code.

      code scenario :

      let numTwo = numOne;
      console.log(numTwo);
      Solution 1

      js :

      let numOne = 5;
      let numTwo = numOne;
      console.log(numTwo);

      Back to table ⬆

    • Accessing a variable 1

      scenario :

      In this simple exercise we declare a variable called num and assign it a value of 5. Then 
      we try to log the value of the variable using the console.log() method.
      But, the console.log() method contains a small mistake. If you try the run the code, you 
      will see an error message.
      Fix the mistake and run the code again.

      code scenario :

      const num = 5;
      console.log(Num);
      Solution 1

      js :

      const num = 5;
      console.log(num);

      Back to table ⬆

    • Accessing a variable 2

      scenario :

      This exercise is very similar to the previous one. We declare a variable called num, assign 
      it a value of 5, and try to log it. But again, we introduced a small mistake.
      Fix the code and run it.

      code scenario :

      console.log(num);
      const num = 5;
      Solution 1

      js :

      const num = 5;
      console.log(num);

      Back to table ⬆

    • Declare a variable and assign a number

      scenario :

      In this exercise we practice how to declare a new variable and how to assign it a number. 
      The console.log() statement below attempts to log a variable named num.
      Declare a variable with this name and assign it a number of your choice. Run the code to 
      see if the number is being logged.

      code scenario :

      console.log('The value of num is: ' + num);
      Solution 1

      js :

      const num = 5;
      console.log('The value of num is: ' + num);

      Back to table ⬆

    • Reassign a value to a variable 2

      scenario :

      Here again, we want to assign a new value to a variable that we previously declared. Again, the code will not work the way it is. Find the mistake and fix it. Execute the corrected code.

      code scenario :

      const text = 'hello';
      text = 'hello world';
      console.log(text);
      Solution 1

      js :

      let text = 'hello';
      text = 'hello world';
      console.log(text);

      Back to table ⬆

  • booleans

    • Assign boolean to a variable

      scenario :

      Here, we declare the variable isTrue. But, it has no value yet. Assign a boolean value to it and run the code.

      code scenario :

      let isTrue;
      
      console.log(isTrue);
      Solution 1

      js :

      let isTrue;
      isTrue = true;
      console.log(isTrue);

      Back to table ⬆

    • Convert Number to Boolean

      scenario :

      Here, we declare the variable num and assign it the value 5. We also declare the variable bool which we assign the boolean 
      representation of num.
      Extend the code such that the console.log() statement logs false.

      code scenario :

      let num = 5;
      
      const bool = Boolean(bool);
      console.log(bool);
      Solution 1

      js :

      let num = 5;
      num = 0;
      const bool = Boolean(bool);
      console.log(bool);

      Back to table ⬆

  • operators

    • Comparison operators - Equal

      scenario :

      In the console.log() statement below we use the Equal operator to check whether numOne and numTwo have the same value. Change the code so that the console.log() statement logs true.

      code scenario :

      const numOne = 5;
      const numTwo = 6;
      console.log(numOne == numTwo);
      Solution 1

      js :

      const numOne = 5;
      const numTwo = 5;
      console.log(numOne == numTwo);

      Back to table ⬆

    • Comparison operators - Not Equal

      scenario :

      In the console.log() statement below we use the Not Equal operator to check whether numOne and numTwo have different values. Change the code so that the console.log() statement logs true.

      code scenario :

      const numOne = 5;
      const numTwo = 5;
      console.log(numOne != numTwo);
      Solution 1

      js :

      const numOne = 5;
      const numTwo = 6;
      console.log(numOne != numTwo);

      Back to table ⬆

    • Comparison operators - Greater than

      scenario :

      In the console.log() statement below we use the Greater Than operator to check whether the value of numOne is greater than the value of numTwo. Change the code so that the console.log() statement logs true.

      code scenario :

      const numOne = 5;
      const numTwo = 6;
      console.log(numOne > numTwo);
      Solution 1

      js :

      const numOne = 6;
      const numTwo = 5;
      console.log(numOne > numTwo);

      Back to table ⬆

    • Comparison operators - Less than

      scenario :

      In the console.log() statement below we use the Less Than operator to check whether the value of numOne is less than the value of numTwo. Change the code so that the console.log() statement logs true.

      code scenario :

      const numOne = 2;
      const numTwo = 1;
      console.log(numOne < numTwo);
      Solution 1

      js :

      const numOne = 1;
      const numTwo = 2;
      console.log(numOne < numTwo);

      Back to table ⬆

    • Comparison operators - Greater than or equal

      scenario :

      In the console.log() statement below we use the Greater Than Or Equal operator to check whether the value of numOne is greater than or equal the value of numTwo. It also checks whether the value of numTwo is greater than or equal the value of numThree. Change the code so that both expressions in the console.log() statement logs true.

      code scenario :

      const numOne = 3;
      const numTwo = 4;
      const numThree = 2;
      console.log(numOne >= numTwo, numTwo >= numThree);
      Solution 1

      js :

      const numOne = 3;
      const numTwo = 2;
      const numThree = 2;
      console.log(numOne >= numTwo, numTwo >= numThree);

      Back to table ⬆

    • Comparison operators - Less than or equal

      scenario :

      In the console.log() statement below we use the Less Than Or Equal operator to check whether the value of numOne is less than or equal the value of numTwo. It also checks whether the value of numTwo is less than or equal the value of numThree. Change the code so that both expressions in the console.log() statement logs true.

      code scenario :

      const numOne = 1;
      const numTwo = 4;
      const numThree = 2;
      console.log(numOne <= numTwo, numTwo <= numThree);
      Solution 1

      js :

      const numOne = 1;
      const numTwo = 1;
      const numThree = 2;
      console.log(numOne <= numTwo, numTwo <= numThree);

      Back to table ⬆

  • strings

    • Create a Javascript string

      scenario :

      In this exercise the existing console.log() statement logs the value of the variable text. The variable text has already been declared with an empty stringas indicated by the two single quotes.
      Fill in the string with some characters and run the code to see if the string is being logged.

      code scenario :

      const text = '';
      console.log('The value of text is: ' + text);
      Solution 1

      js :

      const text = 'hello world';
      console.log('The value of text is: ' + text);

      Back to table ⬆

    • Different ways to create Javascript strings

      scenario :

      Here, we have declared 3 variables textOne, textTwo, and textThree. An empty string is assigned to all of them.
      Do you see how in each case different symbols are used to create the string? All three of them are valid methods to create a JavaScript string.
      Fill in all 3 strings with some characters and run the code to see if the values get logged.In this exercise the existing console.log() statement logs the value of the variable text. The variable text has already been declared with an empty stringas indicated by the two single quotes.
      Fill in the string with some characters and run the code to see if the string is being logged.

      code scenario :

      const textOne = '';
      const textTwo = "";
      const textThree = ``;
      console.log(textOne, textTwo, textThree);
      Solution 1

      js :

      const textOne = 'Hello, ';
      const textTwo = "it's ";
      const textThree = `me`;
      console.log(textOne, textTwo, textThree);

      Back to table ⬆

    • Connect Javascript strings 1

      scenario :

      After we have learnt how to create JavaScript strings, we will now connect 2 strings together. In the code below we use the Addition (+) operator to concatenate textOne and textTwo. The console.log() statement logs the resulting string. Currently, the result would be HelloWorld.
      Change the code below so that the value of res is Hello World

      code scenario :

      const textOne = 'Hello';
      const textTwo = 'World';
      const combined = textOne + textTwo;
      console.log(combined);
      Solution 1

      js :

      const textOne = 'Hello';
      const textTwo = 'World';
      const combined = textOne + ' ' + textTwo;
      console.log(combined);

      Back to table ⬆

  • conditionals

    • if statement - satisfy condition

      scenario :

      In this exercise we will work with our first if-statement. In the code below we declare a variable num with a value 0. Then, we have an if-statement. The if-statement consists of a conditionthe part inside the parenthesesand some code inside a pair of curly braces. The code will assign the variable num a new value 1. But it will only run if the condition is met.
      Adjust the condition such that the code inside the curly braces will execute and the console.log() statement logs true.

      code scenario :

      let num = 0;
      if (1 > 2) {
         num = 1;
      }
      console.log(num === 1);
      Solution 1

      js :

      let num = 0;
      if (1 < 2) {
         num = 1;
      }
      console.log(num === 1);

      Back to table ⬆

    • if statement - add missing condition

      scenario :

      Time to practice what we've learnt so far. In the code below, the if...statement will assign a new value to the variable text. But only if its condition is met. Currently, the condition is missing.
      Add any condition that will be satisfied such that the console.log() statement logs true.

      code scenario :

      let text = 'hello';
      if () {
         text = text + ' world';
      }
      console.log(text === 'hello world');
      Solution 1

      js :

      let text = 'hello';
      if (text === 'hello') {
         text = text + ' world';
      }
      console.log(text === 'hello world');

      Back to table ⬆

  • functions I

    • Function declaration

      scenario :

      In this exercise we will work with our first JavaScript function. In the code below we create a function named func. This way of creating functions is called function declaration: the keyword function followed by the name of the function and a pair of parentheses. Then follows some JavaScript code wrapped by curly braces.
      Notice that we use the return keyword to make the function return a value, in this case a string.
      When we create a function in JavaScript, the statement inside the curly braces is exectued only when the function is called. You can call a function by using its name and a pair of parentheses func().
      Below, we call our function and assign its return value to the variable result. Then, we log the result. To solve this exercise simply have the console.log() statement log the words hello world.

      code scenario :

      function func() {
          return 'hello';
      };
      const result = func();
      console.log(result);
      Solution 1

      js :

      function func() {
          return 'hello world';
      };
      const result = func();
      console.log(result);

      Back to table ⬆

    • Function expression

      scenario :

      In this exercise, we use a slightly different way to create a functiona function expression. Here, we create a function and assign it to the variable func. Notice that we omit the name of the function after the function keyword. We call this function the same way as in the previous exercise. But, instead of using the name of the function itself, we call it using the name of the variable to which the function was assigned.
      In the code below, we introduced a small mistake when calling the function. Find the mistake and run the code to see if the words hello world are correctly logged.

      code scenario :

      const func = function() {
          return 'hello world';
      };
      const result = func;
      console.log(result);
      Solution 1

      js :

      const func = function() {
          return 'hello world';
      };
      const result = func();
      console.log(result);

      Back to table ⬆

    • Correctly return value from function 1

      scenario :

      In this exercise, we create a function func. Then, we call func and assign its return value to the variable result.
      When you run the code like this, you see that the value undefined is logged. This is the current return value of func because we do not explicitly define a return value ourselfs.
      Let func return the value of the variable text.

      code scenario :

      const func = function() {
          let text = 'hello';
          text = text + ' world';
      };
      const result = func();
      console.log(result);
      Solution 1

      js :

      const func = function() {
          let text = 'hello';
          text = text + ' world';
          return text;
      };
      const result = func();
      console.log(result);

      Back to table ⬆

    • Correctly return value from function 2

      scenario :

      In this exercise, func declares a variable text with the value hello. Then it returns the value of text. After that, it assigns a new value hello world to the variable text and returns the new value.
      But, when you run the code, you see that only the initial value of text (hello) is logged. This is because once a function call reaches a return statement, further function execution is stopped. All code after the return statement is ignored.
      Adjust the code so that the final value of text is logged.

      code scenario :

      const func = function () {
          let text = 'hello';
          return text;
          text = text + ' world';
          return text;
      };
      const result = func();
      console.log(result);
      Solution 1

      js :

      const func = function () {
          let text = 'hello';
          text = text + ' world';
          return text;
      };
      const result = func();
      console.log(result);

      Back to table ⬆

  • arrays

  • loops

  • asynchronous javascript

    • Execute the code synchronously

      scenario :

      Adjust the code snippet so that the console.log statement logs the value 2.

      code scenario :

      let i = 0;
      function func() {
       i = 2;
      }
      setTimeout(func, 100)
      // expected output = 2
      console.log(i);
      Solution 1

      js :

      let i = 0;
      function func() {
       i = 2;
      }
      func();
      // expected output = 2
      console.log(i);

      Back to table ⬆

    • Execute the code asynchronously

      scenario :

      Adjust the code snippet so that the value 0 is logged first and then the value 1.

      code scenario :

      let count = 0;
      function increment() {
       count = count + 1;
      }
      increment();
      setTimeout(() => {
      
        console.log(count);
      }, 1000);
      
      console.log(count);
      Solution 1

      js :

      let count = 0;
      function increment() {
       count = count + 1;
      }
      setTimeout(() => {
        increment();
        console.log(count);
      }, 1000);
      
      console.log(count);

      Back to table ⬆

Javascript Practice :

  • Javascript fundamentals

    • Sum two numbers

      scenario :

      Write a function that takes two numbers (a and b) as argument
      Sum a and b
      Return the result

      code scenario :

      function myFunction(a, b) {
          return 
      }
      Solution 1

      js :

      function myFunction(a, b) {
          return a + b;
      }

      Back to table ⬆

    • Comparison operators, strict equality

      scenario :

      Write a function that takes two values, say a and b, as arguments
      Return true if the two values are equal and of the same type

      code scenario :

      function myFunction(a, b) {
          return 
      }
      Solution 1

      js :

      function myFunction(a, b) {
          return a === b;
      }

      Back to table ⬆

    • Get type of value

      scenario :

      Write a function that takes a value as argument
      Return the type of the value

      code scenario :

      function myFunction(a) {
          return 
      }
      Solution 1

      js :

      function myFunction(a) {
          return typeof a;
      }

      Back to table ⬆

    • Get nth character of string

      scenario :

      Write a function that takes a string (a) and a number (n) as argument
      Return the nth character of 'a'

      code scenario :

      function myFunction(a, n) {
          return 
      }
      Solution 1

      js :

      function myFunction(a, n) {
          return a[n - 1];
      }

      Back to table ⬆

    • Remove first n characters of string

      scenario :

      Write a function that takes a string (a) as argument
      Remove the first 3 characters of a
      Return the result

      code scenario :

      function myFunction(a) {
          return 
      }
      Solution 1

      js :

      function myFunction(a) {
          return a.slice(3);
      }

      Back to table ⬆

    • Get first n characters of string

      scenario :

      Write a function that takes a string (a) as argument
      Get the first 3 characters of a
      Return the result

      code scenario :

      function myFunction(a) {
          return 
      }
      Solution 1

      js :

      function myFunction(a) {
          return a.slice(0, 3);
      }

      Back to table ⬆

    • Find the position of one string in another

      scenario :

      Write a function that takes a string as argument
      The string contains the substring 'is'
      Return the index of 'is'

      code scenario :

      function myFunction(a) {
          return 
      }
      Solution 1

      js :

      function myFunction(a) {
          return a.indexOf('is');
      }

      Back to table ⬆

    • Extract first half of string

      scenario :

      Write a function that takes a string (a) as argument
      Extract the first half a
      Return the result

      code scenario :

      function myFunction(a) {
          return 
      }
      Solution 1

      js :

      function myFunction(a) {
          return a.slice(0, a.length / 2);
      }

      Back to table ⬆

    • Remove last n characters of string

      scenario :

      Write a function that takes a string (a) as argument
      Remove the last 3 characters of a
      Return the result

      code scenario :

      function myFunction(a) {
          return 
      }
      Solution 1

      js :

      function myFunction(a) {
          return a.slice(0, -3);
      }

      Back to table ⬆

    • Return the percentage of a number

      scenario :

      Write a function that takes two numbers (a and b) as argument
      Return b percent of a

      code scenario :

      function myFunction(a, b) {
          return 
      }
      Solution 1

      js :

      function myFunction(a, b) {
          return b / 100 * a
      }

      Back to table ⬆

    • Basic JavaScript math operators

      scenario :

      Write a function that takes 6 values (a,b,c,d,e,f) as arguments
      Sum a and b
      Then substract by c
      Then multiply by d and divide by e
      Finally raise to the power of f and return the result
      Tip: mind the order

      code scenario :

      function myFunction(a, b, c, d, e, f) {
          return 
      }
      Solution 1

      js :

      function myFunction(a, b, c, d, e, f) {
          return (((a + b - c) * d) / e) ** f;
      }

      Back to table ⬆

    • Check whether a string contains another string and concatenate

      scenario :

      Write a function that takes two strings (a and b) as arguments. If a contains b, append b to the 
      beginning of a. If not, append it to the end. Return the concatenation

      code scenario :

      function myFunction(a, b) {
          return 
      }
      Solution 1

      js :

      function myFunction(a, b) {
          return a.indexOf(b) === -1 ? a + b : b + a
      }

      Solution 2

      js :

      function myFunction(a, b) {
          return a.includes(b) ? `${b}${a}` : `${a}${b}`
      }

      Back to table ⬆

    • Check if a number is even

      scenario :

      Write a function that takes a number as argument. If the number is even, return true. Otherwise, 
      return false

      code scenario :

      function myFunction(a) {
          return 
      }
      Solution 1

      js :

      function myFunction(a) {
          return a % 2 === 0
      }

      Back to table ⬆

    • How many times does a character occur?

      scenario :

      Write a function that takes two strings (a and b) as arguments. Return the number of times a occurs in 
      b.

      code scenario :

      function myFunction(a, b) {
          return 
      }
      Solution 1

      js :

      function myFunction(a, b) {
          return b.split(a).length - 1
      }

      Back to table ⬆

    • Check if a number is a whole number

      scenario :

      Write a function that takes a number (a) as argument. If a is a whole number (has no decimal place), 
      return true. Otherwise, return false.

      code scenario :

      function myFunction(a) {
          return 
      }
      Solution 1

      js :

      function myFunction(a) {
          return a - Math.floor(a) === 0
      }

      Solution 2

      js :

      function myFunction(a) {
          return parseInt(a) === a
      }

      Back to table ⬆

    • Multiplication, division, and comparison operators

      scenario :

      Write a function that takes two numbers (a and b) as arguments. If a is smaller than b, divide a by b. 
      Otherwise, multiply both numbers. Return the resulting value

      code scenario :

      function myFunction(a, b) {
          return 
      }
      Solution 1

      js :

      function myFunction(a, b) {
          return a < b ? a / b : a * b
      }

      Back to table ⬆

    • Round a number to 2 decimal places

      scenario :

      Write a function that takes a number (a) as argument. Round a to the 2nd digit after the comma. 
      Return the rounded number

      code scenario :

      function myFunction(a) {
          return 
      }
      Solution 1

      js :

      function myFunction(a) {
          return Number(a.toFixed(2));
      }

      Back to table ⬆

    • Split a number into its digits

      scenario :

      Write a function that takes a number (a) as argument. Split a into its individual digits and return 
      them in an array. Tipp: you might want to change the type of the number for the splitting

      code scenario :

      function myFunction( a ) {
          return 
      }
      Solution 1

      js :

      function myFunction( a ) {
          const string = a + '';
          const strings = string.split('');
          return strings.map(digit => Number(digit))
      }

      Solution 2

      js :

      function myFunction(a) {
          return a.toString()
                  .split('')
                  .map(charNum => parseInt(charNum))
      }

      Back to table ⬆

  • Javascript arrays

    • Get nth element of array

      scenario :

      Write a function that takes an array (a) and a value (n) as argument. Return the nth element of 'a'

      code scenario :

      function myFunction(a, n) {
          return 
      }
      Solution 1

      js :

      function myFunction(a, n) {
          return a[n - 1];
      }

      Back to table ⬆

    • Remove first n elements of an array

      scenario :

      Write a function that takes an array (a) as argument. Remove the first 3 elements of 'a'. Return the 
      result

      code scenario :

      function myFunction(a) {
          return 
      }
      Solution 1

      js :

      function myFunction(a) {
          return a.slice(3);
      }

      Back to table ⬆

    • Get last n elements of an array

      scenario :

      Write a function that takes an array (a) as argument. Extract the last 3 elements of 'a'. Return the 
      resulting array

      code scenario :

      function myFunction(a) {
          return 
      }
      Solution 1

      js :

      function myFunction(a) {
          return a.slice(-3);
      }

      Back to table ⬆

    • Get first n elements of an array

      scenario :

      Write a function that takes an array (a) as argument. Extract the first 3 elements of a. Return the 
      resulting array

      code scenario :

      function myFunction(a) {
          return 
      }
      Solution 1

      js :

      function myFunction(a) {
          return a.slice(0, 3);
      }

      Back to table ⬆

    • Return last n array elements

      scenario :

      Write a function that takes an array (a) and a number (n) as arguments. It should return the last n 
      elements of a.

      code scenario :

      function myFunction(a, n) {
          return 
      }
      Solution 1

      js :

      function myFunction(a, n) {
          return a.slice(-n);
      }

      Back to table ⬆

    • Remove a specific array element

      scenario :

      Write a function that takes an array (a) and a value (b) as argument. The function should remove all 
      elements equal to 'b' from the array. Return the filtered array.

      code scenario :

      function myFunction( a, b ) {
          return 
      }
      Solution 1

      js :

      function myFunction( a, b ) {
          return a.filter(arrItem => arrItem !== b)
      }

      Back to table ⬆

    • Count number of elements in JavaScript array

      scenario :

      Write a function that takes an array (a) as argument. Return the number of elements in a.

      code scenario :

      function myFunction(a) {
          return 
      }
      Solution 1

      js :

      function myFunction(a) {
          return a.length;
      }

      Back to table ⬆

    • Count number of negative values in array

      scenario :

      Write a function that takes an array of numbers as argument. Return the number of negative values 
      in the array.

      code scenario :

      function myFunction(a) {
          return 
      }
      Solution 1

      js :

      function myFunction(a) {
          return a.filter((el) => el < 0).length;
      }

      Solution 2

      js :

      function myFunction(a) {
          const isNegative = num => num < 0;
          return a.filter(isNegative).length;
      }

      Back to table ⬆

    • Sort an array of strings alphabetically

      scenario :

      Write a function that takes an array of strings as argument. Sort the array elements alphabetically. 
      Return the result.

      code scenario :

      function myFunction(arr) {
          return 
      }
      Solution 1

      js :

      function myFunction(arr) {
          return arr.sort();
      }

      Back to table ⬆

    • Sort an array of numbers in descending order

      scenario :

      Write a function that takes an array of numbers as argument. It should return an array with the 
      numbers sorted in descending order.

      code scenario :

      function myFunction( arr ) {
          return 
      }
      Solution 1

      js :

      function myFunction( arr ) {
          // > 0 => sort a after b
          // < 0 => sort a before b
          // === 0 => keep original order of a and b
          return arr.sort((a, b) => b - a)
      }

      Back to table ⬆

    • Calculate the sum of an array of numbers

      scenario :

      Write a function that takes an array of numbers as argument. It should return the sum of the 
      numbers.

      code scenario :

      function myFunction(a) {
          return 
      }
      Solution 1

      js :

      function myFunction(a) {
          return a.reduce((acc, cur) => acc + cur, 0);
      }

      Back to table ⬆

    • Return the average of an array of numbers

      scenario :

      Write a function that takes an array of numbers as argument. It should return the average of the 
      numbers.

      code scenario :

      function myFunction( arr ) {
          return 
      }
      Solution 1

      js :

      function myFunction( arr ) {
          return arr.reduce((acc, cur) => acc + cur, 0) / arr.length
      }

      Back to table ⬆

    • Return the longest string from an array of strings

      scenario :

      Write a function that takes an array of strings as argument. Return the longest string.

      code scenario :

      function myFunction( arr ) {
          return 
      }
      Solution 1

      js :

      function myFunction( arr ) {
          return arr.reduce((a, b) => a.length <= b.length ? b : a)
      }

      Back to table ⬆

    • Check if all array elements are equal

      scenario :

      Write a function that takes an array as argument. It should return true if all elements in the array are 
      equal. It should return false otherwise.

      code scenario :

      function myFunction( arr ) {
          return 
      }
      Solution 1

      js :

      function myFunction( arr ) {
          return new Set(arr).size === 1;
      }

      Back to table ⬆

    • Merge an arbitrary number of arrays

      scenario :

      Write a function that takes arguments an arbitrary number of arrays. It should return an array 
      containing the values of all arrays.

      code scenario :

      function myFunction(...arrays) {
          return 
      }
      Solution 1

      js :

      function myFunction(...arrays) {
          return arrays.flat();
      }

      Back to table ⬆

    • Sort array by object property

      scenario :

      Write a function that takes an array of objects as argument. Sort the array by property b in ascending 
      order. Return the sorted array

      code scenario :

      function myFunction(arr) {
          return 
      }
      Solution 1

      js :

      function myFunction(arr) {
          // > 0 => sort a after b
          // < 0 => sort a before b
          // === 0 => keep original order of a and b
          const sort = (x, y) => x.b - y.b;
          return arr.sort(sort);
      }

      Back to table ⬆

    • Merge two arrays with duplicate values

      scenario :

      Write a function that takes two arrays as arguments. Merge both arrays and remove duplicate values. 
      Sort the merge result in ascending order. Return the resulting array

      code scenario :

      function myFunction(a, b) {
          return 
      }
      Solution 1

      js :

      function myFunction(a, b) {
          return [...new Set([...a, ...b])].sort((x, y) => x - y);
      }

      Solution 2

      js :

      function myFunction(a, b) {
          let merged = a.concat(b);
          let noDuplicate = Array.from(new Set(merged));
          let sorted = noDuplicate.sort((a, b) => a - b);
          return sorted;
      }

      Back to table ⬆

  • Javascript objects

    • Accessing object properties one

      scenario :

      Write a function that takes an object with two properties as argument. It should return the value of 
      the property with key country.

      code scenario :

      function myFunction(obj) {
          return 
      }
      Solution 1

      js :

      function myFunction(obj) {
          return obj.country;
      }

      Back to table ⬆

    • Accessing object properties two

      scenario :

      Write a function that takes an object with two properties as argument. It should return the value of 
      the property with key 'prop-2'. Tipp: you might want to use the square brackets property accessor

      code scenario :

      function myFunction(obj) {
          return 
      }
      Solution 1

      js :

      function myFunction(obj) {
          return obj['prop-2'];
      }

      Back to table ⬆

    • Accessing object properties three

      scenario :

      Write a function that takes an object with two properties and a string as arguments. It should return 
      the value of the property with key equal to the value of the string

      code scenario :

      function myFunction(obj, key) {
          return 
      }
      Solution 1

      js :

      function myFunction(obj, key) {
          return obj[key]
      }

      Back to table ⬆

    • Check if property exists in object

      scenario :

      Write a function that takes an object (a) and a string (b) as argument. Return true if the object has a 
      property with key 'b'. Return false otherwise. Tipp: test case 3 is a bit tricky because the value of 
      property 'z' is undefined. But the property itself exists.

      code scenario :

      function myFunction(a, b) {
          return 
      }
      Solution 1

      js :

      function myFunction(a, b) {
          // The in operator returns true if the specified property is in 
          // the object or its prototype chain.
          return b in a;
      }

      Back to table ⬆

    • Check if property exists in object and is truthy

      scenario :

      Write a function that takes an object (a) and a string (b) as argument. Return true if the object has a 
      property with key 'b', but only if it has a truthy value. In other words, it should not be null or 
      undefined or false. Return false otherwise.

      code scenario :

      function myFunction(a, b) {
          return 
      }
      Solution 1

      js :

      function myFunction(a, b) {
          return Boolean(a[b]);
      }

      Solution 2

      js :

      function myFunction(a, b) {
          return a[b] ? true : false;
      }

      Back to table ⬆

    • Creating Javascript objects one

      scenario :

      Write a function that takes a string as argument. Create an object that has a property with key 'key' 
      and a value equal to the string. Return the object.

      code scenario :

      function myFunction(a) {
          return 
      }
      Solution 1

      js :

      function myFunction(a) {
          return { key: a }
      }

      Back to table ⬆

    • Creating Javascript objects two

      scenario :

      Write a function that takes two strings (a and b) as arguments. Create an object that has a property 
      with key 'a' and a value of 'b'. Return the object.

      code scenario :

      function myFunction(a, b) {
          return 
      }
      Solution 1

      js :

      function myFunction(a, b) {
          return { [a]: b }
      }

      Back to table ⬆

    • Creating Javascript objects three

      scenario :

      WWrite a function that takes two arrays (a and b) as arguments. Create an object that has properties 
      with keys 'a' and corresponding values 'b'. Return the object.

      code scenario :

      function myFunction(a, b) {
          return 
      }
      Solution 1

      js :

      function myFunction(a, b) {
          return a.reduce((acc, cur, i) => ({ ...acc, [cur]: b[i] }), {})
      }

      Back to table ⬆

    • Extract keys from Javascript object

      scenario :

      Write a function that takes an object (a) as argument. Return an array with all object keys.

      code scenario :

      function myFunction(a) {
          return 
      }
      Solution 1

      js :

      function myFunction(a) {
          return Object.keys(a);
      }

      Back to table ⬆

    • Return nested object property

      scenario :

      Write a function that takes an object as argument. In some cases the object contains other objects 
      with some deeply nested properties. Return the property 'b' of object 'a' inside the original object if it 
      exists. If not, return undefined

      code scenario :

      function myFunction(obj) {
          return 
      }
      Solution 1

      js :

      function myFunction(obj) {
          return obj?.a?.b;
      }

      Solution 2

      js :

      function myFunction(obj) {
          return obj.a && obj.a.b ? obj.a.b : undefined
      }

      Back to table ⬆

    • Sum object values

      scenario :

      Write a function that takes an object (a) as argument. Return the sum of all object values.

      code scenario :

      function myFunction(a) {
          return 
      }
      Solution 1

      js :

      function myFunction(a) {
          return Object.values(a).reduce((sum, cur) => sum + cur, 0);
      }

      Back to table ⬆

    • Remove a property from an object

      scenario :

      Write a function that takes an object as argument. It should return an object with all original object 
      properties. except for the property with key 'b'

      code scenario :

      function myFunction(obj) {
          return 
      }
      Solution 1

      js :

      function myFunction(obj) {
          const { b, ...rest } = obj;
          return rest;
      }

      Solution 2

      js :

      function myFunction(obj) {
          if("b" in obj) {
              return delete obj.b && obj;
          }
      }

      Back to table ⬆

    • Merge two objects with matching keys

      scenario :

      Write a function that takes two objects as arguments. Unfortunately, the property 'b' in the second 
      object has the wrong key. It should be named 'd' instead. Merge both objects and correct the wrong 
      property name. Return the resulting object. It should have the properties 'a', 'b', 'c', 'd', and 'e'

      code scenario :

      function myFunction(x, y) {
          return 
      }
      Solution 1

      js :

      function myFunction(x, y) {
          const {b, ...rest} = y;
          return {...x, ...rest, d: b};
      }

      Solution 2

      js :

      function myFunction(x, y) {
          y.d = y.b;
          delete y.b;
          return {...x, ...y};
      }

      Back to table ⬆

    • Multiply all object values by x

      scenario :

      Write a function that takes an object (a) and a number (b) as arguments. Multiply all values of 'a' by 
      'b'. Return the resulting object.

      code scenario :

      function myFunction(a, b) {
          return 
      }
      Solution 1

      js :

      function myFunction(a, b) {
          return Object.entries(a).reduce((acc, [key, val]) => {
              return { ...acc, [key]: val * b };
          }, {});
      }

      Back to table ⬆

  • Javascript dates

    • Check if two dates are equal

      scenario :

      Sounds easy, but you need to know the trick. Write a function that takes two date instances as 
      arguments. It should return true if the dates are equal. It should return false otherwise.

      code scenario :

      function myFunction(a, b) {
          return 
      }
      Solution 1

      js :

      function myFunction(a, b) {
          return a.getTime() === b.getTime();
      }

      Solution 2

      js :

      function myFunction(a, b) {
          return a - b === 0;
      }

      Back to table ⬆

    • Return the number of days between two dates

      scenario :

      Write a function that takes two date instances as argument. It should return the number of days that 
      lies between those dates.

      code scenario :

      function myFunction(a, b) {
          return 
      }
      Solution 1

      js :

      function myFunction(a, b) {
          const dif = Math.abs(a - b);
          return dif / 1000 / 60 / 60 / 24
      }

      Solution 2

      js :

      functiion myFunction(a, b) {
          return Math.abs( (a.getTime() / 86400000) - (b.getTime() / 86400000) )
      }

      Back to table ⬆

    • Check if two dates fall on the exact same day

      scenario :

      Write a function that takes two date instances as argument. It should return true if they fall on the 
      exact same day. It should return false otherwise.

      code scenario :

      function myFunction(a, b) {
          return 
      }
      Solution 1

      js :

      function myFunction(a, b) {
          return a.getFullYear() === b.getFullYear() &&
                 a.getMonth() === b.getMonth() &&
                 a.getDate()=== b.getDate()
      }

      Back to table ⬆

    • Check if two dates are within 1 hour from each other

      scenario :

      Write a function that takes two date instances as argument. It should return true if the difference between the dates is less 
      than or equal to 1 hour. It should return false otherwise.

      code scenario :

      function myFunction(a, b) {
          return 
      }
      Solution 1

      js :

      function myFunction(a, b) {
          return Math.abs(a - b) / 1000 / 60 <= 60
      }

      Solution 2

      js :

      function myFunction(a, b) {
          const timeDiffLimitInMinutes = 60;
          let firstDateTime = a.getTime();
          let secondDateTime = b.getTime();
          let timeDiffInMiliSeconds = Math.abs(firstDateTime - secondDateTime);
          let timeDiffInMinutes = timeDiffInMiliSeconds / 60000;
      
          if(timeDiffInMinutes > timeDiffLimitInMinutes) return false;
          return true;
      }

      Back to table ⬆

    • Check if one date is earlier than another

      scenario :

      Write a function that takes two date instances (a and b) as arguments. It should return true if a is earlier than b. It should 
      return false otherwise.

      code scenario :

      function myFunction(a, b) {
          return 
      }
      Solution 1

      js :

      function myFunction(a, b) {
          return a < b
      }

      Back to table ⬆

  • Javascript Sets

    • Check if value is present in Set

      scenario :

      Write a function that takes a Set and a value as arguments. Check if the value is present in 
      the Set

      code scenario :

      function myFunction(set, val) {
          return 
      }
      Solution 1

      js :

      function myFunction(set, val) {
          return set.has(val);
      }

      Back to table ⬆

    • Convert a Set to Array

      scenario :

      Write a function that takes a Set as argument. Convert the Set to an Array. Return the Array

      code scenario :

      function myFunction(set) {
          return 
      }
      Solution 1

      js :

      function myFunction(set) {
          return [...set];
      }

      Back to table ⬆

    • Get union of two sets

      scenario :

      Write a function that takes two Sets as arguments. Create the union of the two sets. Return 
      the result. Tipp: try not to switch to Arrays, this would slow down your code

      code scenario :

      function myFunction(a, b) {
          return 
      }
      Solution 1

      js :

      function myFunction(a, b) {
          const result = new Set(a);
          b.forEach((el) => result.add(el));
          return result;
      }

      Back to table ⬆

    • Creating Javascript Sets

      scenario :

      Write a function that takes three elements of any type as arguments. Create a Set from 
      those elements. Return the result

      code scenario :

      function myFunction(a, b, c) {
          return 
      }
      Solution 1

      js :

      function myFunction(a, b, c) {
          const set = new Set();
          set.add(a);
          set.add(b);
          set.add(c);
          return set;
      }

      Back to table ⬆

    • Delete element from Set

      scenario :

      Write a function that takes a Set and a value as argument. If existing in the Set, remove the 
      value from the Set. Return the result

      code scenario :

      function myFunction(set, val) {
          return 
      }
      Solution 1

      js :

      function myFunction(set, val) {
          set.delete(val);
          return set;
      }

      Solution 2

      js :

      function myFunction(set, val) {
          return set.has(val) ? set.delete(val) && set : set;
      }

      Back to table ⬆

Javascript DOM :

  • DOM selector methods

    • Select the button element on the page

      scenario :

      In this scenario, the existing code adds an eventListener for a click event on a variable buttonElem. It expects buttonElem to be the button element in the example UI. But, that element is not selected yet.
      Assign the button element to the variable buttonElem. Click the button to verify that the code is working.
      Hint: Make use of the unique id of the button element.

      html :

      <button type="button" id="button">OFF</button>

      code scenario :

      const buttonElem = 
      
      buttonElem.addEventListener('click', () => {
        const oldText = buttonElem.innerText;
        return button.innerText = oldText === "ON" ? "OFF" : "ON";
      });
      Solution 1

      js :

      const buttonElem = document.getElementById("button");
      
      buttonElem.addEventListener('click', () => {
        const oldText = buttonElem.innerText;
        return button.innerText = oldText === "ON" ? "OFF" : "ON";
      });

      Back to table ⬆

    • Query descendent HTML elements

      scenario :

      Here, the existing code expects the variables 'buttonElem' and 'inputElem' to represent the button and input elements in the example UI.
      Assign the respective elements to the variables.
      In this case, the two elements do not have unique identifiers - like for example an id. Instead they are direct descendents of a div element with id 'wrapper'. Use an appropriate selector method!
      Click the button to verify that the code is working.

      html :

      <div id="wrapper">
          <input type="text" value="OFF" readonly/>
          <button type="button">Click Me</button>
      </div>

      code scenario :

      const buttonElem = 
      const inputElem = 
      
      buttonElem.addEventListener('click', () => {
        const oldText = inputElem.value;
          return inputElem.value = oldText === "ON" ? "OFF" : "ON";
      });
      Solution 1

      js :

      const buttonElem = document.querySelector("#wrapper button");
      const inputElem = document.querySelector("#wrapper input");
      
      buttonElem.addEventListener('click', () => {
        const oldText = inputElem.value;
          return inputElem.value = oldText === "ON" ? "OFF" : "ON";
      });

      Back to table ⬆

    • Select multiple HTML elements

      scenario :

      In this scenario, we are looking for a list of elements gathered in one variable - rather than only one element.
      Assign the list items in the view to the variable 'listItems' by using an appropriate selector method.
      Once you have completed the code below, verify it by hovering over the list items until all items have the value 'ON'

      html :

      <ul id="list">
          <li>OFF</li>
          <li>OFF</li>
          <li>OFF</li>
          <li>OFF</li>
          <li>OFF</li>
          <li>OFF</li>
      </ul>

      code scenario :

      const listItems = 
      
      const handleHover = (event) => {
        return event.target.innerText = 'ON';
      };
      
      if(listItems.length > 1) {
        listItems.forEach(item => item.addEventListener('mouseover', handleHover));
      }
      Solution 1

      js :

      const listItems = document.querySelectorAll("#list li");
      
      const handleHover = (event) => {
        return event.target.innerText = 'ON';
      };
      
      if(listItems.length > 1) {
        listItems.forEach(item => item.addEventListener('mouseover', handleHover));
      }

      Back to table ⬆

  • Events and user interactions

    • Execute function on button click

      scenario :

      The Javascript function handleText fills the input field with the words Hello World. But, there is no code to execute this function.
      Complete the existing code below such that the function is called when the button is clicked. Verify by clicking the button.

      html :

      <input type="text" id="input" readonly/>
      <button type="button" id="button">Click Me</button>

      code scenario :

      const button = document.getElementById('button');
      const input = document.getElementById('input');
      
      const handleClick = () => {
        input.value = 'Hello World';
      };
      Solution 1

      js :

      const button = document.getElementById('button');
      const input = document.getElementById('input');
      
      const handleClick = () => {
        input.value = 'Hello World';
      };
      
      button.addEventListener('click', handleClick);

      Back to table ⬆

    • Execute function when cursor moves onto element

      scenario :

      The Javascript function changeText changes the text inside the circle. But again, there is no code to execute this function.
      Complete the existing code below such that the function is called when the cursor moves onto the circle. Verify that your code works by hovering over the circle.

      html :

      <div id="element">
          Hover Me
      </div>

      code scenario :

      const element = document.getElementById('element');
      
      const changeText = () => {
        element.innerText = 'Thanks!';
      };
      Solution 1

      js :

      const element = document.getElementById('element');
      
      const changeText = () => {
        element.innerText = 'Thanks!';
      };
      
      element.addEventListener("mouseover", changeText);

      Back to table ⬆

    • Cursor enters and leaves element

      scenario :

      In this scenario we want the color of the circle to change depending on the type of cursor movement. Use the function toggleColor to turn the circle orange when the cursor moves onto it. Reuse the same function to turn it black when the cursor leaves it.
      The tricky part is that you have to call toggleColor with different values for the parameter isEntering. Verify that your code is working by hovering the circle with the mouse cursor and leaving it again.

      html :

      <div id="element">
          Hover Me
      </div>

      code scenario :

      const element = document.querySelector('#element');
      
      const toggleColor = (isEntering) => {
        element.style.background = isEntering ? 'orange' : 'black';
      };
      Solution 1

      js :

      const element = document.querySelector('#element');
      
      const toggleColor = (isEntering) => {
        element.style.background = isEntering ? 'orange' : 'black';
      };
      
      element.addEventListener('mouseover', () => toggleColor(true));
      element.addEventListener('mouseleave', () => toggleColor(false));

      Back to table ⬆

  • DOM manipulation

    • Remove element from the DOM

      scenario :

      You may not see it in the example UI, but underneath the red circle is a green circle. Extend the function removeRedCircle to remove the circle with id red from the DOM.
      Make sure that you really remove the element instead of just hiding it. Confirm that your code works by clicking the button.

      html :

      <div id="green"/>
      <div id="red"/>
      <button type="button" id="button">Click Me</button>

      code scenario :

      const button = document.querySelector('#button');
      
      const removeRedCircle = () => {
        
      };
      button.addEventListener('click', removeRedCircle);
      Solution 1

      js :

      const button = document.querySelector('#button');
      
      const removeRedCircle = () => {
        const redCircle = document.querySelector('#red');
        redCircle.parentNode.removeChild(redCircle);
      };
      button.addEventListener('click', removeRedCircle);

      Solution 2

      js :

      const button = document.querySelector('#button');
      
      const removeRedCircle = () => {
        document.getElementById("red").remove();
      };
      button.addEventListener('click', removeRedCircle);

      Back to table ⬆

    • Change id of HTML element

      scenario :

      In this scenario the existing code listens to a click on the button. When the button is clicked, the function changeInput is triggered. changeInput tries to select an input field with id inputEl. But, the existing input field does not have this id. Add some Javascript code to add the id inputEl to the existing input field.
      Verify that your code works by clicking the button.

      html :

      <div id="wrapper">
          <input type="text" placeholder="Text" readonly/>
          <button type="button">Click Me</button>
      </div>

      code scenario :

      const button = document.querySelector('#wrapper button');
      
      const changeInput = () => {
        const input = document.querySelector('#inputEl');
        if(input) {
          input.value = 'Hello World';
        }
      };
      
      button.addEventListener('click', changeInput);
      Solution 1

      js :

      const button = document.querySelector('#wrapper button');
      
      const changeInput = () => {
        const input = document.querySelector('#inputEl');
        if(input) {
          input.value = 'Hello World';
        }
      };
      
      button.addEventListener('click', changeInput);
      
      document.querySelector('#wrapper input').setAttribute('id', 'inputEl');

      Back to table ⬆

  • DOM fundamentals

    • Check the checkbox

      scenario :

      Your first JavaScript DOM exercise. Let's start simple.
      Extend the JavaScript code below to interact with the displayed HTML elements. Once you click the button, the checkbox should be checked.
      Confirm your code by clicking the button!

      html :

      <input id="checkbox" disabled/>
      <label for="checkbox">checkbox</label>
      <button type="button" id="button">Verify Code</button>

      code scenario :

      const button = document.getElementById('button');
      button.addEventListener('click', () => {
        
      });
      Solution 1

      js :

      const button = document.getElementById('button');
      button.addEventListener('click', () => {
        const checkbox = document.getElementById('checkbox');
        checkbox.checked = true;
      });

      Back to table ⬆

    • Get full-name from input

      scenario :

      Extend the JavaScript code below to interact with the displayed HTML elements.
      This time we are looking for the full name. When the button is clicked, combine the names of the first two input fields. Insert the full name in the third input field.
      Hint: Check if your code still works if you change the first or last name.
      Confirm your code by clicking the button!

      html :

      <input type="text" id="firstName" placeholder="Max" value="Max"/>
      <input type="text" id="lastName" placeholder="Musterman" value="Musterman"/>
      <input type="text" id="fullName" placeholder="full name" readonly/>
      <button type="button" id="button">Verify Code</button>

      code scenario :

      const button = document.getElementById('button');
      button.addEventListener('click' , () => {
        
      });
      Solution 1

      js :

      const button = document.getElementById('button');
      button.addEventListener('click' , () => {
        const firstName = document.getElementById('firstName');
        const lastName = document.getElementById('lastName');
        const fullName = document.getElementById('fullName');
        fullName.value = firstName.value + ' ' + lastName.value;
      });

      Back to table ⬆

    • Pop the balloons

      scenario :

      Make the balloons pop by hovering over them.
      Extend the JavaScript code below to interact with the displayed HTML elements. Every time you hover over a balloon, it should become invisible.
      Your goal is to pop all the balloons one after the other.

      html :

      <ul id="list">
        <li/>
        <li/>
        <li/>
        <li/>
        <li/>
        <li/>
        <li/>
        <li/>
        <li/>
        <li/>
      </ul>

      code scenario :

      const list = document.getElementById('list');
      Solution 1

      js :

      const list = document.getElementById('list');
      const handleHover = event => {
        if(event.target !== list) {
          event.target.style.visibility = 'hidden';
        }
      };
      
      list.addEventListener('mouseover', handleHover);

      Back to table ⬆

  • Recursive functions

    • Stop and restart the moving button

      scenario :

      This is a good exercise to learn about recursive functions. The function move in the code below moves the button 1px to the left or the right. It is recursive because it calls itself again and again. This keeps the button moving.
      Extend the JavaScript code. Once you click the button, it should stop moving. When you click it again, it should move again.
      Confirm your code by clicking the button twice.

      html :

      <button type="button" id="button">Click Me</button>

      code scenario :

      const button = document.getElementById('button');
      let stopped = false;
       
      function move(isReturning) {
       const width = button.parentNode.clientWidth;
       const left = parseInt(button.style.left , 10) || 0;
       if (!stopped) {
          button.style.left = (isReturning ? left - 1 : left + 1) + 'px';
          setTimeout(() => move ((isReturning && left > 0) || left === width - button.clientWidth), 10);
       };
      };
       
      move();
       
      button.addEventListener('click', () => {
        
      });
      Solution 1

      js :

      const button = document.getElementById('button');
      let stopped = false;
       
      function move(isReturning) {
       const width = button.parentNode.clientWidth;
       const left = parseInt(button.style.left , 10) || 0;
       if (!stopped) {
          button.style.left = (isReturning ? left - 1 : left + 1) + 'px';
          setTimeout(() => move ((isReturning && left > 0) || left === width - button.clientWidth), 10);
       };
      };
       
      move();
       
      button.addEventListener('click', () => {
        stopped = !stopped;
        move();
      });

      Back to table ⬆