Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/cyruskabir/js-challenger
Solution to all JSchallenger challenges
https://github.com/cyruskabir/js-challenger
array challenge dom-manipulation javascript jschallenger object practice solved-problems
Last synced: about 17 hours ago
JSON representation
Solution to all JSchallenger challenges
- Host: GitHub
- URL: https://github.com/cyruskabir/js-challenger
- Owner: CyrusKabir
- Created: 2022-08-01T13:35:35.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2023-03-16T03:14:33.000Z (over 1 year ago)
- Last Synced: 2023-12-29T00:31:31.255Z (10 months ago)
- Topics: array, challenge, dom-manipulation, javascript, jschallenger, object, practice, solved-problems
- Language: JavaScript
- Homepage: https://www.jschallenger.com/
- Size: 275 KB
- Stars: 31
- Watchers: 2
- Forks: 14
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
## **Welcome !** π
Thanks for checking out this [js-challenger solutions repo](https://github.com/CyrusKabir/js-challenger).
## **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](https://www.erik-kueckelheim.com/). thanks Erik.
## **Why this repo ?** πΆ
In this repo, you can find available solutions for a challenge.
## **Table of solutions**
- **Javascript Basics**
variables
1. [Reassign a value to a variable](#reassign-a-value-to-a-variable)
1. [Assign a value to a variable](#assign-a-value-to-a-variable)
1. [Assign the value of another variable](#assign-the-value-of-another-variable)
1. [Create the missing variable](#create-the-missing-variable)
1. [Accessing a variable 1](#accessing-a-variable-1)
1. [Accessing a variable 2](#accessing-a-variable-2)
1. [Declare a variable and assign a number](#declare-a-variable-and-assign-a-number)
1. [Reassign a value to a variable 2](#reassign-a-value-to-a-variable-2)
booleans
1. [Assign boolean to a variable](#assign-boolean-to-a-variable)
1. [Convert Number to Boolean](#convert-number-to-boolean)
operators
1. [Comparison operators - Equal](#comparison-operators---equal)
1. [Comparison operators - Not Equal](#comparison-operators---not-equal)
1. [Comparison operators - Greater than](#comparison-operators---greater-than)
1. [Comparison operators - Less than](#comparison-operators---less-than)
1. [Comparison operators - Greater than or equal](#comparison-operators---greater-than-or-equal)
1. [Comparison operators - Less than or equal](#comparison-operators---less-than-or-equal)
strings
1. [Create a Javascript string](#create-a-javascript-string)
1. [Different ways to create Javascript strings](#different-ways-to-create-javascript-strings)
1. [Connect Javascript strings 1](#connect-javascript-strings-1)
conditionals
1. [if statement - satisfy condition](#if-statement---satisfy-condition)
1. [if statement - add missing condition](#if-statement---add-missing-condition)
functions I
1. [Function declaration](#function-declaration)
1. [Function expression](#function-expression)
1. [Correctly return value from function 1](#correctly-return-value-from-function-1)
1. [Correctly return value from function 2](#correctly-return-value-from-function-2)
arrays
loops
asynchronous javascript
1. [Execute the code synchronously](#execute-the-code-synchronously)
1. [Execute the code asynchronously](#execute-the-code-asynchronously)
- **Javascript Practice**
Javascript fundamentals
1. [Sum two numbers](#sum-two-numbers)
1. [Comparison operators, strict equality](#comparison-operators,-strict-equality)
1. [Get type of value](#get-type-of-value)
1. [Get nth character of string](#get-nth-character-of-string)
1. [Remove first n characters of string](#remove-first-n-characters-of-string)
1. [Get first n characters of string](#get-first-n-characters-of-string)
1. [Find the position of one string in another](#find-the-position-of-one-string-in-another)
1. [Extract first half of string](#extract-first-half-of-string)
1. [Remove last n characters of string](#remove-last-n-characters-of-string)
1. [Return the percentage of a number](#return-the-percentage-of-a-number)
1. [Basic JavaScript math operators](#basic-javascript-math-operators)
1. [Check whether a string contains another string and concatenate](#check-whether-a-string-contains-another-string-and-concatenate)
1. [Check if a number is even](#check-if-a-number-is-even)
1. [How many times does a character occur?](#how-many-times-does-a-character-occur?)
1. [Check if a number is a whole number](#check-if-a-number-is-a-whole-number)
1. [Multiplication, division, and comparison operators](#multiplication,-division,-and-comparison-operators)
1. [Round a number to 2 decimal places](#round-a-number-to-2-decimal-places)
1. [Split a number into its digits](#split-a-number-into-its-digits)
Javascript arrays
1. [Get nth element of array](#get-nth-element-of-array)
1. [Remove first n elements of an array](#remove-first-n-elements-of-an-array)
1. [Get last n elements of an array](#get-last-n-elements-of-an-array)
1. [Get first n elements of an array](#get-first-n-elements-of-an-array)
1. [Return last n array elements](#return-last-n-array-elements)
1. [Remove a specific array element](#remove-a-specific-array-element)
1. [Count number of elements in JavaScript array](#count-number-of-elements-in-javascript-array)
1. [Count number of negative values in array](#count-number-of-negative-values-in-array)
1. [Sort an array of strings alphabetically](#sort-an-array-of-strings-alphabetically)
1. [Sort an array of numbers in descending order](#sort-an-array-of-numbers-in-descending-order)
1. [Calculate the sum of an array of numbers](#calculate-the-sum-of-an-array-of-numbers)
1. [Return the average of an array of numbers](#return-the-average-of-an-array-of-numbers)
1. [Return the longest string from an array of strings](#return-the-longest-string-from-an-array-of-strings)
1. [Check if all array elements are equal](#check-if-all-array-elements-are-equal)
1. [Merge an arbitrary number of arrays](#merge-an-arbitrary-number-of-arrays)
1. [Sort array by object property](#sort-array-by-object-property)
1. [Merge two arrays with duplicate values](#merge-two-arrays-with-duplicate-values)
Javascript objects
1. [Accessing object properties one](#accessing-object-properties-one)
1. [Accessing object properties two](#accessing-object-properties-two)
1. [Accessing object properties three](#accessing-object-properties-three)
1. [Check if property exists in object](#check-if-property-exists-in-object)
1. [Check if property exists in object and is truthy](#check-if-property-exists-in-object-and-is-truthy)
1. [Creating Javascript objects one](#creating-javascript-objects-one)
1. [Creating Javascript objects two](#creating-javascript-objects-two)
1. [Creating Javascript objects three](#creating-javascript-objects-three)
1. [Extract keys from Javascript object](#extract-keys-from-javascript-object)
1. [Return nested object property](#return-nested-object-property)
1. [Sum object values](#sum-object-values)
1. [Remove a property from an object](#remove-a-property-from-an-object)
1. [Merge two objects with matching keys](#merge-two-objects-with-matching-keys)
1. [Multiply all object values by x](#multiply-all-object-values-by-x)
Javascript dates
1. [Check if two dates are equal](#check-if-two-dates-are-equal)
1. [Return the number of days between two dates](#return-the-number-of-days-between-two-dates)
1. [Check if two dates fall on the exact same day](#check-if-two-dates-fall-on-the-exact-same-day)
1. [Check if two dates are within 1 hour from each other](#check-if-two-dates-are-within-1-hour-from-each-other)
1. [Check if one date is earlier than another](#check-if-one-date-is-earlier-than-another)
Javascript Sets
1. [Check if value is present in Set](#check-if-value-is-present-in-set)
1. [Convert a Set to Array](#convert-a-set-to-array)
1. [Get union of two sets](#get-union-of-two-sets)
1. [Creating Javascript Sets](#creating-javascript-sets)
1. [Delete element from Set](#delete-element-from-set)
- **Javascript DOM**
DOM selector methods
1. [Select the button element on the page](#select-the-button-element-on-the-page)
1. [Query descendent HTML elements](#query-descendent-html-elements)
1. [Select multiple HTML elements](#select-multiple-html-elements)
Events and user interactions
1. [Execute function on button click](#execute-function-on-button-click)
1. [Execute function when cursor moves onto element](#execute-function-when-cursor-moves-onto-element)
1. [Cursor enters and leaves element](#cursor-enters-and-leaves-element)
DOM manipulation
1. [Remove element from the DOM](#remove-element-from-the-dom)
1. [Change id of HTML element](#change-id-of-html-element)
DOM fundamentals
1. [Check the checkbox](#check-the-checkbox)
1. [Get full-name from input](#get-full-name-from-input)
1. [Pop the balloons](#pop-the-balloons)
Recursive functions
1. [Stop and restart the moving button](#stop-and-restart-the-moving-button)
## **Javascript Basics :**
- ### variables
- #### Reassign a value to a variable
scenario :
```python
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 :
```js
let num = 1;
let num = 2;
console.log(num);
```
Solution 1
js :
```js
let num = 1;
num = 2;
console.log(num);
```
[Back to table β¬](#table-of-solutions)
- #### Assign a value to a variable
scenario :
```python
Here, we declare the variable num. But, it has no value yet. Assign a value to it and run
the code.
```
code scenario :
```js
let num;
console.log(num);
```
Solution 1
js :
```js
let num;
num = 2;
console.log(num);
```
[Back to table β¬](#table-of-solutions)
- #### Assign the value of another variable
scenario :
```python
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 :
```js
let numOne = 5;
let numTwo;
console.log(numTwo);
```
Solution 1
js :
```js
let numOne = 5;
let numTwo = numOne;
console.log(numTwo);
```
[Back to table β¬](#table-of-solutions)
- #### Create the missing variable
scenario :
```python
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 :
```js
let numTwo = numOne;
console.log(numTwo);
```
Solution 1
js :
```js
let numOne = 5;
let numTwo = numOne;
console.log(numTwo);
```
[Back to table β¬](#table-of-solutions)
- #### Accessing a variable 1
scenario :
```python
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 :
```js
const num = 5;
console.log(Num);
```
Solution 1
js :
```js
const num = 5;
console.log(num);
```
[Back to table β¬](#table-of-solutions)
- #### Accessing a variable 2
scenario :
```python
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 :
```js
console.log(num);
const num = 5;
```
Solution 1
js :
```js
const num = 5;
console.log(num);
```
[Back to table β¬](#table-of-solutions)
- #### Declare a variable and assign a number
scenario :
```python
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 :
```js
console.log('The value of num is: ' + num);
```
Solution 1
js :
```js
const num = 5;
console.log('The value of num is: ' + num);
```
[Back to table β¬](#table-of-solutions)
- #### Reassign a value to a variable 2
scenario :
```python
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 :
```js
const text = 'hello';
text = 'hello world';
console.log(text);
```
Solution 1
js :
```js
let text = 'hello';
text = 'hello world';
console.log(text);
```
[Back to table β¬](#table-of-solutions)
- ### booleans
- #### Assign boolean to a variable
scenario :
```python
Here, we declare the variable isTrue. But, it has no value yet. Assign a boolean value to it and run the code.
```
code scenario :
```js
let isTrue;console.log(isTrue);
```
Solution 1
js :
```js
let isTrue;
isTrue = true;
console.log(isTrue);
```
[Back to table β¬](#table-of-solutions)
- #### Convert Number to Boolean
scenario :
```python
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 :
```js
let num = 5;
const bool = Boolean(bool);
console.log(bool);
```
Solution 1
js :
```js
let num = 5;
num = 0;
const bool = Boolean(bool);
console.log(bool);
```
[Back to table β¬](#table-of-solutions)
- ### operators
- #### Comparison operators - Equal
scenario :
```python
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 :
```js
const numOne = 5;
const numTwo = 6;
console.log(numOne == numTwo);
```
Solution 1
js :
```js
const numOne = 5;
const numTwo = 5;
console.log(numOne == numTwo);
```
[Back to table β¬](#table-of-solutions)
- #### Comparison operators - Not Equal
scenario :
```python
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 :
```js
const numOne = 5;
const numTwo = 5;
console.log(numOne != numTwo);
```
Solution 1
js :
```js
const numOne = 5;
const numTwo = 6;
console.log(numOne != numTwo);
```
[Back to table β¬](#table-of-solutions)
- #### Comparison operators - Greater than
scenario :
```python
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 :
```js
const numOne = 5;
const numTwo = 6;
console.log(numOne > numTwo);
```
Solution 1
js :
```js
const numOne = 6;
const numTwo = 5;
console.log(numOne > numTwo);
```
[Back to table β¬](#table-of-solutions)
- #### Comparison operators - Less than
scenario :
```python
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 :
```js
const numOne = 2;
const numTwo = 1;
console.log(numOne < numTwo);
```
Solution 1
js :
```js
const numOne = 1;
const numTwo = 2;
console.log(numOne < numTwo);
```
[Back to table β¬](#table-of-solutions)
- #### Comparison operators - Greater than or equal
scenario :
```python
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 :
```js
const numOne = 3;
const numTwo = 4;
const numThree = 2;
console.log(numOne >= numTwo, numTwo >= numThree);
```
Solution 1
js :
```js
const numOne = 3;
const numTwo = 2;
const numThree = 2;
console.log(numOne >= numTwo, numTwo >= numThree);
```
[Back to table β¬](#table-of-solutions)
- #### Comparison operators - Less than or equal
scenario :
```python
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 :
```js
const numOne = 1;
const numTwo = 4;
const numThree = 2;
console.log(numOne <= numTwo, numTwo <= numThree);
```
Solution 1
js :
```js
const numOne = 1;
const numTwo = 1;
const numThree = 2;
console.log(numOne <= numTwo, numTwo <= numThree);
```
[Back to table β¬](#table-of-solutions)
- ### strings
- #### Create a Javascript string
scenario :
```python
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 string β as 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 :
```js
const text = '';
console.log('The value of text is: ' + text);
```
Solution 1
js :
```js
const text = 'hello world';
console.log('The value of text is: ' + text);
```
[Back to table β¬](#table-of-solutions)
- #### Different ways to create Javascript strings
scenario :
```python
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 string β as 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 :
```js
const textOne = '';
const textTwo = "";
const textThree = ``;
console.log(textOne, textTwo, textThree);
```
Solution 1
js :
```js
const textOne = 'Hello, ';
const textTwo = "it's ";
const textThree = `me`;
console.log(textOne, textTwo, textThree);
```
[Back to table β¬](#table-of-solutions)
- #### Connect Javascript strings 1
scenario :
```python
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 :
```js
const textOne = 'Hello';
const textTwo = 'World';
const combined = textOne + textTwo;
console.log(combined);
```
Solution 1
js :
```js
const textOne = 'Hello';
const textTwo = 'World';
const combined = textOne + ' ' + textTwo;
console.log(combined);
```
[Back to table β¬](#table-of-solutions)
- ### conditionals
- #### if statement - satisfy condition
scenario :
```python
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 condition β the part inside the parentheses β and 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 :
```js
let num = 0;
if (1 > 2) {
num = 1;
}
console.log(num === 1);
```
Solution 1
js :
```js
let num = 0;
if (1 < 2) {
num = 1;
}
console.log(num === 1);
```
[Back to table β¬](#table-of-solutions)
- #### if statement - add missing condition
scenario :
```python
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 :
```js
let text = 'hello';
if () {
text = text + ' world';
}
console.log(text === 'hello world');
```
Solution 1
js :
```js
let text = 'hello';
if (text === 'hello') {
text = text + ' world';
}
console.log(text === 'hello world');
```
[Back to table β¬](#table-of-solutions)
- ### functions I
- #### Function declaration
scenario :
```python
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 :
```js
function func() {
return 'hello';
};
const result = func();
console.log(result);
```
Solution 1
js :
```js
function func() {
return 'hello world';
};
const result = func();
console.log(result);
```
[Back to table β¬](#table-of-solutions)
- #### Function expression
scenario :
```python
In this exercise, we use a slightly different way to create a function β a 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 :
```js
const func = function() {
return 'hello world';
};
const result = func;
console.log(result);
```
Solution 1
js :
```js
const func = function() {
return 'hello world';
};
const result = func();
console.log(result);
```
[Back to table β¬](#table-of-solutions)
- #### Correctly return value from function 1
scenario :
```python
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 :
```js
const func = function() {
let text = 'hello';
text = text + ' world';
};
const result = func();
console.log(result);
```
Solution 1
js :
```js
const func = function() {
let text = 'hello';
text = text + ' world';
return text;
};
const result = func();
console.log(result);
```
[Back to table β¬](#table-of-solutions)
- #### Correctly return value from function 2
scenario :
```python
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 :
```js
const func = function () {
let text = 'hello';
return text;
text = text + ' world';
return text;
};
const result = func();
console.log(result);
```
Solution 1
js :
```js
const func = function () {
let text = 'hello';
text = text + ' world';
return text;
};
const result = func();
console.log(result);
```
[Back to table β¬](#table-of-solutions)
- ### arrays
- ### loops
- ### asynchronous javascript
- #### Execute the code synchronously
scenario :
```python
Adjust the code snippet so that the console.log statement logs the value 2.
```
code scenario :
```js
let i = 0;
function func() {
i = 2;
}
setTimeout(func, 100)
// expected output = 2
console.log(i);
```
Solution 1
js :
```js
let i = 0;
function func() {
i = 2;
}
func();
// expected output = 2
console.log(i);
```
[Back to table β¬](#table-of-solutions)
- #### Execute the code asynchronously
scenario :
```python
Adjust the code snippet so that the value 0 is logged first and then the value 1.
```
code scenario :
```js
let count = 0;
function increment() {
count = count + 1;
}
increment();
setTimeout(() => {console.log(count);
}, 1000);console.log(count);
```
Solution 1
js :
```js
let count = 0;
function increment() {
count = count + 1;
}
setTimeout(() => {
increment();
console.log(count);
}, 1000);console.log(count);
```
[Back to table β¬](#table-of-solutions)
## **Javascript Practice :**
- ### Javascript fundamentals
- #### Sum two numbers
scenario :
```python
Write a function that takes two numbers (a and b) as argument
Sum a and b
Return the result
```
code scenario :
```js
function myFunction(a, b) {
return
}
```
Solution 1
js :
```js
function myFunction(a, b) {
return a + b;
}
```
[Back to table β¬](#table-of-solutions)
- #### Comparison operators, strict equality
scenario :
```python
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 :
```js
function myFunction(a, b) {
return
}
```
Solution 1
js :
```js
function myFunction(a, b) {
return a === b;
}
```
[Back to table β¬](#table-of-solutions)
- #### Get type of value
scenario :
```python
Write a function that takes a value as argument
Return the type of the value
```
code scenario :
```js
function myFunction(a) {
return
}
```
Solution 1
js :
```js
function myFunction(a) {
return typeof a;
}
```
[Back to table β¬](#table-of-solutions)
- #### Get nth character of string
scenario :
```python
Write a function that takes a string (a) and a number (n) as argument
Return the nth character of 'a'
```
code scenario :
```js
function myFunction(a, n) {
return
}
```
Solution 1
js :
```js
function myFunction(a, n) {
return a[n - 1];
}
```
[Back to table β¬](#table-of-solutions)
- #### Remove first n characters of string
scenario :
```python
Write a function that takes a string (a) as argument
Remove the first 3 characters of a
Return the result
```
code scenario :
```js
function myFunction(a) {
return
}
```
Solution 1
js :
```js
function myFunction(a) {
return a.slice(3);
}
```
[Back to table β¬](#table-of-solutions)
- #### Get first n characters of string
scenario :
```python
Write a function that takes a string (a) as argument
Get the first 3 characters of a
Return the result
```
code scenario :
```js
function myFunction(a) {
return
}
```
Solution 1
js :
```js
function myFunction(a) {
return a.slice(0, 3);
}
```
[Back to table β¬](#table-of-solutions)
- #### Find the position of one string in another
scenario :
```python
Write a function that takes a string as argument
The string contains the substring 'is'
Return the index of 'is'
```
code scenario :
```js
function myFunction(a) {
return
}
```
Solution 1
js :
```js
function myFunction(a) {
return a.indexOf('is');
}
```
[Back to table β¬](#table-of-solutions)
- #### Extract first half of string
scenario :
```python
Write a function that takes a string (a) as argument
Extract the first half a
Return the result
```
code scenario :
```js
function myFunction(a) {
return
}
```
Solution 1
js :
```js
function myFunction(a) {
return a.slice(0, a.length / 2);
}
```
[Back to table β¬](#table-of-solutions)
- #### Remove last n characters of string
scenario :
```python
Write a function that takes a string (a) as argument
Remove the last 3 characters of a
Return the result
```
code scenario :
```js
function myFunction(a) {
return
}
```
Solution 1
js :
```js
function myFunction(a) {
return a.slice(0, -3);
}
```
[Back to table β¬](#table-of-solutions)
- #### Return the percentage of a number
scenario :
```python
Write a function that takes two numbers (a and b) as argument
Return b percent of a
```
code scenario :
```js
function myFunction(a, b) {
return
}
```
Solution 1
js :
```js
function myFunction(a, b) {
return b / 100 * a
}
```
[Back to table β¬](#table-of-solutions)
- #### Basic JavaScript math operators
scenario :
```python
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 :
```js
function myFunction(a, b, c, d, e, f) {
return
}
```
Solution 1
js :
```js
function myFunction(a, b, c, d, e, f) {
return (((a + b - c) * d) / e) ** f;
}
```
[Back to table β¬](#table-of-solutions)
- #### Check whether a string contains another string and concatenate
scenario :
```python
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 :
```js
function myFunction(a, b) {
return
}
```
Solution 1
js :
```js
function myFunction(a, b) {
return a.indexOf(b) === -1 ? a + b : b + a
}
```
Solution 2
js :
```js
function myFunction(a, b) {
return a.includes(b) ? `${b}${a}` : `${a}${b}`
}
```
[Back to table β¬](#table-of-solutions)
- #### Check if a number is even
scenario :
```python
Write a function that takes a number as argument. If the number is even, return true. Otherwise,
return false
```
code scenario :
```js
function myFunction(a) {
return
}
```
Solution 1
js :
```js
function myFunction(a) {
return a % 2 === 0
}
```
[Back to table β¬](#table-of-solutions)
- #### How many times does a character occur?
scenario :
```python
Write a function that takes two strings (a and b) as arguments. Return the number of times a occurs in
b.
```
code scenario :
```js
function myFunction(a, b) {
return
}
```
Solution 1
js :
```js
function myFunction(a, b) {
return b.split(a).length - 1
}
```
[Back to table β¬](#table-of-solutions)
- #### Check if a number is a whole number
scenario :
```python
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 :
```js
function myFunction(a) {
return
}
```
Solution 1
js :
```js
function myFunction(a) {
return a - Math.floor(a) === 0
}
```
Solution 2
js :
```js
function myFunction(a) {
return parseInt(a) === a
}
```
[Back to table β¬](#table-of-solutions)
- #### Multiplication, division, and comparison operators
scenario :
```python
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 :
```js
function myFunction(a, b) {
return
}
```
Solution 1
js :
```js
function myFunction(a, b) {
return a < b ? a / b : a * b
}
```
[Back to table β¬](#table-of-solutions)
- #### Round a number to 2 decimal places
scenario :
```python
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 :
```js
function myFunction(a) {
return
}
```
Solution 1
js :
```js
function myFunction(a) {
return Number(a.toFixed(2));
}
```
[Back to table β¬](#table-of-solutions)
- #### Split a number into its digits
scenario :
```python
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 :
```js
function myFunction( a ) {
return
}
```
Solution 1
js :
```js
function myFunction( a ) {
const string = a + '';
const strings = string.split('');
return strings.map(digit => Number(digit))
}
```
Solution 2
js :
```js
function myFunction(a) {
return a.toString()
.split('')
.map(charNum => parseInt(charNum))
}
```
[Back to table β¬](#table-of-solutions)
- ### Javascript arrays
- #### Get nth element of array
scenario :
```python
Write a function that takes an array (a) and a value (n) as argument. Return the nth element of 'a'
```
code scenario :
```js
function myFunction(a, n) {
return
}
```
Solution 1
js :
```js
function myFunction(a, n) {
return a[n - 1];
}
```
[Back to table β¬](#table-of-solutions)
- #### Remove first n elements of an array
scenario :
```python
Write a function that takes an array (a) as argument. Remove the first 3 elements of 'a'. Return the
result
```
code scenario :
```js
function myFunction(a) {
return
}
```
Solution 1
js :
```js
function myFunction(a) {
return a.slice(3);
}
```
[Back to table β¬](#table-of-solutions)
- #### Get last n elements of an array
scenario :
```python
Write a function that takes an array (a) as argument. Extract the last 3 elements of 'a'. Return the
resulting array
```
code scenario :
```js
function myFunction(a) {
return
}
```
Solution 1
js :
```js
function myFunction(a) {
return a.slice(-3);
}
```
[Back to table β¬](#table-of-solutions)
- #### Get first n elements of an array
scenario :
```python
Write a function that takes an array (a) as argument. Extract the first 3 elements of a. Return the
resulting array
```
code scenario :
```js
function myFunction(a) {
return
}
```
Solution 1
js :
```js
function myFunction(a) {
return a.slice(0, 3);
}
```
[Back to table β¬](#table-of-solutions)
- #### Return last n array elements
scenario :
```python
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 :
```js
function myFunction(a, n) {
return
}
```
Solution 1
js :
```js
function myFunction(a, n) {
return a.slice(-n);
}
```
[Back to table β¬](#table-of-solutions)
- #### Remove a specific array element
scenario :
```python
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 :
```js
function myFunction( a, b ) {
return
}
```
Solution 1
js :
```js
function myFunction( a, b ) {
return a.filter(arrItem => arrItem !== b)
}
```
[Back to table β¬](#table-of-solutions)
- #### Count number of elements in JavaScript array
scenario :
```python
Write a function that takes an array (a) as argument. Return the number of elements in a.
```
code scenario :
```js
function myFunction(a) {
return
}
```
Solution 1
js :
```js
function myFunction(a) {
return a.length;
}
```
[Back to table β¬](#table-of-solutions)
- #### Count number of negative values in array
scenario :
```python
Write a function that takes an array of numbers as argument. Return the number of negative values
in the array.
```
code scenario :
```js
function myFunction(a) {
return
}
```
Solution 1
js :
```js
function myFunction(a) {
return a.filter((el) => el < 0).length;
}
```
Solution 2
js :
```js
function myFunction(a) {
const isNegative = num => num < 0;
return a.filter(isNegative).length;
}
```
[Back to table β¬](#table-of-solutions)
- #### Sort an array of strings alphabetically
scenario :
```python
Write a function that takes an array of strings as argument. Sort the array elements alphabetically.
Return the result.
```
code scenario :
```js
function myFunction(arr) {
return
}
```
Solution 1
js :
```js
function myFunction(arr) {
return arr.sort();
}
```
[Back to table β¬](#table-of-solutions)
- #### Sort an array of numbers in descending order
scenario :
```python
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 :
```js
function myFunction( arr ) {
return
}
```
Solution 1
js :
```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 β¬](#table-of-solutions)
- #### Calculate the sum of an array of numbers
scenario :
```python
Write a function that takes an array of numbers as argument. It should return the sum of the
numbers.
```
code scenario :
```js
function myFunction(a) {
return
}
```
Solution 1
js :
```js
function myFunction(a) {
return a.reduce((acc, cur) => acc + cur, 0);
}
```
[Back to table β¬](#table-of-solutions)
- #### Return the average of an array of numbers
scenario :
```python
Write a function that takes an array of numbers as argument. It should return the average of the
numbers.
```
code scenario :
```js
function myFunction( arr ) {
return
}
```
Solution 1
js :
```js
function myFunction( arr ) {
return arr.reduce((acc, cur) => acc + cur, 0) / arr.length
}
```
[Back to table β¬](#table-of-solutions)
- #### Return the longest string from an array of strings
scenario :
```python
Write a function that takes an array of strings as argument. Return the longest string.
```
code scenario :
```js
function myFunction( arr ) {
return
}
```
Solution 1
js :
```js
function myFunction( arr ) {
return arr.reduce((a, b) => a.length <= b.length ? b : a)
}
```
[Back to table β¬](#table-of-solutions)
- #### Check if all array elements are equal
scenario :
```python
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 :
```js
function myFunction( arr ) {
return
}
```
Solution 1
js :
```js
function myFunction( arr ) {
return new Set(arr).size === 1;
}
```
[Back to table β¬](#table-of-solutions)
- #### Merge an arbitrary number of arrays
scenario :
```python
Write a function that takes arguments an arbitrary number of arrays. It should return an array
containing the values of all arrays.
```
code scenario :
```js
function myFunction(...arrays) {
return
}
```
Solution 1
js :
```js
function myFunction(...arrays) {
return arrays.flat();
}
```
[Back to table β¬](#table-of-solutions)
- #### Sort array by object property
scenario :
```python
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 :
```js
function myFunction(arr) {
return
}
```
Solution 1
js :
```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 β¬](#table-of-solutions)
- #### Merge two arrays with duplicate values
scenario :
```python
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 :
```js
function myFunction(a, b) {
return
}
```
Solution 1
js :
```js
function myFunction(a, b) {
return [...new Set([...a, ...b])].sort((x, y) => x - y);
}
```
Solution 2
js :
```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 β¬](#table-of-solutions)
- ### Javascript objects
- #### Accessing object properties one
scenario :
```python
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 :
```js
function myFunction(obj) {
return
}
```
Solution 1
js :
```js
function myFunction(obj) {
return obj.country;
}
```
[Back to table β¬](#table-of-solutions)
- #### Accessing object properties two
scenario :
```python
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 :
```js
function myFunction(obj) {
return
}
```
Solution 1
js :
```js
function myFunction(obj) {
return obj['prop-2'];
}
```
[Back to table β¬](#table-of-solutions)
- #### Accessing object properties three
scenario :
```python
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 :
```js
function myFunction(obj, key) {
return
}
```
Solution 1
js :
```js
function myFunction(obj, key) {
return obj[key]
}
```
[Back to table β¬](#table-of-solutions)
- #### Check if property exists in object
scenario :
```python
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 :
```js
function myFunction(a, b) {
return
}
```
Solution 1
js :
```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 β¬](#table-of-solutions)
- #### Check if property exists in object and is truthy
scenario :
```python
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 :
```js
function myFunction(a, b) {
return
}
```
Solution 1
js :
```js
function myFunction(a, b) {
return Boolean(a[b]);
}
```
Solution 2
js :
```js
function myFunction(a, b) {
return a[b] ? true : false;
}
```
[Back to table β¬](#table-of-solutions)
- #### Creating Javascript objects one
scenario :
```python
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 :
```js
function myFunction(a) {
return
}
```
Solution 1
js :
```js
function myFunction(a) {
return { key: a }
}
```
[Back to table β¬](#table-of-solutions)
- #### Creating Javascript objects two
scenario :
```python
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 :
```js
function myFunction(a, b) {
return
}
```
Solution 1
js :
```js
function myFunction(a, b) {
return { [a]: b }
}
```
[Back to table β¬](#table-of-solutions)
- #### Creating Javascript objects three
scenario :
```python
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 :
```js
function myFunction(a, b) {
return
}
```
Solution 1
js :
```js
function myFunction(a, b) {
return a.reduce((acc, cur, i) => ({ ...acc, [cur]: b[i] }), {})
}
```
[Back to table β¬](#table-of-solutions)
- #### Extract keys from Javascript object
scenario :
```python
Write a function that takes an object (a) as argument. Return an array with all object keys.
```
code scenario :
```js
function myFunction(a) {
return
}
```
Solution 1
js :
```js
function myFunction(a) {
return Object.keys(a);
}
```
[Back to table β¬](#table-of-solutions)
- #### Return nested object property
scenario :
```python
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 :
```js
function myFunction(obj) {
return
}
```
Solution 1
js :
```js
function myFunction(obj) {
return obj?.a?.b;
}
```
Solution 2
js :
```js
function myFunction(obj) {
return obj.a && obj.a.b ? obj.a.b : undefined
}
```
[Back to table β¬](#table-of-solutions)
- #### Sum object values
scenario :
```python
Write a function that takes an object (a) as argument. Return the sum of all object values.
```
code scenario :
```js
function myFunction(a) {
return
}
```
Solution 1
js :
```js
function myFunction(a) {
return Object.values(a).reduce((sum, cur) => sum + cur, 0);
}
```
[Back to table β¬](#table-of-solutions)
- #### Remove a property from an object
scenario :
```python
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 :
```js
function myFunction(obj) {
return
}
```
Solution 1
js :
```js
function myFunction(obj) {
const { b, ...rest } = obj;
return rest;
}
```
Solution 2
js :
```js
function myFunction(obj) {
if("b" in obj) {
return delete obj.b && obj;
}
}
```
[Back to table β¬](#table-of-solutions)
- #### Merge two objects with matching keys
scenario :
```python
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 :
```js
function myFunction(x, y) {
return
}
```
Solution 1
js :
```js
function myFunction(x, y) {
const {b, ...rest} = y;
return {...x, ...rest, d: b};
}
```
Solution 2
js :
```js
function myFunction(x, y) {
y.d = y.b;
delete y.b;
return {...x, ...y};
}
```
[Back to table β¬](#table-of-solutions)
- #### Multiply all object values by x
scenario :
```python
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 :
```js
function myFunction(a, b) {
return
}
```
Solution 1
js :
```js
function myFunction(a, b) {
return Object.entries(a).reduce((acc, [key, val]) => {
return { ...acc, [key]: val * b };
}, {});
}
```
[Back to table β¬](#table-of-solutions)
- ### Javascript dates
- #### Check if two dates are equal
scenario :
```python
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 :
```js
function myFunction(a, b) {
return
}
```
Solution 1
js :
```js
function myFunction(a, b) {
return a.getTime() === b.getTime();
}
```
Solution 2
js :
```js
function myFunction(a, b) {
return a - b === 0;
}
```
[Back to table β¬](#table-of-solutions)
- #### Return the number of days between two dates
scenario :
```python
Write a function that takes two date instances as argument. It should return the number of days that
lies between those dates.
```
code scenario :
```js
function myFunction(a, b) {
return
}
```
Solution 1
js :
```js
function myFunction(a, b) {
const dif = Math.abs(a - b);
return dif / 1000 / 60 / 60 / 24
}
```
Solution 2
js :
```js
functiion myFunction(a, b) {
return Math.abs( (a.getTime() / 86400000) - (b.getTime() / 86400000) )
}
```
[Back to table β¬](#table-of-solutions)
- #### Check if two dates fall on the exact same day
scenario :
```python
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 :
```js
function myFunction(a, b) {
return
}
```
Solution 1
js :
```js
function myFunction(a, b) {
return a.getFullYear() === b.getFullYear() &&
a.getMonth() === b.getMonth() &&
a.getDate()=== b.getDate()
}
```
[Back to table β¬](#table-of-solutions)
- #### Check if two dates are within 1 hour from each other
scenario :
```python
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 :
```js
function myFunction(a, b) {
return
}
```
Solution 1
js :
```js
function myFunction(a, b) {
return Math.abs(a - b) / 1000 / 60 <= 60
}
```
Solution 2
js :
```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 β¬](#table-of-solutions)
- #### Check if one date is earlier than another
scenario :
```python
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 :
```js
function myFunction(a, b) {
return
}
```
Solution 1
js :
```js
function myFunction(a, b) {
return a < b
}
```
[Back to table β¬](#table-of-solutions)
- ### Javascript Sets
- #### Check if value is present in Set
scenario :
```python
Write a function that takes a Set and a value as arguments. Check if the value is present in
the Set
```
code scenario :
```js
function myFunction(set, val) {
return
}
```
Solution 1
js :
```js
function myFunction(set, val) {
return set.has(val);
}
```
[Back to table β¬](#table-of-solutions)
- #### Convert a Set to Array
scenario :
```python
Write a function that takes a Set as argument. Convert the Set to an Array. Return the Array
```
code scenario :
```js
function myFunction(set) {
return
}
```
Solution 1
js :
```js
function myFunction(set) {
return [...set];
}
```
[Back to table β¬](#table-of-solutions)
- #### Get union of two sets
scenario :
```python
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 :
```js
function myFunction(a, b) {
return
}
```
Solution 1
js :
```js
function myFunction(a, b) {
const result = new Set(a);
b.forEach((el) => result.add(el));
return result;
}
```
[Back to table β¬](#table-of-solutions)
- #### Creating Javascript Sets
scenario :
```python
Write a function that takes three elements of any type as arguments. Create a Set from
those elements. Return the result
```
code scenario :
```js
function myFunction(a, b, c) {
return
}
```
Solution 1
js :
```js
function myFunction(a, b, c) {
const set = new Set();
set.add(a);
set.add(b);
set.add(c);
return set;
}
```
[Back to table β¬](#table-of-solutions)
- #### Delete element from Set
scenario :
```python
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 :
```js
function myFunction(set, val) {
return
}
```
Solution 1
js :
```js
function myFunction(set, val) {
set.delete(val);
return set;
}
```
Solution 2
js :
```js
function myFunction(set, val) {
return set.has(val) ? set.delete(val) && set : set;
}
```
[Back to table β¬](#table-of-solutions)
## **Javascript DOM :**- ### DOM selector methods
- #### Select the button element on the page
scenario :
```python
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 :
```html
OFF
```
code scenario :
```js
const buttonElem =
buttonElem.addEventListener('click', () => {
const oldText = buttonElem.innerText;
return button.innerText = oldText === "ON" ? "OFF" : "ON";
});
```
Solution 1
js :
```js
const buttonElem = document.getElementById("button");
buttonElem.addEventListener('click', () => {
const oldText = buttonElem.innerText;
return button.innerText = oldText === "ON" ? "OFF" : "ON";
});
```
[Back to table β¬](#table-of-solutions)
- #### Query descendent HTML elements
scenario :
```python
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 :
```html
Click Me
```
code scenario :
```js
const buttonElem =
const inputElem =buttonElem.addEventListener('click', () => {
const oldText = inputElem.value;
return inputElem.value = oldText === "ON" ? "OFF" : "ON";
});
```
Solution 1
js :
```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 β¬](#table-of-solutions)
- #### Select multiple HTML elements
scenario :
```python
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 :
```html
- OFF
- OFF
- OFF
- OFF
- OFF
- OFF
```
code scenario :
```js
const listItems =
const handleHover = (event) => {
return event.target.innerText = 'ON';
};
if(listItems.length > 1) {
listItems.forEach(item => item.addEventListener('mouseover', handleHover));
}
```
Solution 1
js :
```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 β¬](#table-of-solutions)
- ### Events and user interactions
- #### Execute function on button click
scenario :
```python
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 :
```html
Click Me
```
code scenario :
```js
const button = document.getElementById('button');
const input = document.getElementById('input');
const handleClick = () => {
input.value = 'Hello World';
};
```
Solution 1
js :
```js
const button = document.getElementById('button');
const input = document.getElementById('input');
const handleClick = () => {
input.value = 'Hello World';
};
button.addEventListener('click', handleClick);
```
[Back to table β¬](#table-of-solutions)
- #### Execute function when cursor moves onto element
scenario :
```python
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 :
```html
Hover Me
```
code scenario :
```js
const element = document.getElementById('element');
const changeText = () => {
element.innerText = 'Thanks!';
};
```
Solution 1
js :
```js
const element = document.getElementById('element');
const changeText = () => {
element.innerText = 'Thanks!';
};
element.addEventListener("mouseover", changeText);
```
[Back to table β¬](#table-of-solutions)
- #### Cursor enters and leaves element
scenario :
```python
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 :
```html
Hover Me
```
code scenario :
```js
const element = document.querySelector('#element');
const toggleColor = (isEntering) => {
element.style.background = isEntering ? 'orange' : 'black';
};
```
Solution 1
js :
```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 β¬](#table-of-solutions)
- ### DOM manipulation
- #### Remove element from the DOM
scenario :
```python
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 :
```html
Click Me
```
code scenario :
```js
const button = document.querySelector('#button');
const removeRedCircle = () => {
};
button.addEventListener('click', removeRedCircle);
```
Solution 1
js :
```js
const button = document.querySelector('#button');
const removeRedCircle = () => {
const redCircle = document.querySelector('#red');
redCircle.parentNode.removeChild(redCircle);
};
button.addEventListener('click', removeRedCircle);
```
Solution 2
js :
```js
const button = document.querySelector('#button');
const removeRedCircle = () => {
document.getElementById("red").remove();
};
button.addEventListener('click', removeRedCircle);
```
[Back to table β¬](#table-of-solutions)
- #### Change id of HTML element
scenario :
```python
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 :
```html
Click Me
```
code scenario :
```js
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 :
```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 β¬](#table-of-solutions)
- ### DOM fundamentals
- #### Check the checkbox
scenario :
```python
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 :
```html
checkbox
Verify Code
```
code scenario :
```js
const button = document.getElementById('button');
button.addEventListener('click', () => {
});
```
Solution 1
js :
```js
const button = document.getElementById('button');
button.addEventListener('click', () => {
const checkbox = document.getElementById('checkbox');
checkbox.checked = true;
});
```
[Back to table β¬](#table-of-solutions)
- #### Get full-name from input
scenario :
```python
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 :
```html
Verify Code
```
code scenario :
```js
const button = document.getElementById('button');
button.addEventListener('click' , () => {
});
```
Solution 1
js :
```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 β¬](#table-of-solutions)
- #### Pop the balloons
scenario :
```python
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 :
```html
```
code scenario :
```js
const list = document.getElementById('list');
```
Solution 1
js :
```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 β¬](#table-of-solutions)
- ### Recursive functions
- #### Stop and restart the moving button
scenario :
```python
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 :
```html
Click Me
```
code scenario :
```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', () => {
});
```
Solution 1
js :
```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 β¬](#table-of-solutions)