Things to remember JS Flashcards

1
Q

Functions single line and multiline

A

singleline-block:
const sumNum = num => num + num;

multiline-block:
const sumNum = num => {
const sum = num + num;
return sum;
};

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

switch (rock-paper-scissor-example)

A

const getComputerChoice = () => {
const rnd = Math.floor(Math.randowm()*3);
switch(rnd) {
case 0:
return ‘rock’;
case 1:
return: ‘paper’;
case 2:
return: ‘scissors’;
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

do … while loop

A

runs until something anymore. runs ONCE before check!

let i = 0;
let counter;
do {
counter = counter + i;
i++;
} while (i < 5);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

4 methods to manipulate arrays

A

.push() - add new items to the END of an array

.pop() - remove an item from the END of an array

.shift() - remove an item from the START

.unshift(‘xy’) - move ‘xy to the START of an array

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How to change an item in an array?

A

myArray[index] = ‘new’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

while loops

A

let counter = 1;

while(counter < 4) {
console.log(counter);
counter++
}

Loop runs as long the contidion in the brackets is met

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

for loops

A

for (let counter; counter < 4; counter++) {
—code block—
}

(start value; condition to keep running; updating value)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How to find the position of an item in an array?

A

.indexOf() method

.indexOf(itemXY, start search)

e.g.: .indexOf(‘item’, 3) - Starts looking for ‘item’ beginning at position 4.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How to access propertys in objects?

A

Object.Propertyname (e.g. spaceship.color)

If propertyname contains numbers, spaces or special characters [] MUST be used.

spaceship[‘Fuel Type’]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is a property?

A

It’s a key: value pair inside an object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How to assign and delete Propertys from or to Objects?

A

Assignment:
object.propertyname = value
(e.g. spaceship[‘Fuel Type’] = ‘vegetable oil’)

Delete:
delete object.propertyname
(e.g. spaceship.color) löscht das gesamte key: value pair

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are methods?

A

Functions inside Objects:

methodName() {
—code block—
}

Es können keine Arrowfunctions verwendet werden.

mit this.propertyname hat man Zugriff auf values ausserhalb der Function innerhalb des objects.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How to determine the datatype of a value?

A

type of:

type of value (as a string)
(e.g. type of 42 returns ‘number’ (string!) )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How to delete items from an array by index?

A

const myArray0[‘x’, ‘y’, ‘z’]
delete myArray[index]
(e.g. delete myArray[1] deletes ‘y’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How to access a random item in an array?

A

myArray = [item1, item2, item3, item4]

rnd = Math.floor(Math.random()) * myArray.length

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How to invoke a method?

A

Object methods are invoked by appending the object’s name with the dot operator followed by the method name and parentheses:

alienShip.invade();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How to access the name of an property

A

.name

Access the name property just like with any object. You can use the dot operator to access a function’s property: functionName.name

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What are parameters?

A

Parameters allow functions to accept input(s) and perform a task using the input(s). We use parameters as placeholders for information that will be passed to the function when it is called.

function funcName(parameter1, parameter2, … ) {}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is a higher-order function?

A

A higher-order function is a function that either accepts functions as parameters, returns a function, or both!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What are iterators?

A

Iterators are methods called on arrays to manipulate elements and return values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is a callback function?

A

A callback function is a function passed as an argument into another function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is an argument?

A

An argument is a value passed into a function when the function is called. These values are assigned to parameters defined in the function’s declaration.

e.g.

function greet(name) {
console.log(Hello, ${name}!);
};
greet(‘John’) <— John is the argument

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What does forEach do?

A

.forEach() loops through the array and executes the callback function for each element.

groceries.forEach((groceryItem) => console.log(groceryItem));

grocerItem is a parameter that takes for each loop step the arrays element and (=>) passes it into a code block.
It doesn’t need a name because it’s commonly a anonymous function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What does map do?

A

When .map() is called on an array, it takes an argument of a callback function and returns a new array!

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

const bigNumbers = numbers.map(number => {
return number * 10;
});

New Array bigNumbers[10,20,30,40,50] //Original array bleibt unangetastet

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What does it mean when an arrow function has no curly brackets?

A

If the function only does a return statement no curly brackets needed. With only one parameter no brackets at all needed.

eg.:
var functionVariable = parameter1 => expression ;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What does filter do?

A

.filter() returns an array of elements after filtering out certain elements from the original array.

Like .map(), .filter() returns a new array.

e.g.
const words = [‘chair’, ‘music’, ‘pillow’, ‘brick’, ‘pen’, ‘door’];

const shortWords = words.filter(word => {
return word.length < 6;
});

word is each element of the array that gets filtered.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What does find Index do?

A

Finds the location of an element in an array.

Calling .findIndex() on an array will return the index of the first element that evaluates to true in the callback function.

e.g.
onst animals = [‘hippo’, ‘tiger’, ‘lion’, ‘seal’, ‘cheetah’, ‘monkey’, ‘salamander’, ‘elephant’];

const foundAnimal = animals.findIndex(animal => {return animal === ‘elephant’}); //Output = 7

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What does reduce do?

A

JavaScript’s reduce method condenses an array into a single value by applying a callback function to each element, updating an accumulator, and returning the final result.

const items = [5, 10, 15, 20]

const total = items.reduce((acc, item) => {
   return acc + item
}, 0);

return total;

The first argument is a function that adds the array item to the accumulator. The second argument is the starting value of the accumulator (in this case 0).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What does some?

A

The some() method of Array instances tests whether at least one element in the array passes the test implemented by the provided function.

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

// Checks whether an element is even
const even = (element) => element % 2 === 0;

console.log(array.some(even));
// Expected output: true

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What does every?

A

The every() method of Array instances tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

const isBelowThreshold = (currentValue) => currentValue < 40;

const array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isBelowThreshold));
// Expected output: true

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Arrow function sytnax

A

() => expression

param => expression
(param) => expression (<best practice)

() => {
statements
}

param => {
statements
}

(param1, paramN) => {
statements
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What is the diffrence between Expression and Statement?

A

Expressions yield values, and statements perform actions or sequences of actions. Arrow functions can be written to handle both scenarios, depending on whether you need to return a single value (expression) or execute multiple actions (statements).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

How to remove Duplicates?

A

With ‘Set’. It is a built-in object that allows you to store unique values of any type.

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

const removeDuplicates = (numbers) => […new Set(numbers)];
// ‘new’ creates a new object, Set makes sure the content is unique and with the spread … operator it is automatically put into an array//

console.log(removeDuplicates(numbers)); // Output: [1, 2, 3, 4, 5]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

What is the spread Operator?

A

The spread operator (…) in JavaScript allows elements of an iterable (like an array or string) to be expanded into individual elements. It can be used in array literals, function calls, and more to make copies, merge arrays, or pass multiple arguments.

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];

const mergedArray = […array1, …array2]; // Merges arrays
console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

Which of the following methods returns an array with values that evaluate to truthy based on the condition in the method’s block?

.forEach() / .filter() / .map() / .some()

A

.filter()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

How to turn a string into an array?

A

With .split()

Turns strings into substrings using a seperator like spaces (‘ ‘) and return them as array.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

What is a Ternary Operator?

A

A short-hand syntax to simplify if…else statements.

conditionCheck ? expressionIfTrue : expressionIfFalse

e.g.
let count = 0
count < 1 ? count++ : count–

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

SyntaxError

A

Code that cannot be interpreted by the compiler.
Scan your code for opened and closed brackets, braces, and parentheses and any invalid semicolons.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

Reference Error

A

This error will be thrown if you try to use a variable that does not exist. When this error is thrown, make sure all variables are properly declared.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

How to sort arrays?

A

With the .sort() method.
Called on an array it manipulates the array and sorts the content by default ascending and string unicode.

Otherwise we need a compare function, that returns a negative or equal value to sort ascending and postive if descending.

e.g.numbers:
ages.sort((a, b) => a - b)

e.g. strings:
names.sort((a, b) => a < b)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

How to copy a part of an array into a new one?

A

.slice()
.slice(start)
.slice(start, end)&raquo_space; end Index is not included!

Negative idex count backwards

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

What method lets items delete from an array as well add?

A

.splice(startIndex)&raquo_space; deletes all items from the start Index onwards.

.splice(start, deleteCount)&raquo_space; deletes a certain number of items after start

.splice(start, deleteC, item1, item2, … , itemN)&raquo_space; adds items to the array beginning at startIndex

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

How to sort an array of strings?

A

With .sort() and the compare function:

.sort((a, b) => {
if (a < b) return -1;
if (a > b) return 1;
return 0;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

What are the 4 pros of using getters/setters?

A

1) control access to object properties

2) change the internal representation of data without affecting external code that interacts with the object.

3) providing flexibility in how data is represented and accessed

