Vanilla JavaScript Flashcards
How do you throw an error?
throw new Error(‘this is the error’)
How do you add JavaScript to html?
<head>
</head>
How do you reference a DOM element by its ID?
document.getElementById(‘my-id’);
How do you reference a DOM element by a CSS selector (both first element or all elements)?
document.queySelector(‘div’);
const divItems = document.querySelectorAll(‘div’);
// can then iterate through divItems using forEach or reference elements like divItems[1]
How do you reference a DOM element by its CSS class?
document.getElementsByClassName(‘my-class’);
How do you change the styling of an element, like color?
const item = getElementById(‘my-id’);
item.style.color = ‘blue’
OR
item.setAttribute(‘color’, ‘blue’);
// generally shouldn’t do this; should set with CSS instead
How do you change the text of an element?
element.textContent = ‘My new content’;
OR
element.setAttribute(‘textContent’, ‘My new content’);
How do you add and remove CSS classes to an element?
element.classList.add(‘my-class’, ‘my-second-class’);
element.classList.remove(‘my-class’);
How do you create a new DOM node, like paragraph?
const p = document.createElement(‘p’);
p.textContent = ‘Hello’;
document.body.append(p); // can also .prepend(p)
How do you create multiple new DOM nodes at once, like list items?
const parent = document.querySelector(‘ol’);
const fragment = document.createDocumentFragment();
for (let i = 0; i < 3; i++) {
const li = document.createElement(‘li’);
li.textContent = List item ${i}
;
fragment.append(li);
}
parent.append(fragment);
How do you delete an element from the DOM?
element.remove();
How do you get the list items within a ul with an id of ‘my-id’?
const ul = document.getElementById(‘my-id’);
const listItems = ul.querySelectorAll(‘li’);
How would you log to the console if a button was clicked?
const button = document.querySelector(‘button’);
const onClick = () => console.log(‘you clicked the button’);
button.addEventListener(‘click’, onClick);
// can remove event listener with button.removeEventListener(‘click’, onClick);
// double click is ‘dblclick’
How would you create an event listener for any key that is clicked?
window.addEventListener(‘keydown’, (event) => { … })
How do you create a promise?
const promise = new Promise((resolve, reject) => {
resolve(someValue);
// reject(new Error(‘something went wrong’))
})
promise.then(value => console.log(value)).catch(error => console.log(error))
// a promise is in a “pending” state until it is either resolved (“fulfilled”) or rejected
// you can also chain thens, eg
promise
.then(value => value * 2)
.then(value => value + 1)
.then(value => console.log(value))
.catch(error => console.log(error))
.finally(() => console.log(‘done’))
// finally will always run; it doesn’t take a parameter
How can you wait for all promises to be fulfilled before returning?
const [value1, value2] = Promise.all([promise1, promise2])
// can also use Promise.any to return first fulfilled promise or Promise.race to return first fulfilled or rejected promise
How do you call an endpoint?
const response = await fetch(url, {
method: “POST”,
headers: {
“Content-Type”: “application/json”,
},
body: JSON.stringify({ key: “value” }),
});
const data = await response.json();
// wrap the above in a try catch
OR
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
What is closure?
A function along with a saved reference to the lexical environment in which it was defined; this is set when the function is declared, not when it’s called; the lexical environment is an internal data structure used for keeping track of variable and function names and their values
When an identifier (variable or function) is not defined locally, JS will look to the parent environment, then to the parent’s parent environment and so on up to the global environment
What’s the difference between defining a variable using let or var?
var is globally scoped; let is locally scoped
What is the keyword this?
A reference to the context in which the current code is running
At the top level of the file (or a standard function without strict mode), ‘this’ refers to the global object which is the ‘window’
In an object method, ‘this’ refers to the object
Arrow functions do not create their own ‘this’ context, instead they retain the value of the enclosing context