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((accumulator, item) => {
return total + item}, 0)

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’

58
Q

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

A

.appendChild()

59
Q

Which method removes a specified child from a parent?

A

.removeChild()

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

61
Q

How can you access an element directly by its ID?

A

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

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…]

63
Q

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

A

With the
.innerHTML
and
.style
properties.

64
Q

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

A

.onclick

65
Q

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

A

document.getElementByID(“id”).value;

66
Q

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

A

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

67
Q

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

A

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

68
Q

How to turn a string into a number in JS?

A

Number(“324”)
=> 324

69
Q

How to convert a string into a number in JS?

A

parseInt(“string”, 10);

70
Q

How to turn a node list in an array?

A

const inputs = [node list]
const arrayFromNode = Array.from(inputs)

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 -->

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
click, ?, ?
1
click, ?, ?

A

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

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”

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]);
});

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);

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”);
});
});

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));

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();
});

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
80
Q

Should you use event.target or event.currentTarget?

A

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

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);

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>

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>

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
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.

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”

87
Q

How to add an HTML element to the body?

A

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

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

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

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

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!).

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.

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);
});

93
Q

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

A

curl

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.)

95
Q

What is a POST HTTP request?

A

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

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
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})
})

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.

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
});

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.

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.

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>
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.

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’;

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);
}

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);
});
}