Beginning JavaScript Flashcards
Where should your scripts / script tags always go?
At the bottom of your body tag, because for you to access elements on the page, they first must have loaded onto the page.
What, in folder symbol language, is “this folder”
./
What’s the downside of multiple script tags in the same file?
Every time the browser hits a script tag it will go off and download and parse that file.
What should you do instead of having multiple script tags within the same HTML document?
Either bundle your files into one JS file or employ code-splitting.
What is code splitting?
When you split JS files into multiple smaller files and then have them load on demand.
What is the keyboard shortcut within the browser to inspect an element?
Cmd + Shift + C, then you can hold it while hovering over the element you need.
What is the keyboard shortcut to open the console directly in the browser?
Option + Cmd + J
Why don’t we have to type ‘use strict’ every time?
Because it is enforced by default in JS modules, which is how almost all modern JS will be written.
What is the difference in scope between var, let, and const?
let and const are block scoped while var is function scoped.
What is Wes’s opinion of when to use var, let, or const?
By default always use const, once it needs to change switch it to let…never use var.
What are the 7 types in JavaScript?
BS BONUS - BigInt, Symbol, Boolean, Object, Null, Undefined, String
Everything in javascript is an….
Object.
What is the only non-primitive Type?
Object
Which type always gives us a guaranteed unique identifier?
Symbols.
How do you disable eslint on a particular file?
Just make a comment at the top:
/* eslint-disable */
How do you disable eslint for just one line?
Make a comment above the line
/* eslint-disable-line */
How can use a single quote within single quotes?
Escape it with a backslash /
This tells the interpreter to take what follows as text, not as javascript.
‘he/’s so cool’
What does it mean to say the plus sign is ‘loaded’?
It can both add and concatenate and if you use different types, you could be in for a world of hurt and misunderstanding, bugs and misery.
How should you store money?
Just in cents, so that you have a whole number that is easy to do math with rather than a floating point integer that is prone to errors, then just divide by 100 when you need to display it.
What is the difference between undefined and null?
Undefined is when a variable has been created but never defined, null is when something has explicitly been set to nothing. It’s the difference between Cher being born with only one name (undefined) and Teller of Penn & Teller legally setting his name to just Teller (marking his last name as null explicitly)
What is the difference between using a double and triple equal sign?
“It’s almost always wrong to use the double equal sign to test equality.
Triple equal tests that the value and the type are the same, whereas a double equal sign tests only that the value is the same, not the type.
So, ““10”” == 10 is true, but ““10”” === 10 is false because they are different types.
“
What is the tab keyword to get lorem ipsum text with the emmet extension?
lorem500 (or however many words you would like)
What built in JS function will let you move the navbar to any x, y coordinate on the page?
scrollTo - it either accepts an x and y coordinate as the params, or else accepts an option object which would have the position defined by top, left, bottom.
What argument can you pass if you need a function parameter to fall back to its default (but, for example, it’s in the middle of the argument list, so you can’t just skip it)
If you pass undefined, then the function will fall back to its default.
What does it mean to say a JS Function is a 1st class citizen?
JS functions are values in themselves - this means that they can be stored in variables and passed into other functions. This allows functions to be handled and moved around just like any other data type.
What is an anonymous function?
An anonymous function is just a function declared without a name - they are valid for callbacks or in an IIFE.
What is an IIFE?
An Immediately Invoked Function Expression.
What is a function expression?
A function expression is when you store a function as a value in a variable.
Why do some say you shouldn’t use function expressions?
Because using them gives you bad errors - this is a little outdated, but it used to be tricky to track down what caused an error within a function expression, modern debug tools, however, infer the name of the function from the variable name it’s assigned to, and uses that in the error logging.
Why is it ok to use function expressions now when it used to be a faux pas?
Because modern browsers can infer the name of the function expression from the variable it’s assigned to and use this in error logging.
What is the difference between a regular function declaration and a function expression (as far as how they work, not syntax)?
The main difference is just in how they operate during hoisting. A function expression must be initialized before being run or you’ll get an error (no hoisting) - with regular functions defined using the function keyword, they are hoisted to the top, so it’s always available everywhere.
What are the advantages of arrow functions?
- A concise syntax that’s shorter.
- They don’t have their own scope in reference to the ‘this’ keyword, which is a little more intuitive.
Why must arrow functions be stuck into a variable?
Because, they are a special type of anonymous function.
How can you use implicit returns within an arrow function?
Place the function all on one line, then make sure to take out the curly brackets (and the return keyword)
const implicit = () => ‘awesome’
implicit()
When do you not need parentheses around a parameter sent into an arrow function?
If you only are passing one parameter.
What can you do if you need to implicitly return an object from an arrow function?
Pop a set of parentheses around the object to be returned and that will contain it and keep the compiler from thinking that the object’s opening curly is the block of the function.
What is the most important factor when determining whether to use an arrow function or a normal function?
Readability - if you come back in 6 months, which type will make the most sense and be understood better in this case.
What is an IIFE? (Not the acronym - but what is an immediately invoked function expression?)
It’s when you wrap an anonymous function inside a parentheses - and parentheses always run first in JS, so the IIFE will run and return a function value then you can immediately run that value by putting another parentheses on the end.
What is this an example of?
(function() {
console.log(‘running the anon function’);
return ‘You are Cool’;
})();
An IIFE
What is the benefit of an IIFE?
Not really any anymore, but it used to be popular before there were modules and block scoped variables.
What is a method?
A function that lives inside of an object. NOT the same thing as a function, as many functions are not methods.
“What is the normal function shorthand way to write this method?
const robb = {
name: ‘Robb Schuneman’
sayHi: function() {
console.log(‘Hey Robb’)
return ““Hey Robb””;
}
}
“
const robb2 = {
name: ‘Robb Schuneman’
yellHi() {
console.log(‘HEY ROBB’)
}
}
“What is the method arrow shorthand way to rewrite this function?
const robb = {
name: ‘Robb Schuneman’
sayHi: function() {
console.log(‘Hey Robb’)
return ““Hey Robb””;
}
}
”
const robb2 = {
name: ‘Robb Schuneman’
whisperHi: () => {
console.log(‘HEY ROBB’)
}
}
What is ‘this’ equal to in normal functions?
The object that the function was called against.
What does ‘this’ refer to in an arrow function?
An arrow function inherits the parents scope of what ‘this’ refers to.
What is a callback function?
A function that will happen when something else is done - prominent examples are a click or a timer.
What type of function is this an example of?
const button = document.querySelector(‘.clickMe’); button.addEventListener(‘click’, robb.yellHi)
A callback function (listening for a button click)
What is this an example of?
button.addEventListener(‘click’, function() { console.log(‘nice’);
});
A callback function that is defining its own anonymous function (rather than calling a predefined function).
What does console.count(‘message’) do?
It keeps a running tab of how many times that console.count has been hit, so if you stick it in a function that you suspect is being called multiple times when it shouldn’t, you can easily see how many times exactly that it has been called.
What does console.table do?
If you have a group, say an object or an array of objects, console.table puts them into an easily read attribute table.
What is the advantage of passing in a variable to console.count
It’s counting the exact instance of the string that’s passed in as a param. So if you use object literal notation to do something like calling ${person.name}
then it will tell you how many times the log is called for each argument.
What does console.group do?
It nicely organizes anything that is put under it - this is a way to group together logs or variables or whatever.
How do you start and end a console.group?
console.group to start and console.groupEnd to finish.
What does console.groupCollapsed do?
it starts the group (still ending with console.groupEnd), but it is collapsed by default to provide less clutter to your console.
What is the console command (not keyboard shortcut) to return whatever element you currently have selected?
$0
In addition to $0, how do you call the second to last element, or beyond that?
$1 is next to last, $2 second to last, and so forth.
What aspect of a webpage will keep the $ command from working within the debugger console?
If the site is running JQuery, it overrides the meaning of the $ sign so that you can’t use it in debugging.
What does the $(‘element’) console selector do?
It returns the first matching element or class object selected - so $(‘p’) will return the first paragraph on the page.
What does the $$ selector select?
This will return all matching elements - so $$(‘p’) will return all paragraphs on the page.
What command will pause JS from running at the specified point in the code and give you a lot of tools you can use to figure out what’s wrong?
debugger;
What all can you see when using the ‘debugger’ command within your code?
The program will pause running and allow you to see the local variables and what they’re exactly set to, as well as the call stack.
How do you progress when using the debugger command to insert linebreaks?
Use the play button, it will forward to the next time it hits the debugger call.
What does the Step Over command do in the debugger console?
It will allow you to go step by step through your code, watching how variables change and what gets called when.
What is a second way to set a breakpoint, in addition to putting the ‘debugger’ command into your code?
If you click the sources tab, then click on a line of code, it will insert a breakpoint.
Where can you see which network calls are being fired when?
If you go to the Network tab, you can see all the files being used. Additionally, if you click on the timing tab, it will let you see where the time was spent (processing, waiting for data to return)
What does it mean to break on an attribute within the console debugger, and how do you do it?
If you right click on an element, you can tell the debugger to break on attribute modification - this will pause in the debugger whenever the attribute change happens. This will let you see which function is calling for a change, as well as to see which attributes are getting passed.
How can you put a breakpoint on a specific event (like a click, or a network call)
If you go to sources, you’ll see an event listener breakpoint - you can tell it to break on mouseClick for example, and then it will give you a breakpoint debugger when they click - or whatever listener you’ve set,
What is this an example of?
var anon = function() { alert('I am anonymous');
} anon();
An anonymous function
What question does scope answer?
Where are my functions and variables available to me?
What is a global variable?
A variable that is available anywhere within your application.
What can a global variable be accessed by?
Any other Javascript running on the page - all functions, modules, if statements, and so on.
What is the global scope in terms of the browser?
The Window object.
How are common pre-defined methods available to us throughout Javascript?
Because they are defined on the Window object.
What is the difference between var variables and let and const when talking about variables declared on the top level?
Var variables are attached to the window object and are globally scoped, but const and let do not attach to the Window object.
Global variables are awesome!
GTFO - they are a recipe for a disastrous headache.
Where are variables available if they are created within a function?
Only within that function (unless returned to whatever called it)
What is Scope Lookup?
If a variable isn’t found in the scope where it is called, it will then look for it at a higher level.
What happens if two variables of different scope are declared with the same name?
The one at the most immediate level of scope will prevail. (If a variable is declared both in a function and globally, and then called within the function - it will use the function definition of the variable.)
Why is it not a good idea to name variables at different scopes the same thing (shadow variables)?
Because you’ve limited yourself to not being able to access the variable from the umbrella scope within the more specific scope.
How can you access a variable outside of a block where it is modified?
Just declare it prior to the block as a let and then modify it - it will keep the scope of where it is declared.
What is one of the best things about block scoping on let and const?
Previously, with the function-scoped var, variables would sometimes leak out of their intended scope - for instance, if you finished a for loop with a var variable declared to count the iterations, the variable would still be there just hanging around after the loop has finished.
What is Lexical Scoping (or Static Scoping)
It is a feature in some languages, including JS, which means that Scope Lookup begins from the scope in which the function is defined, not by the scope in which the function is called.
We shouldn’t create global variables - how does modern JS make it hard to do so?
Most of modern JS is done within modules, where it is almost impossible to declare a global variable unless you explicitly call the window and attach the variable to it. But don’t do that - that’s just some hellish bugs.
What are functions scoped to?
Their parent function.
What is hoisting?
It’s a feature of JS that allows you to access functions and variables before they’ve been created within the code.
Which two things in JS are hoisted?
- Function Declarations
- Variable Declarations
What might be a preferred method instead of relying on hoisting?
Just define your functions and variables at the top of your file, or else put your functions into a separate module (utilFunctions, mathFunctions, etc) and then import them only as needed into the file where you need to run them.
What might be one use for hoisting?
“Some people prefer to first make clear in their code ““what does this file do””, and then below, have the function declarations and variables showing how the sausage is made - but that’s just a style preference.”
What’s the gotcha on hoisting variable declarations?
JS will hoist the declaration - but not a value if it’s set, so if you call a variable before the value that it’s been set to, it will return undefined.
What is a closure?
A closure is the ability to access a parent level’s scope from the child level’s scope even after the parent has been terminated.
How does a closure work?
JS is able to reach out to the parent scope from the child scope even if the parent is done running because it still maintains the variable or function in memory so that it can be accessed at a later time - it isn’t cleaned up or garbage collected.
Why would a closure be helpful?
For one, often they can be used to create private variables that are inaccesible except through a child function.
What is the Document Object Model (DOM)?
It is what the browser turns the HTML and CSS you write into.
What is the best way to think of the Window object?
Think of it as everything about the current browser window - which would include the tabs, browser bar, and other external things.
What is the best way to think of the document?
The document is responsible for everything from the opening html to the end - so not the tabs or the browser bar like the window. This entire HTML document is then accessible through the document keyword.
What is the navigator keyword?
The navigator is a higher-level thing than the window or document, which give you info about not just the browser, but the device that the code is being run on itself - it can tell you about webcams or battery level or audio access, etc.
Device-specific things live on the navigator object.
What happens if you load your Javascript before the HTML is created, like putting the script tag in the Head section as CSS is?
You won’t be able to access the HTML - you should instead put it right before the closing body tag.
If you really needed to load your JS from the header section for some reason, how could you do it?
You’d need to wrap all of your code in some sort of init function, and then launch that init function from an EventListener listening for the DOMContentLoaded event.
function init() {
const p =
document. querySelector(‘p’); console.log(p); }
document. addEventListener(‘DOMContentLoaded’, init);
What are the two main ways to select elements on the page?
.querySelector and querySelectorAll
Can .querySelector and .querySelectorAll only be called against the document object?
No, they can be called against any element. Doing so will limit the scope of the selector to only children of that element.
Give an example of how to select the first paragraph on a page.
const p = document.querySelector(‘p’);
What does querySelectorAll return?
A NodeList of all matching elements.
What does querySelector return?
The first matching element.
What are NodeLists?
They are lists of things, like array, but they don’t have all the functions built in that arrays do (map, filter, reduce, etc.)
Give an example of a parent -> child selector within JS?
const imgs = document.querySelectorAll(‘.item img’);
What are additional ways to select elements on a page, beyond querySelector and querySelectorAll?
Though not really used anymore, there are still functions like getElementById, getElementByClassName and the like. Mostly you need to know about them in case you come across them in code, but you should be able to do all you need with querySelector and querySelectorAll.
What does console.dir do?
It will give you the object properties for an element, rather than just the display of the element - so you can see al the methods available, such as the parentNode, textContent and the like.
How do you set a property of an HTML element once you’ve gotten it with a querySelector?
“Simply by setting it equal to something new via dot notation.
heading.textContent = ““Robb is cool””
“
What is the property for the text within an element?
.textContent
What are the differences between .innerText and .textContent?
.textContent is newer and gets the contant of all elements, including script and style properties within the element - .innerText only shows human-readable element.
However, innerText is style-aware, and won’t return elements hidden by CSS, whereas textContent just returns everything in the element, hidden or not.
What does the element.innerHTML property give you?
The full HTML within the element.
What does the element.outerHTML property give you?
It returns the full HTML within the element - and also the element it is contained within, as well as keeping any white space.
How should you tack some content onto preexisting content?
Instead of seeting the content equal to itself and whatever additions, use the insertAdjacentText property, like so:
pizzaList.insertAdjacentText(‘afterend’, ‘pizza’)
The first argument says where to add the text, the second says what to add.
Why should you use element.insertAdjacentText instead of setting the textContent equal to what’s already there plus whatever is new?
Replacing the textContent is pretty slow in cases where there is lots of text and html getting put back in - and it causes the browser to re-render the entire element instead of just inserting the text.
What is the difference between an HTML Node and an Element?
Everything is a Node, whereas an Element describes only things wrapped in some sort of HTML tag.
What’s the best website to find a list of all the element properties and methods?
developer.mozilla.org/en-US/docs/Web/API
How do you add a class to an element using JS?
element.classList.add(‘newClass’);
How do you remove a class from an element?
element.classList.remove(‘oldClass’);
What does element.classList.toggle(‘aClass’) do ?
It will add the class to the element if it isn’t present, or remove it if it is present.
Where should you generally put transitions? On the element? Or on a class?
Probably on the element being transitioned, not the class, because otherwise it will only transition one way - when the class is added, not when it’s removed.
What does element.classList.contains(‘someClass’) do?
It will return true or false dependent on whether the classList contains that class - which would be useful if you’re basing some conditional on that.
What two measurements can you pass in to CSS transform: rotate()?
You can either measure the rotation in degrees (360deg) or # of turns (1turn).
What are some common transform properties?
transform: rotate(360deg) or
transform: scale(1.5) or
What arguments get passed to transform: scale() ?
You can either pass one argument to scale it both ways, or you can separately pass the X and Y you’d like to scale like:
transform: scale(2, 0.5);
It’s based off of relation to 1 - so 2 would be twice the size, 0.5 would be half the size.
Give me an example of a common, basic argument set for the boxShadow CSS property?
boxShadow: 0 0 10px black;
What border radius will give you a circle?
border-radius: 50%;
What is probably the most common way to interact between CSS and JS?
Just adding and removing classes at different points in time, which lets us step in with our CSS and add or remove all the different transitions. This is especially common with modals or navs that need to slide in or whatever.
What is the className element attribute?
It is a class attribute which gives us a list of classes - but it’s older than classList, and classList additionally gives us these very useful functions (add, remove, toggle, contains)
What is an HTML attribute?
Anything provided to an element as additional info - classes, source, alt, etc.
How do you set an HTML attribute?
The same as other things - once you’ve gotten your element, just set the dot property equal to something new:
element.alt = ‘Cute Pup’
“Do you need to title an alt attribute something like ““photo of (whatever)””?”
“NAH, because screen readers will already let the people using them know that this is an image. Just name it ““cute pup”” not ““A photo of a cute pup”””
True or False - dot attributes like element.width or element.title work as both setters and getters?
True, you just do element.width = 300 or myWidth = element.width
All dot attributes are setters and getters?
Not all - some, like .naturalWidth, can’t be changed, which makes sense if you think about it.
What can you do if you have an element that you’re waiting to load before you can do something with it in JS?
You can put it in an event listener with the ‘load’ trigger - either from the window attribute, or for the element in question.
window. addEventLIstener(‘load’, function() {
console. log(pic.naturalWidth);
});
This waits for it to be loaded first, then executes the function.
True of False - eventListeners can only be fired on the Window element.
Nah. You can use them to watch for actions on specific elements as well.
Why do you have to wait for things to load even if the script tag is at the bottom of the body tag?
Because, that is true it will wait for all HTML to load - but certain things are asynchronous, like API calls or things loaded from a server, and it will not wait for those.
Why do we have getAttribute, setAttribute and hasAttribute methods when we can just use dot notation on an attribute?
They’re older for one, but also they work for getting non-standard attributes. But don’t set custom attributes, that’s pain.
Should you set non-standard attributes on HTML elements?
No. Don’t go willy-nilly making up your own attributes, because if the HTML spec introduces it in the future, your legacy code will clash with the standard and make for huge bugs. Some popular libraries did this, and that’s why JS has to have stupid names for certain methods (.contains instead of .includes)
How should you set your own custom attributes?
Use data attributes - which is to say, use data-whatever like so:
This lets you attach data that isn’t a standard attribute.
How do you access data attributes?
You call element.dataset, which returns an object with each of the properties defined on it - so you can do element.dataset.customWhatever
What is it an example of if you have an image, and set a custom attribute of data-largeUrl that is the source to a larger picture you can use in the link?
That’s data attributes, homey.
What is a good website to figure out keycodes?
keycode.info
What happens if you call .play() on an audio element already playing?
Nothing. It won’t play again until it has run its full course.
How do you rewind an audio element to the beginning?
audio.currentTime = 0
Why shouldn’t you have a timeout in your JS to run when a transition ends, in addition to a transition manually set to the same amount of time?
Because that creates multiple places you have to remember to update if you change the time. Also someone on your team might unknowingly change one spot and not the other.
What is a better solution than setting two corresponding timers (one as a transition, one as a timer before running code)?
Use the transitionEnd event that fires when the element is done transitioning, rather than trying to time it just right.
You can attach a listener to a JS array? T/F?
false. You can’t do that, you instead need to loop over each of them and attach an eventListener to each.
keys. forEach(key => key.addEventListener(‘transitionend’, removeTransition));
What is this (almost) always equal to?
The thing that it got called against.
What is the main way to create HTML elements in Javascript?
document.createElement(), and then pass it a tag name ( (‘p’) or (‘div’)
What do square brackets around a param on MDN mean?
That it’s an optional param.
When you use document.createElement() it automatically puts that element on the page. T/F?
False - it just creates it within memory, then you still will need to tell it where to go.
What is the shortcut to give a class or title to an element via document.createElement?
TRICK NO TREAT - there is no shortcut for that, you just have to do it after creation by dot notation on the variable that you stored your newly created element within.
How do we add some created HTML to the DOM?
We grab the element we want to add it after and use .appendChild() or insertAdjacentElement()
How do you access the body of the document?
Easy - with document.body - they give us a nice attribute accessible via dot notation directly on the document.
Why shouldn’t you update the created element and re-append it to the document.body a bunch of times?
Every time you use appendChild() you’re modifying the DOM, which causes the browser to re-paint what is on the actual page. So, you should use appendChild only after setting all the content and classes and whatever other attributes you need to.
And if you have multiple elements going in the same spot, append them to each other before appending them to the DOM.
How can you add a JS created element to another element?
element.append() - but it doesn’t work on IE, or element.appendChild()
What built-in function can you use to append somewhere other than as a child of an existing element?
You can use .insertAdjacentElement() - which works the same as insertAdjacentText() - you pass it one of several options on where you want the element.
What built-in function will copy the contents of a node to a new variable?
newElement = elementToBeCopied.cloneNode()
When you use .cloneNode() but don’t pass any arguments, what should you expect?
It will just be the top level node without any of its children - not even the textContent of that node. To get those along with it, you pass it an argument of ‘true’ which will tell it to do a deep clone and copy the child elements as well.
What’s a major gotcha when using backtick strings to dump HTML into the DOM?
If they’re coming from user input, you are opening yourself to XSS - cross site scripting, unless you sanitize it.
What do we use to set or change the actual HTML of the item we have selected?
We would use .innerHTML (as opposed to just .textContent)
Other than security risks - what is another downside to setting innerHTML to backtick HTML?
What you get are not elements - they’re just strings so you can’t call functions against them or add event listeners or set attributes unless you first dump it into the DOM and then pull it back out.
What is a range?
Just a collection of elements or HTML that we can then work with.
How can you turn a back-tick string into actual HTML so that you can use your element built-in functions?
call .range.createContextualFragment()
document.createRange().createContextualFragment(myHTMLString);
What is XSS?
Cross-site Scripting - when a third party runs their own JS on your site, which should never happen.
Explain the difference between a node and an element in terms of this element:
I am SO Cool
If you grabbed this p, and then called myP.children (which returns the child elements) - youwould only get the em tag - if you called myP.childNodes you would get the text node before the em, the em, and the text node afterward.
List the properties we have available for traversing and working with elements?
For elements:
.children
.firstElementChild (first element under)
.lastElementChild (last element under)
.previousElementSibling (the element before this)
.nextElementSibling (element after)
.parentElement (up one level)
What’s a better way to move between nodes in JS then traversing up, up, over, down or something?
Just use querySelector to grab the one you want, or if you don’t know exactly, use .closest()
what does .closest(element or class) do?
It grabs the closest element to whatever it is called against.
Why is it a bad idea to traverse the dom going up up over down down and so on?
Because you can’t assume the document structure will stay the same - if one div gets inserted between, or something else changes the structure of your code slightly, suddenly your day is ruined.
What are the properties available for dealing with nodes?
.firstChild
.lastChild
.previousSibling
.nextSibling
.parentNode
.childNodes
What is maybe the one most important take away for the node and element properties?
The exact same properties are available for both and are confusingly named - so you might get them mixed up and then wonder why your results aren’t what you thought. Just make sure you’re calling the ones you want.
What is the built in method to remove an element or node that is available on every single method or node?
.remove()
What is the gotcha with using .remove() to remove elements/nodes?
If you remove it - it’s taken out of the DOM, but is still present in memory - so you still have access to it, and you can do some stuff to it and then put it back in the same spot or somewhere else.
If you want to insert an HTML string into the DOM, how can you accomplish this?
You’d have to use insertAdjacentHTML instead of insertadjacentElement, as this accepts any valid HTML. Or else do the createRange().createContextualFragment(divToInsert) trick.
You can’t just use insertAdjacentElement because an HTML string is not an element