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’;
Can you describe a POST HTTP request?
Remember, POST is called the HTTP verb. It needs:
URL
Headers (User-Agent, Referer, Cookies, etc.)
Body
What does a Promise object allow us to do?
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.
In Vue, how do you bind click event to a button?
We can use v-on or @.
<button>
<button @click=”doSomething”></button>
In Vue, how do you iterate through a list in HTML?
We can use v-for:
<div>
...
</div>
In Vue, what syntax do you use to bind data in HTML?
The double mustache syntax:
{{}}
How do you create a Vue instance?
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>
Stimulus JS
What is this.element?
this.element is the element the Stimulus controller is bound to.
What is a value in Stimulus JS and how is it used?
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}!
;
}
}
How do you define a target in a Stimulus controller?
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”]
// […]
}
What’s the scope of a stimulus controller?
When Stimulus connects a controller to an element, that element and all of its children make up the controller’s scope.
How do I create a Stimulus JS controller?
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
}
What is the purpose of the disconnect() method in a Stimulus controller?
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.
How can you pass data from HTML to a Stimulus controller if we don’t want to use values?
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);
}
}
How do I register a Stimulus JS controller with the name disable_button_controller.js?
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)
How do you connect a Stimulus controller to an HTML element?
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>
How can I add an event listener on click to display something if the button looks like this <button>Show</button>
<button>Show</button>
What’s the equivalent of .addEventListener in Stimulus?
data-action
1
data-action
Adding a data-action=”event->controller-name#methodName” to the html tag.
What’s the equivalent of document.querySelector in Stimulus?
Adding a data-controller-name-target=”input” to the html tag.
How can I select the target from the Stimulus controller if the html looks like this <button>Show</button>
In the toggle_display_controller.js you can add this.buttonTarget inside a function to get the button element
What are the three main concepts of Stimulus?
- 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
How to remove white space from strings?
.trim()
.trimStart() or .trimEnd() for only one side
How to downcase strings?
.toLowerCase()
How to insert a row at the end of a table?
const table = document.querySelector(‘.table’);
let row = table.insertRow(-1);
How to insert a cell at the start of a row?
cell1 = row.insertCell(0);
How to at content to a cell?
let cell1 = row.insertCell(0);
cell1.innerText = “content”;
How to reverse a string in JS?
string.split(‘’).reverse().join(‘’);
How can you check if a string ends with another string?
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.
How can you run code after the DOM is fully loaded?
document.addEventListener(“DOMContentLoaded”, …)
How do you define and use a CSS custom property (variable)?
Define a custom property using
–propertyName: value;
and use it with
var(–propertyName).
How do you delay the execution of a function in JavaScript?
Use setTimeout(function, delay) to execute a function after a specified delay in milliseconds.
How do you generate a random integer within a specific range in JavaScript?
Use Math.floor(Math.random() * range) to generate a random integer from 0 to range - 1
How do you generate a random uppercase letter in JavaScript?
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).
How do you convert an ASCII value to its corresponding character in JavaScript?
Use String.fromCharCode(asciiValue) to convert an ASCII value to its character representation.
What structure do APIs commonly use to return a list of items?
An array of objects.
How can you iterate over an array of Objects in JavaScript?
Using a for…of loop.
What method do you use to parse a JSON response in JavaScript?
response.json()
How to get the square number in JS?
Math.sqrt(n)
//Math.sqrt(9); // is 3
How can you refer to the first capture group that was matched by a regular expression?
‘$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)
How can you access the last element of an array in JS?
With .at(-1).
It might not work in old browsers. To be safe this is the other way:
array[array.length - 1]
How would you create a new IntersectionObserver instance to observe the page?
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);
How can you alter e.g. when the IntersectionObserver starts acting?
With defining options and use them in the new IntersectionObserver instance:
const options = { someOptions };
How can you create an offset for the IntersectionObserver?
const options = {
rootMargin: “-200px 0px 0px 0px”
};
I will offset the top by 200px when scrolling down
How do you start youre IntersectionObserver?
elementObserver.observe(element);
How to get the time in JS?
const now = new Date();
let hours = now.getHours();
let minutes = now.getMinutes();
let seconds = now.getSeconds();
How to convert a number into a string in JS?
number.toString();
What does that do?
updateTime();
setInterval(updateTime, 1000);
It initially calls a function named updateTime()
Than it sets an intervall of 1000ms after it repeatedly calls the updateTime function.
How can you add a 0 to a single digit at the beginning in JS?
.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’.
How can you retrieve the ASCII Code for a character in JS?
.charCodeAt(index);
let char = ‘-‘;
let asciiValue = char.charCodeAt(0);
console.log(asciiValue); // Output: 45
How do you set up an image for lazy loading in HTML?
Replace the src attribute with data-src to prevent the image from loading initially.
What JavaScript method is used to select all elements with a specific attribute?
document.querySelectorAll(‘[data-src]’)
What is the purpose of the preloadImage function in lazy loading?
AIt sets the src attribute of the image from the data-src attribute when the image is about to enter the viewport.
How to split multiline strings in javascript in an array of lines?
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.
How to matche any uppercase letter in JS?
With the regular expression /[A-Z]/
How do you prevent split(/[A-Z]/) from removing the matched character in JavaScript?
Use a positive lookahead assertion, like “.split(/(?=[A-Z])/)”.
How do you uppercase the first character of a string in JavaScript?
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.
How do you ensure string start with an uppercase letter (and leave every other letter) in JavaScript?
Use charAt(0).toUpperCase() for the first letter and slice(1).toLowerCase() for the rest.
function capitalizeFirstLetter(str) { return str.charAt(0).toUpperCase() + str.slice(1); }
How do you check if a number is prime in JavaScript?
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).
What is the efficient loop for checking primes in JavaScript?
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.
Why is incrementing by 6 efficient in prime checking?
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.
What event is fired when a form is submitted?
The ‘onsubmit’ event.
What attribute can be used to turn off HTML validation in a form?
The ‘novalidate’ attribute.
When is setCustomValidity typically used?
Within event listeners to dynamically control form validation based on specific conditions.
How do you clear a custom error message set with setCustomValidity?
Call setCustomValidity(“”) on the form field.
One liner to filter out even numbers:
const scores = [85, 92, 73, 98, 80];
const evenScores = scores.filter(num => num % 2 === 0);
One liner to get squares of numbers:
const sideLengths = [5, 3, 7];
const areas = sideLengths.map(num => num * num);
One liner to reverse a string:
const str = “Hello, world!”;
const reversedStr = str.split(‘’).reverse().join(‘’);
One liner to figure out whether a specific attribute (such as “email”) exists in a user object.
// 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
How about creating an operation to greet users but giving a backup value in case no name is provided?
const greet = (name = “Guest”) => Hello, ${name}!
;
console.log(greet());»_space; Hello, Guest!
console.log(greet(“Bob”));»_space; Hello, Bob!
One liner to remove empty values or null elements from arrays.
const numbers = [1, 0, null, 3];
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
What are classes in JavaScript?
Classes are templates for objects.
What happens when a new instance of a class is created in JavaScript?
JavaScript calls a constructor method.
Which keyword is used to create a subclass in JavaScript?
The extends keyword.
What is a constructor method in JavaScript?
A constructor method is a special method for creating and initializing an object created within a class.
Give an example of creating a class with a constructor in JavaScript.
class Animal { constructor(name) { this.name = name; } }
How do you instantiate a new object from a class in JavaScript?
Using the new keyword followed by the class name and any required arguments for the constructor.
const dog = new Animal('Buddy');
What is method overriding in JavaScript?
Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass.
Provide an example of getter and setter methods in a JavaScript class.
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
How do you ensure a method in a subclass correctly overrides and utilizes a parent class method in JavaScript?
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).
What is the correct way to call a parent class’s method from a subclass in JavaScript?
super.methodName(arguments). This calls the parent class’s method with the provided arguments.
What is the purpose of using getters in JavaScript classes?
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.
How do you call a static method in JavaScript?
Static methods are called on the class itself, not on instances of the class. Use ClassName.staticMethodName().
How do you export named resources in ES6?
export const resourceToExport = value;
or directly in front of the variable declaration:
export const resourceToExport = value;
How do you access a getter in JavaScript?
Getters are accessed as properties, not called as functions. Example: objectName.propertyName.
How do you import named resources in ES6?
import { exportedResourceA, exportedResourceB } from '/path/to/module.js';
How can you rename an imported resource to avoid naming collisions?
import { exportedResource as newResourceName } from '/path/to/module';
How do you export a default value in a module?
const resources = { valueA, valueB }; export default resources;
or directly:
export default value;
How do you import a default export?
import importedResources from '/path/to/module.js';
Note: The default value may be given any name by the importer.
How do you export multiple functions using named exports in ES6?
function functionName() { /* logic */ } export { functionName };
or:
export function functionName() { /* logic */ }
How would you update an HTML file to properly load a JavaScript module?
Add the type=”module” attribute to the script tag:
<script type="module" src="./module.js"> </script>
How do you use the as keyword to rename imported resources?
import { exportedResource as newResourceName } from '/path/to/module';
This helps avoid naming collisions and clarify the purpose of the imported resource.
Provide an example of exporting multiple named resources and importing them in another file.
```// module.js
export const resourceA = valueA;
export const resourceB = valueB;
// main.js
import { resourceA, resourceB } from ‘./module.js’;
~~~
How can you combine multiple functions into a single default export?
const functionA = () => { /* logic */ }; const functionB = () => { /* logic */ }; const resources = { functionA, functionB }; export default resources;
How do you import and destructure a default export object in ES6?
import resources from '/path/to/module.js'; const { functionA, functionB } = resources;
What does array destructuring in JavaScript allow you to do?
Array destructuring allows you to unpack values from arrays into separate variables in a concise and readable manner.
How does array destructuring work with array literals?
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.
What is an example of using array destructuring with .split()?
You can split a string and destructure the result: let [firstName, lastName] = “John Doe”.split(‘ ‘); assigns “John” to firstName and “Doe” to lastName.
How do you create an error using the Error() function?
A: You can create an error by using the Error() function, e.g., let error = new Error(‘This is an error message’);.
How do you throw an error object using the throw keyword?
You can throw an error object using the throw keyword, e.g., throw new Error(‘This is an error message’);
How do you use the try…catch statement to handle thrown errors?
try { // code that may throw an error } catch (error) { // code to handle the error }
Explain the expression Math.min(Math.max(value, lowerBound), upperBound).
This expression clamps value within the range [lowerBound, upperBound]. It ensures value is at least lowerBound and at most upperBound.
What does Math.max(value, lowerBound) do?
It returns the larger of value and lowerBound, ensuring value is not less than lowerBound.
Provide an example of clamping a value between 0 and 100.
let lowerBound = 0; let upperBound = 100; let value = 150; let clampedValue = Math.min(Math.max(value, lowerBound), upperBound); console.log(clampedValue); // Output: 100
What is a simpler alternative to readline for synchronous user input?
The prompt-sync Node module.
How do you require and call prompt-sync?
const name = prompt(‘What is your name?’);
console.log(Hey there ${name}
);
How do you allow users to exit with Ctrl + C using prompt-sync?
const prompt = require('prompt-sync')({sigint: true});
How do you convert user input to a number in prompt-sync?
const num = prompt('Enter a number: '); console.log(Number(num) + 4);
What is the syntax for Array.from()?
Array.from(arrayLike [, mapFn [, thisArg]])
Create an array with ‘height’ rows, each row being a new array of ‘width’ filled with fieldCharacter
Array.from({ length: height }, () => new Array(width).fill(fieldCharacter))
You have an 2D Array. How can you get an array ‘positions’ with all coordinates in that 2D Array?
const positions = []; for (let row = 0; row < this.height; row++) { for (let col = 0; col < this.width; col++){ positions.push([row, col]); } }
How can you swap two elements in an array using JavaScript destructuring assignment?
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.
How to state an array with 9 similiar items like null?
Array(9).fill(null);
How to create a shallow copy of an array?
arrayCopy = array.slice();
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
window.location.search
How can you easily create, parse, manipulate, and iterate over query string parameters in a URL.
With the JavaScript interface URLSearchParams
How do you create a URLSearchParams object from the current URL?
Use
new URLSearchParams(window.location.search)
to create a URLSearchParams object from the query string of the current URL.
How do you retrieve a specific query parameter using “URLSearchParams”?
Use query.get(‘name’) to retrieve the value of the query parameter name. If the URL is ?name=John, it returns ‘John’.
How can you check if a query parameter exists using URLSearchParams?
Use
query.has('name')to check if the query parameter name exists in the URL.
How do you append a new query parameter using URLSearchParams?
Use
query.append('key', 'value')to add a new key-value pair to the query string. If key already exists, it adds another instance.
How do you remove a query parameter using URLSearchParams?
Use
query.delete('name')to remove the “name” parameter and its value from the query string.
What does
query.toString()do in URLSearchParams?
Converts the query parameters back into a string format, excluding the leading “?”.
How do you iterate over all key-value pairs in URLSearchParams?
Use
for (let [key, value] of query.entries())
to loop through all key-value pairs in the query string.
How can you merge two arrays?
With the spread operator …
mergedArray = [...array1, ...array2]
What is the outcome of the following code?
assert.ok(false);
An error is thrown.
assert.ok() has two outcomes: throw an error or return nothing.
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!'; }
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.
Which is the correct syntax for a Mocha it() function?
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) });
How can you calculate the factorial of a number variable like num?
function factorial(n) { if (n === 0) { return 1; } let result = 1; // Store result separately for (let i = n; i > 1; i--) { result *= i; } return result; }
What is the diffrence between setTimeOut() and setIntervall.
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.
How do you create a JavaScript Promise?
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'); } });
What is the purpose of the executor function in a Promise?
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.
How do you handle a resolved Promise?
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" });
How do you handle a rejected Promise?
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" });
What is Promise chaining?
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));
What is Promise.all() used for?
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));
How do Promises handle errors?
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().
When do you use .finally() in Promises?
.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'));
How do you turn a .json file in a JS Object, and how a JS Object into a .json file?
With JSON.parse and JSON.stringify:
const jsObject = JSON.parse(jsonData);
const jsonData = JSON.stringify(jsObject);
How do you create a simple GSAP timeline animation that moves an element horizontally?
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.
What properties should you define for a ScrollTrigger object in GSAP?
- 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.
How does changing the start and end properties of ScrollTrigger affect the animation timing?
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.
How can you control an animation’s duration and behavior with ScrollTrigger using the scrub property?
- 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.
How do toggle actions in ScrollTrigger control animations when entering and leaving the viewport?
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.
How can you visualize ScrollTrigger’s start and end points during development?
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.
What is the effect of using negative values for the start and end properties in ScrollTrigger?
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.
How can you use HTML data attributes in JS to toggle elements?
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.
What is the purpose of Object.values() in JavaScript, and what does it return?
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"]
What does Object.entries() return when called on an object?
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"]]
How can you map over the values of an object passed as a prop in React to render them?
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> ); }
Why should you use a key prop in React when rendering a list?
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> ))}
What is the purpose of Object.keys() in JavaScript, and what does it return?
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"]
What is the difference between Object.values(), Object.entries(), and Object.keys()?
- Object.values(): Returns an array of values.
- Object.entries(): Returns an array of key-value pairs.
- Object.keys(): Returns an array of keys.
How do you generate a drob cap in css?
p::first-letter {
-webkit-initial-letter: 2;
initial-letter: 2;
padding: 0.25rem;
}
How can you convert a Set into an Array?
Array.from(set)
converts a Set into an array, preserving only unique values from the Set.
What is the role of JSON.stringify() in JavaScript?
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.
What does JSON.parse() do in JavaScript?
JSON.parse() converts a JSON string back into a JavaScript object or array. It reverses the effect of JSON.stringify().
Why is JSON.parse() used in conjunction with Array.from() when working with Set?
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.
How can you ensure uniqueness when dealing with complex objects in JavaScript?
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.
How can you make a button scroll to the top of the page?
scrollToTopButton.addEventListener("click", () => { window.scrollTo({ top: 0, behavior: "smooth", });
How can you show a Scroll To Top Botton, that is initialy hidden?
window.addEventListener("scroll", () => { const isScrolled = window.scrollY > 200; // Show Button after 200px of scrolling scrollToTopButton.classList.toggle("show", isScrolled); });
isScrolled becomes either true or false based on how much the site is scrolled. The class “show” contains css to show the button that is initially hidden.
How can you set the focus on the page to an specific element?
const navbar = document.querySelector(“nav”);
navbar.focus();
How can you determine the height or width of the Browserwindow with javascript?
height:
window.innerHeight
width:
~~~
window.innerWitdth
~~~
How can you determine the widt of an element with javascript on the DOM?
getBoundingClientRect().width;
There is also .heigth, .x, .y (Distance to top left in pixel), .top (Distance Top Element to Top window), .bottom (Bottom Element to Top window), .left, .right
What is the primary function of a forEach loop in JavaScript?
Executes a callback function for each element in a list and does not return any values.
What does the .map() function do in JavaScript?
Calls a function on each element in a list and returns a transformed array with the values returned by that function.
True or False: A forEach loop returns a new array.
False
True or False: The .map() function can transform the elements of an array.
True
Fill in the blank: The forEach loop does not return a _______.
new array
Fill in the blank: The .map() function returns a _______ with the transformed values.
transformed array
What is a JavaScript Promise?
A way to write more asynchronous code, defined with resolve and reject functions.
What happens if a Promise is executed successfully?
The resolve function is returned to the main program.
What happens if a Promise fails?
The reject function is returned.
What problem does using Promises solve?
It helps avoid ‘callback hell.’
What is ‘callback hell’?
Defining callback functions within callback functions, leading to unreadable code.
What method do Promises support for clearer code execution order?
.then() statement.
Fill in the blank: A Promise is defined with two functions: a _______ and a _______.
[resolve], [reject]
True or False: Promises can lead to more readable code than callbacks.
True
How can you check if an array is empty?
Use an ‘if’ statement with the condition: array_name === undefined || array_name.length === 0
This checks if the array is defined and if its length is 0.
What is the first condition in the ‘if’ statement for checking an empty array?
array_name === undefined
This ensures that the array has been defined before checking its length.
What is the second condition in the ‘if’ statement for checking an empty array?
array_name.length === 0
This checks if the length of the array is equal to 0.
What happens if the ‘if’ statement conditions are true?
The code within the ‘if’ statement will execute
This typically contains logic to handle the case when the array is empty.
What is a Map in JavaScript?
A Map is a collection of key-value pairs where both the key and the value can be any data type (primitive or object). It is part of ES6 and offers methods for handling key-value data more efficiently than plain objects.
How do you create a new Map in JavaScript?
You can create a new Map by using the Map constructor:
let map = new Map();
How can you initialize a Map with key-value pairs?
A Map can be initialized with an array of key-value pairs:
let map = new Map([ ['a', 1], ['b', 2], ['c', 3] ]);
Question: What does the set method do in a Map?
The set method adds a key-value pair to the map. If the key already exists, it updates the value.
let map = new Map(); map.set('a', 1); map.set('b', 2); map.set('a', 10); // Updates 'a' to 10 console.log(map.get('a')); // 10
How can you retrieve a value from a Map using a key?
Use the get method to retrieve the value associated with a key.
let map = new Map([['a', 1], ['b', 2]]); console.log(map.get('a')); // 1 console.log(map.get('b')); // 2
How can you check if a key exists in a Map?
Use the has method to check if a key exists in the map.
let map = new Map([['a', 1], ['b', 2]]); console.log(map.has('a')); // true console.log(map.has('z')); // false
Question: How do you delete a key-value pair from a Map?
The delete method removes a key and its associated value.
let map = new Map([['a', 1], ['b', 2]]); map.delete('b'); console.log(map.has('b')); // false
How do you clear all entries from a Map?
The clear method removes all key-value pairs from the map.
let map = new Map([['a', 1], ['b', 2]]); map.clear(); console.log(map.size); // 0
What does the size property of a Map return?
The size property returns the number of key-value pairs in the map.
let map = new Map([['a', 1], ['b', 2]]); console.log(map.size); // 2
How can you iterate through the keys of a Map?
Use the keys method to get an iterator over the keys of the map.
let map = new Map([['a', 1], ['b', 2]]); let keys = map.keys(); for (let key of keys) { console.log(key); // 'a', 'b' }
How do you iterate through the values of a Map?
Use the values method to get an iterator over the values of the map.
let map = new Map([['a', 1], ['b', 2]]); let values = map.values(); for (let value of values) { console.log(value); // 1, 2 }
How can you iterate through both keys and values of a Map?
Use the entries method to get an iterator of key-value pairs.
let map = new Map([['a', 1], ['b', 2]]); let entries = map.entries(); for (let [key, value] of entries) { console.log(`${key}: ${value}`); // 'a: 1', 'b: 2' }
What is the difference between a Map and a plain JavaScript object?
A Map allows any type of value as keys (including objects), preserves insertion order, and provides efficient methods for adding, removing, and checking entries. A plain JavaScript object only allows strings as keys and may not preserve order for non-string keys.
How can you create a Map from an array of objects with keys and values?
You can create a Map by passing an array of arrays, where each inner array contains a key-value pair.
let arr = [['a', 1], ['b', 2], ['c', 3]]; let map = new Map(arr); console.log(map.get('b')); // 2
What does the showModal() method of HTMLDialogElement do?
It displays the **<dialog>** element as a modal dialog, blocking interaction with the rest of the page.</dialog>
What happens to the rest of the page when showModal() is called?
The rest of the page becomes inactive, and the dialog appears in the top layer along with a ::backdrop pseudo-element.
How can you check if a dialog is open?
By checking the open property of the **<dialog>** element.</dialog>
if (dialog.open) { console.log("Dialog is open"); } else { console.log("Dialog is closed"); }
How do you open a **<dialog>** element using JavaScript?</dialog>
dialog.showModal();
How do you close a **<dialog>** element using JavaScript?</dialog>
dialog.close();
Why is Axios preferred over fetch?
Axios
- automatically parses JSON
- has better error handling
- supports timeouts
- can cancel requests.