Things to remember JS Flashcards
Functions single line and multiline
singleline-block:
const sumNum = num => num + num;
multiline-block:
const sumNum = num => {
const sum = num + num;
return sum;
};
switch (rock-paper-scissor-example)
const getComputerChoice = () => {
const rnd = Math.floor(Math.randowm()*3);
switch(rnd) {
case 0:
return ‘rock’;
case 1:
return: ‘paper’;
case 2:
return: ‘scissors’;
}
}
do … while loop
runs until something anymore. runs ONCE before check!
let i = 0;
let counter;
do {
counter = counter + i;
i++;
} while (i < 5);
4 methods to manipulate arrays
.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 to change an item in an array?
myArray[index] = ‘new’
while loops
let counter = 1;
while(counter < 4) {
console.log(counter);
counter++
}
Loop runs as long the contidion in the brackets is met
for loops
for (let counter; counter < 4; counter++) {
—code block—
}
(start value; condition to keep running; updating value)
How to find the position of an item in an array?
.indexOf() method
.indexOf(itemXY, start search)
e.g.: .indexOf(‘item’, 3) - Starts looking for ‘item’ beginning at position 4.
How to access propertys in objects?
Object.Propertyname (e.g. spaceship.color)
If propertyname contains numbers, spaces or special characters [] MUST be used.
spaceship[‘Fuel Type’]
What is a property?
It’s a key: value pair inside an object.
How to assign and delete Propertys from or to Objects?
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
What are methods?
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 to determine the datatype of a value?
type of:
type of value (as a string)
(e.g. type of 42 returns ‘number’ (string!) )
How to delete items from an array by index?
const myArray0[‘x’, ‘y’, ‘z’]
delete myArray[index]
(e.g. delete myArray[1] deletes ‘y’)
How to access a random item in an array?
myArray = [item1, item2, item3, item4]
rnd = Math.floor(Math.random()) * myArray.length
How to invoke a method?
Object methods are invoked by appending the object’s name with the dot operator followed by the method name and parentheses:
alienShip.invade();
How to access the name of an property
.name
Access the name property just like with any object. You can use the dot operator to access a function’s property: functionName.name
What are parameters?
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, … ) {}
What is a higher-order function?
A higher-order function is a function that either accepts functions as parameters, returns a function, or both!
What are iterators?
Iterators are methods called on arrays to manipulate elements and return values.
What is a callback function?
A callback function is a function passed as an argument into another function.
What is an argument?
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
What does forEach do?
.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.
What does map do?
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
What does it mean when an arrow function has no curly brackets?
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 ;
What does filter do?
.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.
What does find Index do?
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
What does reduce do?
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).
What does some?
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
What does every?
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
Arrow function sytnax
() => expression
param => expression
(param) => expression (<best practice)
() => {
statements
}
param => {
statements
}
(param1, paramN) => {
statements
}
What is the diffrence between Expression and Statement?
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 to remove Duplicates?
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]
What is the spread Operator?
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]
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()
.filter()
How to turn a string into an array?
With .split()
Turns strings into substrings using a seperator like spaces (‘ ‘) and return them as array.
What is a Ternary Operator?
A short-hand syntax to simplify if…else statements.
conditionCheck ? expressionIfTrue : expressionIfFalse
e.g.
let count = 0
count < 1 ? count++ : count–
SyntaxError
Code that cannot be interpreted by the compiler.
Scan your code for opened and closed brackets, braces, and parentheses and any invalid semicolons.
Reference Error
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 to sort arrays?
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 to copy a part of an array into a new one?
.slice()
.slice(start)
.slice(start, end)»_space; end Index is not included!
Negative idex count backwards
What method lets items delete from an array as well add?
.splice(startIndex)»_space; deletes all items from the start Index onwards.
.splice(start, deleteCount)»_space; deletes a certain number of items after start
.splice(start, deleteC, item1, item2, … , itemN)»_space; adds items to the array beginning at startIndex
How to sort an array of strings?
With .sort() and the compare function:
.sort((a, b) => {
if (a < b) return -1;
if (a > b) return 1;
return 0;
}
What are the 4 pros of using getters/setters?
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
What are the 4 cons of using getters/setters?
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,
What is the shorthand syntax of a function in object literals?
You can drop the function keyword and just use the name of the function and parameters:
methodName (parameter) {
code block
},
How to create an object based on an prototype?
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 to select an element from the DOM to interact with?
document.querySelector(CSS_SELECTOR),
and store it into a variable:
e.g.:
const button = document.querySelector(“#my-button”)
How to add or remove classes to an element on the DOM?
with classList.add(“class”) or classList.remove(“class”)
What is the general sytnax for an event listener?
const someElement = document.querySelector(“CSS_SELECTOR”)
someElement.addEventListener(“event_type”, () => {
// code to run when the event is triggered
// for example, changing innerText
, etc
})
How to modify html elements on the DOM with JS?
document.tag.innerHTML = ‘<tag>...</tag>’;
e.G.:
document.body.innerHTML = ‘<h2>This is a heading</h2>’;
How to modify text on the DOM with JS?
element.innerText = “new_text”
How to disable a button on the DOM with JS?
button.disabled = true
How to add or remove a new or existing class from an element?
How to add multiple white space to a string?
With .repeat(x)
x = number of repetitions
string${' '.repeat(x)}
How do for … in / for … of loops work? And where do they get used?
for … in wird meist für Objects and … of für Arrays genutzt.
Syntax:
for (const key in object) {
…
}
for (const item of array) {
…
}
Syntax for styling elements on the DOM (like background)
document.querySelector(‘element’).style.backgroundColor = ‘color’
Which method will add a child element as the parent element’s last child node?
.appendChild()
Which method removes a specified child from a parent?
.removeChild()
How to hide an element?
If you want to hide an element, the .hidden property allows you to hide it by setting the property as true or false
How can you access an element directly by its ID?
With the .getElementById(‘ID’) method which returns a single element.
How can you access an array of elements from the dom?
With the .getElementsByClassName() and .getElementsByTagName() methods, then call a single element by referencing its placement in the array with [0…]
How to modify an element by changing its contents or style respectively?
With the
.innerHTML
and
.style
properties.
How to add interactivity to a DOM element based on a click event?
.onclick
How to get the set value of an ID of an html page?
document.getElementByID(“id”).value;
How to find out how many rows there are in a table?
document.getElementById(“myTable”).rows.length;
How to insert a row at the end of a <table>?
const table = document.querySelector(“table”);
let row = table.insertRow(-1);
How to turn a string into a number in JS?
Number(“324”)
=> 324
How to convert a string into a number in JS?
parseInt(“string”, 10);
How to turn a node list in an array?
Array.from([node list])
How do you append content into a DOM element? (not append)
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 -->
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
1) ‘focus’
2) ‘change’
3) ‘blur’ (or ‘focusout’)
How can we read data attributes from an HTML element?
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 do you iterate through an Object in JavaScript?
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]);
});
What happens when you click on a link? How do you prevent this from happening?
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 do you toggle an .img-circle class on all <img></img> on click?
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 would you console.log() the instrument data of every band member in an unordered list? (<li class="musician" data-instrument="guitar">Joe Duplantier</li>)?
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 do we trigger playing an audio file when clicking a button?
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();
});
Can you list five different events that can be triggered by using a mouse?
- 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
Should you use event.target or event.currentTarget?
The rule of thumb is to always use event.currentTarget.
How can we add an unordered list to the DOM using only JavaScript?
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 can we add attributes to an element using JavaScript?
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 can we remove attributes from an element using JavaScript?
We can remove an attribute from an element by using Element.removeAttribute()
button.removeAttribute(“disabled”)
<button>Hello World</button>
Can you list five different events that are triggered by the Window object?
- 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
What does Event.currentTarget refer to?
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 can you pass data from HTML to JavaScript?
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 to add an HTML element to the body?
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);
Hot to get the next HTML Element with JS?
.nextElementSibling
const position = document.querySelector(“div”);»_space;> first div in the HTML
position.nextElementSibling;»_space;> returns the element immediately following the specified one in its parent’s children list
How to get the first element after selecting the parent HTML element in JS?
.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
In which part of the request should we pass the authentication token?
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!).
What is a PATCH HTTP request?
A request executed to update existing data such as your name or address when you edit your profile.
Give an example of making an API GET request in Javascript using fetch to the endpoint https://uselessfacts.jsph.pl/api/v2/facts/random.
fetch(‘https://uselessfacts.jsph.pl/api/v2/facts/random’)
.then(response => response.json())
.then((data) => {
console.log(data);
});
What command line tool can you use to make HTTP requests?
curl
What are the two parts of a GET HTTP request?
Remember, GET is called the HTTP verb.
URL
Headers (User-Agent, Referer, Cookies, etc.)
What is a POST HTTP request?
A request executed to send new data such as email and password to sign in.
What are the three parts of a POST HTTP request?
Remember, POST is called the HTTP verb.
- URL
- Headers (User-Agent, Referer, Cookies, etc.)
- Body
How do you make an Ajax POST request with fetch?
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})
})
What are the three states of a Promise?
> pending: initial state, neither fulfilled nor rejected.
fulfilled: meaning that the operation was completed successfully.
rejected: meaning that the operation failed.
What’s the intermediate step you need to perform after fetch when calling a JSON API endpoint?
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
});
Why do we need to import es-module-shims before the importmap?
To make sure our JavaScript code works with older browsers, as importmap is a new feature, not fully compatible.
What is a Response in AJAX?
It’s an interface of the fetch API that represents the response to a HTTP request.
What are Import Maps?
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>
What is a Response object?
The Response object represents the HTTP response to a request, usually as the result of a fetch() request.
How do we import and organise our JavaScript external library imports using importmaps?
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’;