javascript Flashcards
What is a variable?
A keyword that’s used to store data.
Why are variables useful?
They can be ‘referenced’/re-used Any time and be used over and over again, thus saving time. If you don’t store data in a value (the return), then the computer does the calculations but that’s it. You won’t be able to retrieve that final result when you need it.
What two special characters can a variable begin with?
‘$’ and ‘_’ dollar and underscore. No dashes or periods in a variable name.
How do you declare a variable?
The ‘var’ keyword, then an identifier/variable name. One word written in camelCase.
How do you assign a value to a variable?
Var myVar = value. Equal sign then the value you want to assign.
Are variables case sensitive?
Yes
Which words cannot be used as variable names?
Other JS keywords or reserved words. ‘var’, ‘function’, ‘let’, etc. Numbers and symbols (besides $).
What is a string?
A primitive data type. A grouping of characters.
What is the string concatenation operator?
+ sign
What is the difference when it comes to using single quotes or double quotes (‘ ‘or” “)?
There is no difference in javascript, however if you want to use quotes inside of a string, you will have to escape them, or use the opposite (single or double quote) type of quote to surround the string.
How do youescapequotation characters?
Back slash before the character that needs escaping.
What is type coercion?
When two different data types are combined and both end up being one data type.
12+’hello’ turns into a string of ‘12hello’
What is a number in JavaScript?
Primitive data type that is any numeric value.
What is an arithmetic operator?
Something to perform mathematic equations.
Name four of the arithmetic operators?
+ - / % * ++ –
What is the order of execution?
Follows basic math, where multiplication and division happen before addition/subtration. Right hand side of equal sign, then left hand side. Use parenthesis to change order of operations. PEMDAS
What is a function?
Code that executes a code block. Collection of code that runs as one.
Why are functions useful?
They are -re-usable blocks of code. Saves time writing the same thing over and over. A way to store steps to be used later, for when functions don’t immediately run on page load.
How do you call a function?
Write out the function name with parenthesis and any arguments if you need them.
What are the parts of a function definition?
‘function keyword’, ‘function name’, parenthesis with parameters inside, and curly braces for the code block.
What is the difference between a parameter and an argument?
The are the same, however, it is a parameter when you are defining a function, and is an argument when when you are calling it.
Why is it important to understand truthy and falsy values?
So we can properly do comparisons without unintended results.
Why is the typeof an objectnull?
It’s a bug that is just accepted now because changing it would be the end of the internet.
What is the difference between null and undefined?
Null is purposefully set by the developer and denotes meaningful space. Undefined is generally an accident and is just straight up nothingness. Does not take up space in the memory.
Why do you always use===for comparisons?
Because loose equality == can cause type coercion and give weird results like when comparing 3 == ‘3’.
Why do you want to avoid using==for comparison?
Type coercion and unintended results due to it. Like 3 == “3”.
Do allifstatements require anelsestatement?
No
What is the proper syntax for using theoroperator?
Operand 1 || operand 2
What is the primary use case forswitches?
Comparing an individual value against a range of other individual values. 1 to 1 comparisons.
Does thedefaultcase have to be at the bottom of theswitchstatement?
No it does not. It is ‘else’ of switch statements, but doesn’t need to be at the bottom. But for good practice, you should put it at the bottom.
What happens if there is nobreakstatement betweencases?
It falls through to all subsequent cases and runs the code for each of them until it reaches a break or there are no more cases.
What is an object in JavaScript?
A group of variables and functions that create a model.
A collection of properties and methods grouped together.
It points to a memory address that points to where the data is actually stored,. Contrasted to primitive datatypes where the value is stored right at the variable.
How do you create an object literal?
Literal notation: Var newObject = { }; Object constructor notation: var newObject = new Object();
What is a property in relation to JavaScript objects?
It tells us about the object, like traits or attributes. A place where we can store data inside of the object.
When should you use bracket notation over dot notation with objects?
When the property name is a variable or when the property name is an illegal character, like a space, or if its a number.
How do you remove a property from an object?
Delete myObj.myProp or myObj.myProp = “”;
What is an array in JavaScript?
An object that stores a list of values that are related to each other. Useful for when you don’t need to specify how many values it will hold. (shopping lists, ingredient lists).
How do you create an array literal?
Var myArray = [ ];
What are the keys for the values inside an array?
Numbers. Index positions, that start counting from ‘0’. [0].
Arrays have a property named length. Because arrays have a properties, what other data structure are they similar to?
Objects.
What are some good use cases for using objects inside arrays?
School directory, medical patient data base, any database where each index have similar properties. Shopping cart.
What is the primary advantage to storing your selected elements in a variable?
You don’t have to type out long dom queries over and over again when modifying them
Why might you need JavaScript to modify the DOM after the page loads?
It gives us interactivity with the user. We can update visuals after certain behaviors/actions
For maybe a ‘dark mode’ button on the page that converts all styling from light to dark.
For things like forms: clearing the form after submitting/resetting.
How can you better prepare when writing HTML for DOM manipulation in your JavaScript code?
Setting classes and ID’s appropriately? Structure your html (parents and children) in an organized way?
How to see all the info about the html document? The DOM, document object model.
Console.dir(document); This is our pathway from JS to the html and how it see’s the html and how will interact with it.
What are the differences betweeninnertextandtextContent?
similar to textContent but you should avoid it due to some browsers dont support it, it will not show any content that’s hidden by css. It also takes into account layout rules that specify whether the element is visible or not, so it can be slower than .textContent to retrieve content.
InnerText generally shows what you would visually SEE on the html. It doesn’t show hidden stuff. InnerText has to interpret the html AND any CSS that affects it. So it takes longer.
What datatype are the values you remove from a text input?
strings
Why is it so important to be able to dynamically update text?
So you don’t have waste time and bandwidth to reload the entire page to see changes. So the user can interact with the website. Making changes to the page after a user triggers an input.
What are some of the drawbacks of HTML Event Handler Attributes?
They are harder to make edits to later, especially if there are lots of elements with the same function? Makes code harder to read and hard to understand what the event is doing.
Why is the Window.event property useful for finding an element which was interacted with?
It shows x and y coordinates of the screen of where the event took place. And also the element that was clicked.
Why is the Window.event property to be avoided in new code?
Window.event changes with every single event. The value gets overwritten when a new event occurs. If you wanted to work with values of the event after it occurred, if another event happened in between that time, then you would be working off that new event. You would never know.
What is the difference between thegetElementById()method and thequerySelector()method?
GetElementById() returns the exact element with that ID. QuerySelector() targets the first element (using css selectors) within the document that matches the specified selector or group of selectors.
Who passes in the event object into thehandleClickcallback function?
Javascript automatically does it.
Does a callback function require a name?
No. You can have an anonymous function, but you should name them. Not reason not to.
What is the purpose of a loop?
To iterate through data quickly and automatically, saving time.
Why might there be different kinds of loops?
There may be different situations and conditions for what you need. If you know the exact amount of items you need to loop over, use a for loop. If you don’t know how many items there are, but you know when you need to end use a while loop.
What is the purpose of a conditional expression as it relates to loops?
It’s similar to a conditional statement in that, if the conditional statement is true, the code will run.
Could a loop potentially go on forever?
Yeah if a condition remains true (sometimes due to user-error syntax), and it will crash your browser.
Could a loop never start?
Yes, if the condition doesn’t result to true on the very first run, it will not run the first loop. Exception to this is a ‘do while’ loop, which will run one time.
How does aforloop differ from awhileloop?
How does aforloop differ from awhileloop?
A for loop is for when you know exactly how many items you need to loop over. A while loop is when you don’t know how many items, but you know when it should end. If an array keeps changing, like things getting deleted or added, that’s a good chance to use while loop.
While loops only need a condition. And for loops need a initilization and final expression ( to actually do something )? Watch vod.
What potential use cases are there forforloops?
Logging out a recipe/ingredient list. Student list. Todo list?
Which pieces of information provided in the parentheses for aforloop are mandatory?
None of them. The semi colons are required though. For (;;) { };
What is a for in loop?
A way to iterate through properties of an object.
How do you target the value of a property in an object.
Bracket notation. object[variable]
When should you use a for in loop?
When you want to loop over an object and do the same action on each property.
Good for debugging purposes, easy way to check the properties of an object (by outputting to console or otherwise). Though arrays are more practical for storing data, there are situations where a key-value pair is preferred (with properties acting as the ‘key’, and there may be instances where you want to check if any of those keys hold a particular value.
What is the difference between theparentNodeandparentElementproperties?
ParentElement will return null if the parent element is not an element. ParentNode will return things like white spaces as parents if a white space is present.
Why is it important to be able to traverse the DOM?
Flexibility in being able to target the exact elements you want to.
What kind of information is useful to store in custom attributes?
Useful information that describes the element? Easy ways for JS to access the element? Can use those custom attributes in JS to augment the page based on user interaction?
Clicking a fruit might trigger a pop up that shows info stored in a custom attribute like nutritional facts or something
-<img></img>
What are two ways to target elements on the DOM?
.querySelector(), .querySelectorAll(), getElementById(), getElementByTagName(), getElementByName(), getElementByClassName()
What is another way to add a text node to an element other than usingtextContent.
document.createTextNote(‘’) then appending it. InnerText takes out all whitespace. InnerHTML only shows whats visible.
How do you create a HTML element using vanilla Javascript?
Document.createElement(‘elementName’);
Why is using loops and arrays for creating multiple dom elements preferable to creating them one at a time?
It saves a lot of time. Not having to repeat yourself. And maybe loads a millisecond faster, no clue?
Why are arrays preferred over objects for the functionality referenced in question 1?
Because arrays have order? Arrays are indexed, so you can guarantee order. Objects might not get iterated in order.
Why is it important to be able to retrieve and use data from inputs?
It’s our communication path with our user. It allows them to interact with the site, and for our site to interact with their actions.
Good for to-do lists or creating notes or something. We can use that data to perform other events and modifications to the dom.
Why is it dangerous to assume you have the correct data when creating elements?
Just have to be careful to not mess up your webpage or something, especially if working off of data inputted by the user. If user inputs some sort of malicious code, and you use that code and create an element with it, it could be bad.
What is jQuery?
It is a library. It’s a JS file that you include in your web pages. It allows you to find elements using CSS-style selectors then do something with the elements using jQuery methods.
What is the jQuery selector function?
$() or jQuery().
What does the jQuery selector function return?
All elements that match? an Object?
Why would someone use jQuery over vanilla JavaScript?
Convenience of faster DOM traversal, and for property chaining. Core JS has everything that jQuery has.
What are some downsides from using jQuery over vanilla JavaScript?
It’s gonna die out eventually. It kind of departs from the actual original JS language. If you only get good at jQuery and always use it, then once jQuery dies out, you will be screwed.
Load time is also slower because it has to load it’s own JS page.
Why do we use thetag at the bottom of the body, instead of putting it inside the<head>tag?
Because there are changes to the DOM with JS, it will try to do them before the HTML has even loaded yet and not work.
How do you get the text out of an HTML element?
html() or text()
How do you get the value out of an HTML input field?
.val()
What’s the difference between.text()and.html()?
html grabs only from the first element matched, and also includeds all the markup. text grabs text from all matches and includes spaces, but no markup. Also does not include linebreak spaces.
What does.on()do?
it is like the eventlistener of jquery.
What is event bubbling?
When an event occurs on a target, and then goes up through through all of its ancestors.
What is the difference betweenevent.targetandevent.currentTarget.
event.target is the exact element clicked on, and currentTarget is where the bubbling ends. Example, if clicked a child of a div, it also means that that click happens on the parent div, and every ancestor element it’s in.
currentTarget is what you put your eventListener on, but the target is the most immediate thing that you interacted with.
What is the first argument the function setTimeout takes?
A function.
If the second argument is not passed into the setTimeout function, what is the default value?
1second
What are some scenarios where setTimeout can be useful?
Annoying paywall pop ups. Maybe to have something change or pop up when user scrolls down.
What does the setInterval function return?
the timer interval that is set as an argument in the setInterval() method.
What argument does the clearInterval function take?
the intervalID, which is the name of the variable used to store the setInterval() method
What are some scenarios where setInterval can be useful?
A timed quiz? A game? -Watch Vod
What is the event loop?
It’s the loop in which JS code is called and resolved in a certain order. It consists of the call stack, the webAPI’s and the callback queue.
What does the termblockingmean?
Code that is slow. When a thread is taking a long time to execute a callback (event loop) or a task (worker), then it is blocked. While a thread is
What is the call stack?
The queue and order in which code runs and resolves in JS. Functions get to the top of the stack when called, then popped off the top when there is a return.
Which elements in a website are useful to create dynamically?
Elements that are created due to user interaction. Google search, instagram posts, any sort of live feed, shopping carts.
Why should you not create all elements dynamically?
It can get very confusing trying to modify and make changes to html skeletons when they are all made with JS. You’d have to inspect your page in a browser and see what attributes it has and the structure, instead of being able to just easily see it in your html file.
What is a modal?
A sub window that can pop up and require interaction before returning to the main window. A scripted effect that allows you to overlay a small element over a website. A modal is a graphical control element subordinate to an application’s main window. It creates a mode that disables the main window but keeps it visible, with the modal window as a child window in front of it. Users are forced to interact with the modal window before returning to parent application.
What are some use cases for modals?
- Ads, subscription requests, paywalls, errors, emergency states, amber alerts.
- errors, warnings, data collection, confirm or prompt (remind to do something before moving on), helper (inform users of important information).
Why does a modal usually need to occupy the entire height and width of the viewport?
Or else users can interact to the main window behind it?
Give two examples of media features that you can query in an@mediarule.
max width, min width, min height, max height, color, grid, hover, aspect-ratio, monochrome, orientation, pointer, scan, update.
- Nav list going from horizontal list to a hamburger button. Grid layouts. Changing a flex items’ flex-basis based on screen width. Basically any CSS Styling, like fonts, background-colors, background-images…
Which HTML meta tag is used in mobile-responsive web pages?
Why do we need a single source of truth?
- It is easier to keep track of what is being displayed and what data we store in one place, rather than having to cross reference a bunch of different files.
- It makes changing this data and the DOM easier, when it’s all stored in one spot.
- Consistency issues: DOM might be accurately reflecting the more up to date data in the JS data model.
Why would I create a function to generate my DOM Element instead of just writing my code in the global scope?
It’s easier to change something.
If you wanted to add another property to the data model, or a new object. It’s easy, since we have a reusable function that we use to just add it to the DOM.
Easier to modify the data model. Just add a new object then append the code.
What is a method?
A function that is a property of an object. They contain a set of instructions that together, represent one task.
What does a method do?
Runs a set of instructions on an object.
What isthis?
- a keyword whose value changes based on where/when a function is called (at runtime). Generally it refers to the object to the left of the ‘.’. So like myObject.method, where method: function(){console.log(this)} would return myOjbect.
- ‘this’ refers to the context where the function is being called, not where the function was defined. Is it always an object?
What does bind do?
- Set’s the ‘this’ keyword to the provided value. Basically makes its so the ‘this’ keyword doesn’t have a dynamic nature in which it changes based on how the function is called and in which scope.
- Kind of wraps a function up, so that ‘this’ will refer to the object argument we set, that the function/method appears in.
What is the difference between a function and an object literal?
- Functions are objects.
- for a function, the value of ‘this’ will change based on where its called? No clue. Are they the same thing?
- An object literal can hold many functions inside of it and they all can be referenced and targeted easily like you would with any properties of an object.
What is Prototypal Inheritance?
When creating an object, it inherits some usable methods from an object constructor (or prototype?), and that one has access to the methods from the the chained Object.prototype
What is the Prototypal Chain?
starts with your object that you made using a constructor, then it checks the constructor object, then the Object.prototype.
In the custom objects we created, I noticed that our prototype object has another__proto__property, where did that come from?
the Object.prototype?
Why does JavaScript have Prototypal Inheritance?
So we don’t have to define commonly used methods on every single object we make?
What does thenewkeyword do?
- Creates a new instance of an object, based off an object constructor, that inherits all properties/methods from it.
1. Creates a blank, plain JavaScript object;
2. Links (sets the constructor of) this object to another object;
3. Passes the newly created object fromStep 1as thethis
context;
4. Returnsthis
if the function doesn’t return an object.