4) They can improve code readability

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

What are the 4 cons of using getters/setters?

A

1) slight performance overhead compared to direct property access

2) Overusing getters and setters or implementing unnecessary logic within them can lead to increased complexity

3) Improperly implemented getters and setters, such as infinite loops, can introduce bugs and make debugging more challenging.

4) they may not be fully supported in older browsers or environments,

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

What is the shorthand syntax of a function in object literals?

A

You can drop the function keyword and just use the name of the function and parameters:

methodName (parameter) {
code block
},

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

How to create an object based on an prototype?

A

With Object.create(prototype)

prototype is the name of the object which the new object is based on.

e.g.

const newObject = Object.create(protoype)

newObject inherits the structure of the prototype.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

How to select an element from the DOM to interact with?

A

document.querySelector(CSS_SELECTOR),
and store it into a variable:

e.g.:
const button = document.querySelector(“#my-button”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

How to add or remove classes to an element on the DOM?

A

with classList.add(“class”) or classList.remove(“class”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

What is the general sytnax for an event listener?

A

const someElement = document.querySelector(“CSS_SELECTOR”)
someElement.addEventListener(“event_type”, () => {
// code to run when the event is triggered
// for example, changing innerText, etc
})

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

How to modify html elements on the DOM with JS?

A

document.tag.innerHTML = ‘<tag>...</tag>’;

e.G.:
document.body.innerHTML = ‘<h2>This is a heading</h2>’;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

How to modify text on the DOM with JS?

A

element.innerText = “new_text”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

How to disable a button on the DOM with JS?

A

button.disabled = true

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

How to add or remove a new or existing class from an element?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

How to add multiple white space to a string?

A

With .repeat(x)

x = number of repetitions

string${' '.repeat(x)}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

How do for … in / for … of loops work? And where do they get used?

A

for … in wird meist für Objects and … of für Arrays genutzt.

Syntax:
for (const key in object) {

}
for (const item of array) {

}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q

Syntax for styling elements on the DOM (like background)

A

document.querySelector(‘element’).style.backgroundColor = ‘color’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
58
Q

Which method will add a child element as the parent element’s last child node?

A

.appendChild()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
59
Q

Which method removes a specified child from a parent?

A

.removeChild()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
60
Q

How to hide an element?

A

If you want to hide an element, the .hidden property allows you to hide it by setting the property as true or false

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
61
Q

How can you access an element directly by its ID?

A

With the .getElementById(‘ID’) method which returns a single element.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
62
Q

How can you access an array of elements from the dom?

A

With the .getElementsByClassName() and .getElementsByTagName() methods, then call a single element by referencing its placement in the array with [0…]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
63
Q

How to modify an element by changing its contents or style respectively?

A

With the
.innerHTML
and
.style
properties.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
64
Q

How to add interactivity to a DOM element based on a click event?

A

.onclick

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
65
Q

How to get the set value of an ID of an html page?

A

document.getElementByID(“id”).value;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
66
Q

How to find out how many rows there are in a table?

A

document.getElementById(“myTable”).rows.length;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
67
Q

How to insert a row at the end of a <table>?

A

const table = document.querySelector(“table”);
let row = table.insertRow(-1);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
68
Q

How to turn a string into a number in JS?

A

Number(“324”)
=> 324

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
69
Q

How to convert a string into a number in JS?

A

parseInt(“string”, 10);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
70
Q

How to turn a node list in an array?

A

Array.from([node list])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
71
Q

How do you append content into a DOM element? (not append)

A

We use Element#insertAdjacentHTML:

const list = document.getElementById(“players”); // select a <ul>

list.insertAdjacentHTML(“beforeend”, “<li>Luke</li>”);

You can use beforebegin, afterbegin, beforeend or afterend:

<!-- beforebegin -->

<p>
<!-- afterbegin -->
the content
<!-- beforeend -->
</p>

<!-- afterend -->

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
72
Q

Name the following events occuring on <input></input>s:

1) A user enters the field
2) A user changes the value
3) A user leaves the field

A

1) ‘focus’
2) ‘change’
3) ‘blur’ (or ‘focusout’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
73
Q

How can we read data attributes from an HTML element?

A

by calling dataset and then the name of our attribute on the element.

const element = document.querySelector(“.card”);
const color = element.dataset.color;
console.log(color);
// => “red”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
74
Q

How do you iterate through an Object in JavaScript?

A

You can iterate through an array of its keys, defined by Object.keys(object).

const instruments = { “john”: “guitar”, “paul”: “bass”, “ringo”: “drums”, “george”: “guitar” };

Object.keys(instruments).forEach((beatle) => {
console.log(beatle + “ played the “ + instruments[beatle]);
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
75
Q

What happens when you click on a link? How do you prevent this from happening?

A

By default, clicking a link would:

navigate if the href is a URL
go to top if the href is #
Using preventDefault() will block this default behavior.

<a>Delete</a>
const bindConfirm = (element) => {
element.addEventListener(“click”, (event) => {
if (!confirm(“Are you sure you want to delete?”)) {
event.preventDefault();
}
});
};

document.querySelectorAll(“.confirmable”).forEach(bindConfirm);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
76
Q

How do you toggle an .img-circle class on all <img></img> on click?

A

It’s a three-step process:

First select all images with querySelectorAll
Then bind a listener to the click event
The callback for this listener uses event.currentTarget and updates its classes.
document.querySelectorAll(“img”).forEach((img) => {
img.addEventListener(“click”, (event) => {
event.currentTarget.classList.toggle(“img-circle”);
});
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
77
Q

How would you console.log() the instrument data of every band member in an unordered list? (<li class="musician" data-instrument="guitar">Joe Duplantier</li>)?

A

Iterators & Events

<ul>
<li>Joe Duplantier</li>
<li>Mario Duplantier</li>
<li>Christian Andreu</li>
<li>Jean Labadie</li>
</ul>

const bandMembers = document.querySelectorAll(‘.musician’);
bandMembers.forEach((member) => console.log(member.dataset.instrument));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
78
Q

How do we trigger playing an audio file when clicking a button?

A

By using the Audio constructor and calling .play() on it.

const button = document.querySelector(‘#clickme’);
const audio = new Audio(‘sound.mp3’);

button.addEventListener(‘click’, (e) => {
e.target.classList.add(‘disabled’);
audio.play();
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
79
Q

Can you list five different events that can be triggered by using a mouse?

A
  • dblclick -> When the user double-clicks the primary pointer button.
  • mousedown -> When the user presses a button on a mouse or other pointing device, while the pointer is over the element
  • mouseup -> When the user releases a button on a mouse or other pointing device, while the pointer is over the element
  • mousemove -> When a mouse or other pointing device is moved while over an element
  • wheel -> When the user rotates a mouse wheel or similar user interface component such as a touchpad
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
80
Q

Should you use event.target or event.currentTarget?

A

The rule of thumb is to always use event.currentTarget.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
81
Q

How can we add an unordered list to the DOM using only JavaScript?

A

const abba = [“Bjorn”, “Benny”, “Anni-frid”, “Agnetha”];
let ul = document.createElement(“ul”);

abba.forEach((member) => {
let li = document.createElement(“li”);
li.innerText = member;
ul.appendChild(li);
});

document.body.appendChild(ul);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
82
Q

How can we add attributes to an element using JavaScript?

A

We can add an attribute to an element by using Element.setAttribute()

<button>Hello World</button>
const button = document.querySelector(“button”);

button.setAttribute(“name”, “helloButton”);
button.setAttribute(“disabled”, “”);
<button>Hello World</button>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
83
Q

How can we remove attributes from an element using JavaScript?

A

We can remove an attribute from an element by using Element.removeAttribute()

button.removeAttribute(“disabled”)
<button>Hello World</button>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
84
Q

Can you list five different events that are triggered by the Window object?

A
  • resize -> Fired when the window has been resized
  • copy -> When the user initiates a copy action through the browser’s user interface
  • paste -> When the user initiates a paste action through the browser’s user interface
  • pageshow -> When the browser makes the document visible due to navigation tasks
  • pagehide -> When a page is hidden from view by navigation, like a back or forward button
  • DOMContentLoaded -> Fired when the document has been completely loaded and parsed
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
85
Q

What does Event.currentTarget refer to?

A

Event.currentTarget always refers to the element to which the event handler has been attached, as opposed to Event.target, which identifies the element on which the event occurred and which may be its descendant.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
86
Q

How can you pass data from HTML to JavaScript?

A

You can use the dataset API:

<div>
Boris Paillard
</div>

Then you can access in JavaScript the variables stored in data- attributes:

const boris = document.getElementById(‘user’);
console.log(boris.dataset.uid);
// => “2471555”
console.log(boris.dataset.githubNickname); // Note the auto-camelization of the key!
// => “Papillard”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
87
Q

How to add an HTML element to the body?

A

with .append or .appendChild

const paragraph = document.createElement(“p”);
const text = document.createTextNode(“This is new.”);
paragraph.append(text);

const element = document.getElementById(“body”);
element.appendChild(paragraph);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
88
Q

Hot to get the next HTML Element with JS?

A

.nextElementSibling

const position = document.querySelector(“div”);&raquo_space;> first div in the HTML

position.nextElementSibling;&raquo_space;> returns the element immediately following the specified one in its parent’s children list

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
89
Q

How to get the first element after selecting the parent HTML element in JS?

A

.firstElementChild

returns an element’s first child Element

To get all child nodes, including non-element nodes like text and comment nodes, use Node.firstChild

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
90
Q

In which part of the request should we pass the authentication token?

A

The authentication token has to be passed in the headers of the request. If you are using Postman, you can find the different authentication options in the Authentication tab (but they will still be added to the request headers!).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
91
Q

What is a PATCH HTTP request?

A

A request executed to update existing data such as your name or address when you edit your profile.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
92
Q

Give an example of making an API GET request in Javascript using fetch to the endpoint https://uselessfacts.jsph.pl/api/v2/facts/random.

A

fetch(‘https://uselessfacts.jsph.pl/api/v2/facts/random’)
.then(response => response.json())
.then((data) => {
console.log(data);
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
93
Q

What command line tool can you use to make HTTP requests?

A

curl

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
94
Q

What are the two parts of a GET HTTP request?

A

Remember, GET is called the HTTP verb.

URL
Headers (User-Agent, Referer, Cookies, etc.)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
95
Q

What is a POST HTTP request?

A

A request executed to send new data such as email and password to sign in.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
96
Q

What are the three parts of a POST HTTP request?

A

Remember, POST is called the HTTP verb.

  1. URL
  2. Headers (User-Agent, Referer, Cookies, etc.)
  3. Body
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
97
Q

How do you make an Ajax POST request with fetch?

A

You need to pass some information as a second argument to fetch:

The HTTP method (aka verb)
The HTTP headers (telling the server we’re sending some JSON)
The HTTP body, with the actual JSON being posted
const emailValue = document.getElementById(“email”).value
const passwordValue = document.getElementById(“password”).value

fetch(“https://reqres.in/api/register”, {
method: “POST”,
headers: {
“Content-Type”: “application/json”
},
body: JSON.stringify({“email”: emailValue, “password”: passwordValue})
})

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
98
Q

What are the three states of a Promise?

A

> pending: initial state, neither fulfilled nor rejected.
fulfilled: meaning that the operation was completed successfully.
rejected: meaning that the operation failed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
99
Q

What’s the intermediate step you need to perform after fetch when calling a JSON API endpoint?

A

You need to parse the response with .json():

fetch(“https://swapi.dev/api/people/”)
.then(response => response.json())
.then((data) => {
console.log(data); // data is now a JS object
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
100
Q

Why do we need to import es-module-shims before the importmap?

A

To make sure our JavaScript code works with older browsers, as importmap is a new feature, not fully compatible.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
101
Q

What is a Response in AJAX?

A

It’s an interface of the fetch API that represents the response to a HTTP request.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
102
Q

What are Import Maps?

A

An import map is a JSON object that allows developers to control how the browser resolves module specifiers when importing JavaScript modules.

<script>
{
  "imports": {
    "bootstrap": "https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js",
    "sweetalert2": "https://cdn.jsdelivr.net/npm/sweetalert2@11.7.1/+esm"
  }
}
</script>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
103
Q

What is a Response object?

A

The Response object represents the HTTP response to a request, usually as the result of a fetch() request.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
104
Q

How do we import and organise our JavaScript external library imports using importmaps?

A

We first add the importmap script on the HEAD of our html with the atrtibute type=”importmap”

<!-- index.html -->

<the-script>
{
"imports": {
"bootstrap": "https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js",
"sweetalert2": "https://cdn.jsdelivr.net/npm/sweetalert2@11.7.1/+esm"
}
}
</the-script>

<!-- rename the-script into script after copy-paste -->

Then we can import libraries into our JS files if the main file is of the type=”module”

<!-- index.html -->

<the-script></the-script>

<!-- rename the-script into script after copy-paste -->

And import libraries where needed:

// javascript/application.js
import Swal from ‘sweetalert2’;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
105
Q

Can you describe a POST HTTP request?

A

Remember, POST is called the HTTP verb. It needs:

URL
Headers (User-Agent, Referer, Cookies, etc.)
Body

106
Q

What does a Promise object allow us to do?

A

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. It allows you to associate handlers with an asynchronous action’s eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

107
Q

In Vue, how do you bind click event to a button?

A

We can use v-on or @.

<button>
<button @click=”doSomething”></button>

108
Q

In Vue, how do you iterate through a list in HTML?

A

We can use v-for:

<div>
...
</div>

109
Q

In Vue, what syntax do you use to bind data in HTML?

A

The double mustache syntax:

{{}}

110
Q

How do you create a Vue instance?

A

In JS, use createApp() and mount it on an HTML element.

import { createApp } from “vue”;

createApp({
data() {
return {
message: “Hello from Vue.JS”
}
}
}).mount(‘#app’)
In HTML, create a div where the Vue instance will mount.

<div> </div>

111
Q

Stimulus JS
What is this.element?

A

this.element is the element the Stimulus controller is bound to.

112
Q

What is a value in Stimulus JS and how is it used?

A

A Stimulus JS value is a way to store and share data between actions and targets within a Stimulus controller. It is defined as a static property on a controller using the values keyword, and can be accessed and updated using the this.myNameValue syntax (where myName is whatever name you’ve given your value - for example, this.userBirthdayValue) within an action or a target.

<div>
<button>Greet Marcel</button>
<div></div>
</div>

export default class extends Controller {
static targets = [‘message’];
static values = { name: String };

greet() {
this.messageTarget.innerText = Hello, ${this.nameValue}!;
}
}

113
Q

How do you define a target in a Stimulus controller?

A

A target in a Stimulus controller is defined using the static targets property, which is an object that maps target names to DOM elements.

export default class extends Controller {
static targets = [“button”, “link”]
// […]
}

114
Q

What’s the scope of a stimulus controller?

A

When Stimulus connects a controller to an element, that element and all of its children make up the controller’s scope.

115
Q

How do I create a Stimulus JS controller?

A

To create a Stimulus JS controller, you need to define a class that extends the Controller base class and define one or more actions on it.

// src/controllers/hello_controller.js
import { Controller } from “stimulus”

export default class extends Controller {
// Add an action
}

116
Q

What is the purpose of the disconnect() method in a Stimulus controller?

A

The disconnect() method is called when a controller is disconnected from the DOM, and is used to clean up any state or event listeners created in the connect() method.

117
Q

How can you pass data from HTML to a Stimulus controller if we don’t want to use values?

A

Data can be passed from HTML to a Stimulus controller using data-attributes, which can be accessed in the controller using the data property. For example:

<div>

</div>

// src/controllers/search_controller.js
import { Controller } from “stimulus”

export default class extends Controller {
connect() {
const date = this.data.get(“current-date”);
console.log(date);
}
}

118
Q

How do I register a Stimulus JS controller with the name disable_button_controller.js?

A

You can register a controller by calling the register method on the Application object and passing in the name of the controller and its class.

import DisableButtonController from “./controllers/disable_button_controller.js”
Stimulus.register(“disable-button”, DisableButtonController)

119
Q

How do you connect a Stimulus controller to an HTML element?

A

Through a specific naming convention. The JS class name should be camel case (ex: controllerName). And we pass the data attribute in the HTML like so: data-controller=”controller-name”

A Stimulus controller looks something like this:

// src/controllers/hello_controller.js
import { Controller } from “stimulus”

export default class extends Controller {
}
To connect it to an HTML element, you simply have to pass a data-controller attribute to the HTML element:

<div>
<input></input>
<button>Greet</button>
</div>

120
Q

How can I add an event listener on click to display something if the button looks like this <button>Show</button>

A

<button>Show</button>

121
Q

What’s the equivalent of .addEventListener in Stimulus?

data-action
1
data-action

A

Adding a data-action=”event->controller-name#methodName” to the html tag.

122
Q

What’s the equivalent of document.querySelector in Stimulus?

A

Adding a data-controller-name-target=”input” to the html tag.

123
Q

How can I select the target from the Stimulus controller if the html looks like this <button>Show</button>

A

In the toggle_display_controller.js you can add this.buttonTarget inside a function to get the button element

124
Q

What are the three main concepts of Stimulus?

A
  • Data controllers, which connect DOM elements to JavaScript controller classes
  • Data targets, which select DOM elements within a controller
  • Data actions, which bind DOM events to controller methods
125
Q

How to remove white space from strings?

A

.trim()
.trimStart() or .trimEnd() for only one side

126
Q

How to downcase strings?

A

.toLowerCase()

127
Q

How to insert a row at the end of a table?

A

const table = document.querySelector(‘.table’);
let row = table.insertRow(-1);

128
Q

How to insert a cell at the start of a row?

A

cell1 = row.insertCell(0);

129
Q

How to at content to a cell?

A

let cell1 = row.insertCell(0);
cell1.innerText = “content”;

130
Q

How to reverse a string in JS?

A

string.split(‘’).reverse().join(‘’);

131
Q

How can you check if a string ends with another string?

A
function solution(str, ending){
  return str.endsWith(ending);
}

The function returns either true, if the ending is the end of the main string. Otherwise it will return false.

132
Q

How can you run code after the DOM is fully loaded?

A

document.addEventListener(“DOMContentLoaded”, …)

133
Q

How do you define and use a CSS custom property (variable)?

A

Define a custom property using
–propertyName: value;
and use it with
var(–propertyName).

134
Q

How do you delay the execution of a function in JavaScript?

A

Use setTimeout(function, delay) to execute a function after a specified delay in milliseconds.

135
Q

How do you generate a random integer within a specific range in JavaScript?

A

Use Math.floor(Math.random() * range) to generate a random integer from 0 to range - 1

136
Q

How do you generate a random uppercase letter in JavaScript?

A

Use
let x = Math.floor(Math.random() * (90 - 65 + 1)) + 65
to generate a random ASCII value within the range of uppercase letters, then convert it to a character using
String.fromCharCode(x).

137
Q

How do you convert an ASCII value to its corresponding character in JavaScript?

A

Use String.fromCharCode(asciiValue) to convert an ASCII value to its character representation.

138
Q

What structure do APIs commonly use to return a list of items?

A

An array of objects.

139
Q

How can you iterate over an array of Objects in JavaScript?

A

Using a for…of loop.

140
Q

What method do you use to parse a JSON response in JavaScript?

A

response.json()

141
Q

How to get the square number in JS?

A

Math.sqrt(n)

//Math.sqrt(9); // is 3

142
Q

How can you create a Promise that resolves after a timeout?

A

function wait(duration) {
return new Promise((resolve) => {
setTimeout(resolve, duration);
});
}

143
Q

How can you refer to the first capture group that was matched by a regular expression?

A

‘$1’ refers to the first capture group.

string.replace(/([A-Z])/g, ‘ $1’)

All (because of /g for global) Uppercase Letters will be replaced by a space and the refered uppercaseletter)

144
Q

How can you access the last element of an array in JS?

A

With .at(-1).

It might not work in old browsers. To be safe this is the other way:

array[array.length - 1]

145
Q

How would you create a new IntersectionObserver instance to observe the page?

A

by passing in a callback function and options

const newObserver = new IntersectionObserver(function (
entries,
newObserver
) {
entries.forEach(entry => {
if (!entry.isIntersecting) {
div.classList.add(‘someClass’);
} else {
div.classList.remove(‘someClass’);
}
});
}, options);

146
Q

How can you alter e.g. when the IntersectionObserver starts acting?

A

With defining options and use them in the new IntersectionObserver instance:

const options = { someOptions };

147
Q

How can you create an offset for the IntersectionObserver?

A

const options = {
rootMargin: “-200px 0px 0px 0px”
};

I will offset the top by 200px when scrolling down

148
Q

How do you start youre IntersectionObserver?

A

elementObserver.observe(element);

149
Q

How to get the time in JS?

A

const now = new Date();
let hours = now.getHours();
let minutes = now.getMinutes();
let seconds = now.getSeconds();

150
Q

How to convert a number into a string in JS?

A

number.toString();

151
Q

What does that do?

updateTime();
setInterval(updateTime, 1000);

A

It initially calls a function named updateTime()

Than it sets an intervall of 1000ms after it repeatedly calls the updateTime function.

152
Q

How can you add a 0 to a single digit at the beginning in JS?

A

.padStart(2, ‘0’)

Pads the string with leading zeros until it reaches a length of 2 characters. For example, if hours is 5, it becomes ‘05’.

153
Q

How can you retrieve the ASCII Code for a character in JS?

A

.charCodeAt(index);

let char = ‘-‘;
let asciiValue = char.charCodeAt(0);
console.log(asciiValue); // Output: 45

154
Q

How do you set up an image for lazy loading in HTML?

A

Replace the src attribute with data-src to prevent the image from loading initially.

155
Q

What JavaScript method is used to select all elements with a specific attribute?

A

document.querySelectorAll(‘[data-src]’)

156
Q

What is the purpose of the preloadImage function in lazy loading?

A

AIt sets the src attribute of the image from the data-src attribute when the image is about to enter the viewport.

157
Q

How to split multiline strings in javascript in an array of lines?

A

you need to use a regular expression that matches the various forms of line breaks (\r\n, \n, and \r).

string.split(/\r?\n|\r/);

The regular expression \r?\n|\r covers all these cases by matching any of the possible line break sequences.

158
Q

How to matche any uppercase letter in JS?

A

With the regular expression /[A-Z]/

159
Q

How do you prevent split(/[A-Z]/) from removing the matched character in JavaScript?

A

Use a positive lookahead assertion, like “.split(/(?=[A-Z])/)”.

160
Q

How do you uppercase the first character of a string in JavaScript?

A

Combine charAt and toUpperCase methods:

str.charAt(0).toUpperCase() + str.slice(1).

The first part upcases the first Letter but also ONLY returns that letter. The second part ensures that the rest of the string also gets added back.

161
Q

How do you ensure string start with an uppercase letter (and leave every other letter) in JavaScript?

A

Use map with charAt(0).toUpperCase() for the first letter and slice(1).toLowerCase() for the rest.

162
Q

How do you check if a number is prime in JavaScript?

A

You can efficiently check if a number num is prime by:

  • Ensuring num is greater than 1.
  • Handling special cases for small primes (2 and 3).
  • Checking divisibility by 2 and 3.
  • Using a loop to test divisors from 5 up to the square root of num, skipping unnecessary checks using increments of 6 (i += 6).
163
Q

What is the efficient loop for checking primes in JavaScript?

A

Use a loop that starts at 5 and increments by 6 (i += 6) up to the square root of num. Inside the loop, check divisibility of num by i and i + 2.

164
Q

Why is incrementing by 6 efficient in prime checking?

A

Incrementing by 6 skips even numbers and numbers divisible by 3 (since i + 2 is even and divisible by 3), reducing unnecessary checks and making the prime checking process faster.

165
Q

What event is fired when a form is submitted?

A

The ‘onsubmit’ event.

166
Q

What attribute can be used to turn off HTML validation in a form?

A

The ‘novalidate’ attribute.

167
Q

When is setCustomValidity typically used?

A

Within event listeners to dynamically control form validation based on specific conditions.

168
Q

How do you clear a custom error message set with setCustomValidity?

A

Call setCustomValidity(“”) on the form field.

169
Q

One liner to filter out even numbers:

const scores = [85, 92, 73, 98, 80];

A

const evenScores = scores.filter(num => num % 2 === 0);

170
Q

One liner to get squares of numbers:

const sideLengths = [5, 3, 7];

A

const areas = sideLengths.map(num => num * num);

171
Q

One liner to reverse a string:

const str = “Hello, world!”;

A

const reversedStr = str.split(‘’).reverse().join(‘’);

172
Q

One liner to figure out whether a specific attribute (such as “email”) exists in a user object.

A

// Check if the user object has an ‘email’ property

const hasEmail = “email” in user;

// hasEmail will be false because the ‘email’ property is not present in the user object

173
Q

How about creating an operation to greet users but giving a backup value in case no name is provided?

A

const greet = (name = “Guest”) => Hello, ${name}!;
console.log(greet());&raquo_space; Hello, Guest!
console.log(greet(“Bob”));&raquo_space; Hello, Bob!

174
Q

One liner to remove empty values or null elements from arrays.

const numbers = [1, 0, null, 3];

A

const compactNumbers = numbers.filter(Boolean);

// compactNumbers will be [1, 3] because Boolean(1) is true, Boolean(0) is false, Boolean(null) is false, and Boolean(3) is true

175
Q

What are classes in JavaScript?

A

Classes are templates for objects.

176
Q

What happens when a new instance of a class is created in JavaScript?

A

JavaScript calls a constructor method.

177
Q

Which keyword is used to create a subclass in JavaScript?

A

The extends keyword.

178
Q

What is a constructor method in JavaScript?

A

A constructor method is a special method for creating and initializing an object created within a class.

179
Q

Give an example of creating a class with a constructor in JavaScript.

A
class Animal {
  constructor(name) {
    this.name = name;
  }
}
180
Q

How do you instantiate a new object from a class in JavaScript?

A

Using the new keyword followed by the class name and any required arguments for the constructor.

const dog = new Animal('Buddy');
181
Q

What is method overriding in JavaScript?

A

Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass.

182
Q

Provide an example of getter and setter methods in a JavaScript class.

A

```class Person {
constructor(name) {
this._name = name;
}

get name() {
return this._name;
}

set name(newName) {
this._name = newName;
}
}

const person = new Person(‘John’);
console.log(person.name); // Output: John
person.name = ‘Doe’;
console.log(person.name); // Output: Doe```

183
Q

How do you ensure a method in a subclass correctly overrides and utilizes a parent class method in JavaScript?

A

Use the super keyword followed by the method name with parentheses and arguments. If overriding a method, ensure it accepts the necessary parameters and returns the result of super.methodName(args).

184
Q

What is the correct way to call a parent class’s method from a subclass in JavaScript?

A

super.methodName(arguments). This calls the parent class’s method with the provided arguments.

185
Q

What is the purpose of using getters in JavaScript classes?

A

Getters allow access to an object’s properties. They provide a way to get the value of an object’s private properties without directly accessing the property itself.

186
Q

How do you call a static method in JavaScript?

A

Static methods are called on the class itself, not on instances of the class. Use ClassName.staticMethodName().

187
Q

How do you export named resources in ES6?

A
export const resourceToExport = value;
~~~
or directly in front of the variable declaration:
export const resourceToExport = value;```
188
Q

How do you access a getter in JavaScript?

A

Getters are accessed as properties, not called as functions. Example: objectName.propertyName.

189
Q

How do you import named resources in ES6?

A
import { exportedResourceA, exportedResourceB } from '/path/to/module.js';
190
Q

How can you rename an imported resource to avoid naming collisions?

A
import { exportedResource as newResourceName } from '/path/to/module';
191
Q

How do you export a default value in a module?

A
const resources = { valueA, valueB };
export default resources;

or directly:

export default value;
192
Q

How do you import a default export?

A
import importedResources from '/path/to/module.js';

Note: The default value may be given any name by the importer.

193
Q

How do you export multiple functions using named exports in ES6?

A
function functionName() { /* logic */ }
export { functionName };

or:

export function functionName() { /* logic */ }
194
Q

How would you update an HTML file to properly load a JavaScript module?

A

Add the type=”module” attribute to the script tag:

<script type="module" src="./module.js"> </script>
195
Q

How do you use the as keyword to rename imported resources?

A

```import { exportedResource as newResourceName } from ‘/path/to/module’;
~~~
This helps avoid naming collisions and clarify the purpose of the imported resource.

196
Q

Provide an example of exporting multiple named resources and importing them in another file.

A

```// module.js
export const resourceA = valueA;
export const resourceB = valueB;

// main.js
import { resourceA, resourceB } from ‘./module.js’;
~~~

197
Q

How can you combine multiple functions into a single default export?

A
const functionA = () => { /* logic */ };
const functionB = () => { /* logic */ };

const resources = { functionA, functionB };
export default resources;
198
Q

How do you import and destructure a default export object in ES6?

A
import resources from '/path/to/module.js';
const { functionA, functionB } = resources;
199
Q

What does array destructuring in JavaScript allow you to do?

A

Array destructuring allows you to unpack values from arrays into separate variables in a concise and readable manner.

200
Q

How does array destructuring work with array literals?

A

You can use array destructuring to directly assign elements of an array to variables. For example: let [a, b] = [1, 2]; assigns 1 to a and 2 to b.

201
Q

What is an example of using array destructuring with .split()?

A

You can split a string and destructure the result: let [firstName, lastName] = “John Doe”.split(‘ ‘); assigns “John” to firstName and “Doe” to lastName.

202
Q

How do you create an error using the Error() function?

A

A: You can create an error by using the Error() function, e.g., let error = new Error(‘This is an error message’);.

203
Q

How do you throw an error object using the throw keyword?

A

You can throw an error object using the throw keyword, e.g., throw new Error(‘This is an error message’);

204
Q

How do you use the try…catch statement to handle thrown errors?

A
try {
    // code that may throw an error
} catch (error) {
    // code to handle the error
}
205
Q

Explain the expression Math.min(Math.max(value, lowerBound), upperBound).

A

This expression clamps value within the range [lowerBound, upperBound]. It ensures value is at least lowerBound and at most upperBound.

206
Q

What does Math.max(value, lowerBound) do?

A

It returns the larger of value and lowerBound, ensuring value is not less than lowerBound.

207
Q

Provide an example of clamping a value between 0 and 100.

A
let lowerBound = 0;
let upperBound = 100;
let value = 150;

let clampedValue = Math.min(Math.max(value, lowerBound), upperBound);
console.log(clampedValue); // Output: 100
208
Q

What is a simpler alternative to readline for synchronous user input?

A

The prompt-sync Node module.

209
Q

How do you require and call prompt-sync?

A

const name = prompt(‘What is your name?’);
console.log(Hey there ${name});

210
Q

How do you allow users to exit with Ctrl + C using prompt-sync?

A
const prompt = require('prompt-sync')({sigint: true});
211
Q

How do you convert user input to a number in prompt-sync?

A
const num = prompt('Enter a number: ');
console.log(Number(num) + 4);
212
Q

What is the syntax for Array.from()?

A
Array.from(arrayLike [, mapFn [, thisArg]])
213
Q

Create an array with ‘height’ rows, each row being a new array of ‘width’ filled with fieldCharacter

A
Array.from({ length: height }, () => new Array(width).fill(fieldCharacter))
214
Q

You have an 2D Array. How can you get an array ‘positions’ with all coordinates in that 2D Array?

A
const positions = [];
    for (let row = 0; row < this.height; row++) {
      for (let col = 0; col < this.width; col++){
        positions.push([row][col]);
      }
    }
215
Q

How can you swap two elements in an array using JavaScript destructuring assignment?

A

You can swap two elements in an array using JavaScript destructuring assignment with the following syntax:

[positions[i], positions[j]] = [positions[j], positions[i]];

This line swaps the elements at indices i and j in the positions array.

216
Q

How to state an array with 9 similiar items like null?

A

Array(9).fill(null);

217
Q

How to create a copy of an array?

A

arrayCopy = array.slice();

218
Q

How can you return the query string part of the current URL, including the ?.

For example, if the URL is https://example.com/page?name=John&age=30

A

window.location.search

219
Q

How can you easily create, parse, manipulate, and iterate over query string parameters in a URL.

A

With the JavaScript interface URLSearchParams

220
Q

How do you create a URLSearchParams object from the current URL?

A

Use

new URLSearchParams(window.location.search)
to create a URLSearchParams object from the query string of the current URL.
221
Q

How do you retrieve a specific query parameter using “URLSearchParams”?

A

Use query.get(‘name’) to retrieve the value of the query parameter name. If the URL is ?name=John, it returns ‘John’.

222
Q

How can you check if a query parameter exists using URLSearchParams?

A

Use

query.has('name')
to check if the query parameter name exists in the URL.
223
Q

How do you append a new query parameter using URLSearchParams?

A

Use

query.append('key', 'value')
to add a new key-value pair to the query string. If key already exists, it adds another instance.
224
Q

How do you remove a query parameter using URLSearchParams?

A

Use

query.delete('name')
to remove the “name” parameter and its value from the query string.
225
Q

What does

query.toString()
do in URLSearchParams?
A

Converts the query parameters back into a string format, excluding the leading “?”.

226
Q

How do you iterate over all key-value pairs in URLSearchParams?

A

Use

for (let [key, value] of query.entries())
to loop through all key-value pairs in the query string.
227
Q

How can you merge two arrays?

A

With the spread operator …

mergedArray = [...array1, ...array2]
228
Q

What is the outcome of the following code?

assert.ok(false);
A

An error is thrown.

assert.ok() has two outcomes: throw an error or return nothing.

229
Q

describe blocks can be nested to reflect the structure of the code which they are testing. Which test block best reflects the structure of the following code?

const cup = {};
cup.pour = () => { return 'Poured once!'; }
cup.fill = () => { return 'Cup filled!'; }
A
describe('cup', () => {
    describe('.pour', () => {

    });
    describe('.fill', () => {

    });
});

Since .fill() and .pour() are both methods of cup they should both be nested inside a single describe() block for cup.

230
Q

Which is the correct syntax for a Mocha it() function?

A

The it() function takes two arguments. First, a string that will be printed in the test suite, then a callback function that executes the code to be tested.

it('Add 3 and 4 together to equal 7',() => {
    assert.ok(3+4===7)
});
231
Q

How can you calculate the factorial of a number variable like num?

A
factorial(inputNumber) {
    if(inputNumber === 0) {
      return 1;
    }

    for (let i = inputNumber - 1; i >= 1; i--) {
      inputNumber *= i; 
    }

    return inputNumber
  }
232
Q

What is the diffrence between setTimeOut() and setIntervall.

A

Both have the same structure:

setInterval/setTimeOut(() => {
  alert('Are you paying attention???')
}, 3000)

setInterval execudes the code Block after each 3000ms, while setTimeOut will wait 3000ms to execute the code.

233
Q

How do you create a JavaScript Promise?

A

You create a Promise using the new Promise() constructor, which takes an executor function with two arguments: resolve and reject. These functions control whether the promise is fulfilled or rejected.

const promise = new Promise((resolve, reject) => {
  // asynchronous operation
  if (/* success condition */) {
    resolve('Success value');
  } else {
    reject('Error reason');
  }
});
234
Q

What is the purpose of the executor function in a Promise?

A

The executor function is the function passed to the Promise constructor. It is called immediately and has two arguments, resolve and reject. It contains the logic that decides if the promise will be resolved or rejected.

235
Q

How do you handle a resolved Promise?

A

You handle a resolved Promise by using the .then() method. It takes a function that is executed when the Promise is successfully fulfilled.

promise.then((result) => {
  console.log(result); // logs "Success value"
});
236
Q

How do you handle a rejected Promise?

A

You handle a rejected Promise using the .catch() method. It catches any errors or rejections that occur in the Promise chain.

promise.catch((error) => {
  console.error(error); // logs "Error reason"
});
237
Q

What is Promise chaining?

A

Promise chaining is the practice of performing multiple asynchronous operations sequentially by returning a new Promise from the .then() method. This allows you to handle the result of one operation before starting the next.

promise
  .then((result) => processResult(result))
  .then((processed) => saveResult(processed))
  .catch((error) => console.error(error));
238
Q

What is Promise.all() used for?

A

Promise.all() is used to run multiple promises in parallel and wait for all of them to resolve. If any promise is rejected, Promise.all() immediately rejects. It returns an array of results if all promises are fulfilled.

Promise.all([promise1, promise2])
  .then((results) => console.log(results))
  .catch((error) => console.error(error));
239
Q

How do Promises handle errors?

A

Promises handle errors using the .catch() method. Any error or rejection that occurs in the promise chain is caught by .catch(). Errors in .then() callbacks are also propagated down to the nearest .catch().

240
Q

When do you use .finally() in Promises?

A

.finally() is a method that gets executed after a promise is settled (whether fulfilled or rejected). It’s useful for cleanup tasks that should run regardless of the outcome.

promise
  .then((result) => console.log(result))
  .catch((error) => console.error(error))
  .finally(() => console.log('Operation complete'));
241
Q

How do you turn a .json file in a JS Object, and how a JS Object into a .json file?

A

With JSON.parse and JSON.stringify:

const jsObject = JSON.parse(jsonData);

const jsonData = JSON.stringify(jsObject);
242
Q

How do you create a simple GSAP timeline animation that moves an element horizontally?

A
let timeline = gsap.timeline();
timeline.to('.animated-element', { x: 800 });

This code moves the element with class .animated-element by 800 pixels along the X-axis.

243
Q

What properties should you define for a ScrollTrigger object in GSAP?

A
  • trigger: The DOM element that triggers the animation.
  • start and end: Define when the animation starts and ends relative to the scroll position.
  • scrub: Syncs the animation with the scroll position.
  • markers: Can be set to true for visual debugging.
244
Q

How does changing the start and end properties of ScrollTrigger affect the animation timing?

A

The start and end properties determine the scroll positions at which the animation begins and ends. Adjusting these can speed up or slow down the animation, as well as shift when it occurs during the scroll.

245
Q

How can you control an animation’s duration and behavior with ScrollTrigger using the scrub property?

A
  • Set scrub: true to sync the animation with the scroll position.
  • Set scrub: false for the animation to play independently of the scroll.
  • Example: scrub: true creates smooth, continuous scrolling animations.
246
Q

How do toggle actions in ScrollTrigger control animations when entering and leaving the viewport?

A
gsap.to('.animated-element', {
  scrollTrigger: {
    trigger: '.animated-element',
    toggleActions: 'play pause reverse reset'
  }
});

This configuration plays the animation when entering the viewport, pauses when leaving, reverses when scrolling back, and resets when re-entering.

247
Q

How can you visualize ScrollTrigger’s start and end points during development?

A

Set the markers property to true in the ScrollTrigger object. This will display visual markers in the viewport showing where the scroll animation starts and ends.

248
Q

What is the effect of using negative values for the start and end properties in ScrollTrigger?

A

Negative values for start or end can delay the animation, making it begin or end before the element reaches the viewport. For example, start: “-50%” will start the animation 50% above the top of the element.

249
Q

How can you use HTML data attributes in JS to toggle elements?

A
let toggleButton = document.getElementById('toggleBtn');
let box = document.querySelector('.box');

toggleButton.addEventListener('click', () => {
  let isVisible = box.dataset.visible === "true";
  box.dataset.visible = isVisible ? "false" : "true"; // Toggle value
});

This will toggle the visibility of a button.

250
Q

What is the purpose of Object.values() in JavaScript, and what does it return?

A

Object.values() returns an array of the values of an object’s properties, ignoring the keys.

const obj = { key1: "value1", key2: "value2" };
console.log(Object.values(obj)); // ["value1", "value2"]
251
Q

What does Object.entries() return when called on an object?

A

Object.entries() returns an array of the object’s key-value pairs, where each pair is represented as a [key, value] array.

const obj = { key1: "value1", key2: "value2" };
console.log(Object.entries(obj)); // [["key1", "value1"], ["key2", "value2"]]
252
Q

How can you map over the values of an object passed as a prop in React to render them?

A

Use Object.values() to convert the object into an array of its values, then .map() over the array to render each value in a React component.

function Component({ description }) {
  return (
    <div>
      {Object.values(description).map((value, index) => (
        <p key={index}>{value}</p>
      ))}
    </div>
  );
}
253
Q

Why should you use a key prop in React when rendering a list?

A

The key prop helps React identify which elements have changed, been added, or removed, allowing it to optimize rendering.

{items.map((item, index) => (
  <p key={index}>{item}</p>
))}
254
Q

What is the purpose of Object.keys() in JavaScript, and what does it return?

A

Object.keys() returns an array of the keys (property names) of an object.

const obj = { key1: "value1", key2: "value2" };
console.log(Object.keys(obj)); // ["key1", "key2"]
255
Q

What is the difference between Object.values(), Object.entries(), and Object.keys()?

A
  • Object.values(): Returns an array of values.
  • Object.entries(): Returns an array of key-value pairs.
  • Object.keys(): Returns an array of keys.
256
Q

How do you generate a drob cap in css?

A

p::first-letter {
-webkit-initial-letter: 2;
initial-letter: 2;
padding: 0.25rem;
}

257
Q

How can you convert a Set into an Array?

A
Array.from(set)

converts a Set into an array, preserving only unique values from the Set.

258
Q

What is the role of JSON.stringify() in JavaScript?

A

JSON.stringify() converts a JavaScript object (such as an array or object) into a JSON string. This is useful for serialization, saving, or transmitting data.

259
Q

What does JSON.parse() do in JavaScript?

A

JSON.parse() converts a JSON string back into a JavaScript object or array. It reverses the effect of JSON.stringify().

260
Q

Why is JSON.parse() used in conjunction with Array.from() when working with Set?

A

When storing objects in a Set as strings (using JSON.stringify()), JSON.parse() is used after converting back to an array with Array.from() to turn the strings back into the original JavaScript objects or arrays.

261
Q

How can you ensure uniqueness when dealing with complex objects in JavaScript?

A

You can ensure uniqueness by stringifying the objects with JSON.stringify() before adding them to a Set. Since Set only stores unique values, it will eliminate duplicates based on the string representation of the object.