JavaScript Flashcards
What is the purpose of variables?
To store data and information to be used for later
How do you declare a variable?
By using the var keyword and giving it a variable name
How do you initialize (assign a value to) a variable?
By using the “=” sign (assignment operator)
What characters are allowed in variable names?
Letters, numbers, dollar signs ($), or an underscore (_)
What does it mean to say that variable names are “case sensitive”?
Score and score are different variable names. Lowercase and Uppercase are different
What is the purpose of a string?
Add new text content into a page
What is the purpose of a number?
Represent numerical values. They are good for tasks that involve counting or calculating sums.
What is the purpose of a boolean?
Helpful when determining which part of a script should run.
What does the = operator mean in JavaScript?
Assignment operator
How do you update the value of a variable?
Assign a new variable value but with a different value. Don’t use the var keyword
What is the difference between null and undefined?
Null means an empty or non-existent value. Null is assigned, and explicitly means nothing.
Undefined means a variable has been declared, but the value of that variable has not yet been defined.
Why is it a good habit to include “labels” when you log values to the browser console?
It is much clearer which variables are being logged. If you do not include “labels”, it can be very confusing instead of helpful.
Give five examples of JavaScript primitives.
String, number, undefined, boolean, null
Primitives are stored data/values.
What data type is returned by an arithmetic operation?
A number
What is string concatenation?
The process of joining together 2 or more strings to create one new string
What purpose(s) does the + plus operator serve in JavaScript?
It adds numbers or concatenate strings
What data type is returned by comparing two values (, ===, etc)?
A boolean
What does the += “plus-equals” operator do?
adds the value of the right operand to a variable and assigns the result to the variable
What are objects used for?
group together a set of variables and functions to create a model of something you would recognize from the real world.
What are object properties?
A variable that is part of an object. Properties tell us about the object.
Describe object literal notation.
To access a property or method of an object you use the name of the object, followed by a period, then the name of the property or method you want to access.
How do you remove a property from an object?
Use the delete keyword and then use dot notation to identify the property or method you want to remove from the object
delete user.firstName
What are the two ways to get or update the value of a property?
Dot notation or square brackets
hotel.name = ‘park’;
hotel[‘name’] = ‘park‘;
What are arrays used for?
Store a list of values and items
Describe array literal notation.
Var with variable name, asmt operator (), [square bracket], values inside of it, [close with square bracket]
How are arrays different from “plain” objects?
Arrays use numerically indexed instead of property names.
What number represents the first index of an array?
[0]
What is the length property of an array?
The number of items in an array
How do you calculate the last index of an array?
Length - 1
What is a function in JavaScript?
An object that can allow you to package up code for use later in your program when called.
Describe the parts of a function definition.
- The function keyword to begin the creation of a new function.
- An optional name.
- A comma-separated list of zero or more parameters, surrounded by () parentheses.
- The start of the function’s code block, as indicated by an { opening curly brace.
- An optional return statement to stop the function
- The end of the function’s code block, as indicated by a } closing curly brace.
Describe the parts of a function call.
- The function’s name.
2. A comma-separated list of zero or more arguments surrounded by () parentheses.
When comparing them side-by-side, what are the differences between a function call and a function definition?
Function definition requires a function keyword. Function call just needs the name.
What is the difference between a parameter and an argument?
When we define a function, we declare parameters and that when we call a function, we pass it arguments.
Why are function parameters useful?
Parameters alter function behavior. Useful because it can make modifications to how they run. They are local variables to the functions which are necessary for the function to operate correctly.
What two effects does a return statement have on the behavior of a function?
Causes the function to produce a value we can use in our program.
Prevents any more code in the function’s code block from being run.
Why do we log things to the console?
To test if our code is working
What is a method?
Methods are functions stored as object properties
How is a method different from any other function?
Methods are attached to object.
How do you remove the last element from an array?
.pop
How do you round a number down to the nearest integer?
Math.floor
How do you generate a random number?
Math.random
How do you delete an element from an array?
array.splice method ( index , how many you want to delete)
How do you append an element to an array?
.push (Add to end)
.unshift (Add to beginning)
How do you break a string up into an array?
.split method
Do string methods change the original string? How would you check if you weren’t sure?
It does not change original string.
Check with .console log
Roughly how many string methods are there according to the MDN Web docs?
36
Is the return value of a function or method useful in every situation?
No because the return value is not always something you want to have. Sometimes you just want the functionality.
Roughly how many array methods are there according to the MDN Web docs?
50
What three-letter acronym should you always include in your Google search about a JavaScript method or CSS property?
MDN
Give 6 examples of comparison operators.
- Greater Than (>)
- Less Than (=)
- Equal To (==)
- Not Equal To( !=)
- Strict Not Equal To (!==)
What data type do comparison expressions evaluate to?
Boolean (true or false)
What is the purpose of an if statement?
Evaluates (or checks) a condition. IF the condition evaluates to true, any statements in the subsequent code block are executed.
Is else required in order to use an if statement?
No
Describe the syntax (structure) of an if statement.
Start with an if statement, Opening parentheses, condition operand, comparison operator, operand. Closing parentheses. Opening curly bracket. Return statement. Closing Curly Bracket.
What are the three logical operators?
Logical And (&&) Logical Or (||) Logical Not (!)
How do you compare two different expressions in the same condition?
Logical And (&&) or Logical Or (||)
What is the purpose of a loop?
Loops is to do something as fast possible a certain number of times.
What is the purpose of a condition expression in a loop?
To decide when the loop stop
What does “iteration” mean in the context of loops?
Everytime it goes through a loop
When does the condition expression of a while loop get evaluated?
Before each loop is run
When does the initialization expression of a for loop get evaluated?
At the start of the for loop. Before the loop begins.
When does the condition expression of a for loop get evaluated?
After the Initialization has been set. After the final expression runs
When does the final expression of a for loop get evaluated?
After the condition statement. After the code block.
Besides a return statement, which exits its entire function block, which keyword exits a loop before its condition expression evaluates to false?
Break keyword will break out of loop but not end the function.
What does the ++ increment operator do?
increments (adds one to) its operand and reassigns the value
How do you iterate through the keys of an object?
For…in loop
for (var property in object)
Why do we log things to the console?
To make sure our code is working properly
What is a “model”?
Representation of a web page with a DOM tree
Which “document” is being referred to in the phrase Document Object Model?
The tree structure of word page
What is the word “object” referring to in the phrase Document Object Model?
All the elements within the DOM tree which are then created into objects.
What is a DOM Tree?
As a browser loads a web page, it creates a model of that page. The model is called a DOM tree, and it is stored in the browsers’ memory. A hierarchical chart which breaks down all the pieces of a document with four main types of nodes
Give two examples of document methods that retrieve a single element from the DOM.
querySelector (get anything), getElementByID (Only get ID)
Give one example of a document method that retrieves multiple elements from the DOM at once.
getElementsByClassName, getElementsByTagName, querySelectorAll
Why might you want to assign the return value of a DOM query to a variable?
It saves the browser from looking through the DOM tree to find the same element again.
What console method allows you to inspect the properties of a DOM element object?
console.dir
Why would a tag need to be placed at the bottom of the HTML content instead of at the top?
The browser needs to parse all of the elements in the HTML page before the JavaScript code can access them.
What does document.querySelector() take as its argument and what does it return?
It takes a CSS Selector as an argument and returns the first of the matching elements.
What does document.querySelectorAll() take as its argument and what does it return?
It takes a CSS Selector as an argument and returns all of those that match in a node list/array
Why do we log things to the console?
To make sure our code is working properly
What is the purpose of events and event handling?
Events are things that happen in DOM response to input from a user.
Even handling trigger javascript code and run code in response to events
Are all possible parameters required to use a JavaScript method or function?
no
What method of element objects lets you set up a function to be called when a specific type of event occurs?
AddEventListener() method
What is a callback function?
A function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
What object is passed into an event listener callback when the event fires?
The event object
What is the event.target? If you weren’t sure, how would you check? Where could you get more information about it?
The target property of the Event interface is a reference to the object onto which the event was dispatched.
What is the difference between these two snippets of code?
element. addEventListener(‘click’, handleClick)
element. addEventListener(‘click’, handleClick())
The second one has a return value so it’s calling a function, which we don’t want.
What is the className property of element objects?
sets or returns the class name of an element (the value of an element’s class attribute).
How do you update the CSS class attribute of an element using JavaScript?
(Name of class).className = (‘string of new class name’)
What is the textContent property of element objects?
The textContent property represents the text content of the node and its descendants.
How do you update the text within an element using JavaScript?
TextContent and the asmt operator
Is the event parameter of an event listener callback always useful?
No
Why is storing information about a program in variables better than only storing it in the DOM?
Makes it easier to manipulate and keep track of things. Don’t need to rely on DOM.
What event is fired when a user places their cursor in a form control?
focus
What event is fired when a user’s cursor leaves a form control?
blur
What event is fired as a user changes the value of a form control?
input
What event is fired when a user clicks the “submit” button within a ?
The Submit event is fired. It’s fired on the form element
What does the event.preventDefault() method do?
It prevents an event from being handled with it’s default behavior.
What does submitting a form without event.preventDefault() do?
The browser will automatically reload the page with the form’s values in the URL.
What property of a form element object contains all of the form’s controls?
Elements property
What property of form a control object gets and sets its value?
Value property
What is one risk of writing a lot of code without checking to see if it works so far?
You could write a lot of code and not know where the problem is
What is an advantage of having your console open when writing a JavaScript program?
You can make sure your code is working the whole time and catch errors early
Does the document.createElement() method insert a new element into the page?
It does not because it’s not specified where on the page it should go
How do you add an element as a child to another element?
appendChild
What do you pass as the arguments to the element.setAttribute() method?
.setAttribute(name, value)
What steps do you need to take in order to insert a new element into the page?
Create element, append it to child of something that is on the page.
What is the textContent property of an element object for?
To set the text content of an element
Name two ways to set the class attribute of a DOM element.
setAttribute, className
What are two advantages of defining a function to create something (like the work of creating a DOM tree)?
Defining a function allows you to reuse it to save time.
Helps to organize html you’re creating
What is the event.target?
a reference to the object onto which the event was dispatched. The event interacted with by the user
Why is it possible to listen for events on one element that actually happen in its descendent elements?
Because event bubbling goes all the way up to the parent.
What DOM element property tells you what type of element it is?
event.target.tagName
What does the element.closest() method take as its argument and what does it return?
Takes a selector as an argument and returns the closest parent it has. It can also return itself.
How can you remove an element from the DOM?
Remove method
If you wanted to insert new clickable DOM elements into the page using JavaScript, how could you avoid adding an event listener to every new element individually?
Adding it to the parent and have it bubble up.
What is the event.target?
a reference to the object onto which the event was dispatched. The event interacted with by the user
What is the effect of setting an element to display: none?
the affected element will disappear.
What does the element.matches() method take as an argument and what does it return?
a string representing the selector to test. Returns boolean value. true if the element would be selected by the specified selector string; otherwise, returns false
How can you retrieve the value of an element’s attribute?
.getAttribute()
At what steps of the solution would it be helpful to log things to the console?
All the time.
If you were to add another tab and view to your HTML, but you didn’t use event delegation, how would your JavaScript code be written instead?
Put individual event listeners on each of the tabs.
If you didn’t use a loop to conditionally show or hide the views in the page, how would your JavaScript code be written instead?
You would write an if statement for each tab
What is JSON?
A standard text-based data format following JavaScript object syntax.
JavaScript Object Notation
What are serialization and deserialization?
Serialization is the process of turning an object in memory into a stream of bytes
Deserialization is the reverse process: turning a stream of bytes into an object in memory.
Why are serialization and deserialization useful?
Serialized code can be transferred over a network or stored in a persistent storage and brought back with deserialization in the same state.
How do you serialize a data structure into a JSON string using JavaScript?
JSON.stringify()
How do you deserialize a JSON string into a data structure using JavaScript?
JSON.parse()
How to you store data in localStorage?
localStorage.setItem(key, value);
localStorage.setItem(‘myCat’, ‘Tom’);
How to you retrieve data from localStorage?
localStorage.getItem(key);
What data type can localStorage save in the browser?
JSON strings
When does the ‘beforeunload’ event fire on the window object?
when the window, the document and its resources are about to be unloaded.
What is a method?
A method is a function which is a property of an object
How can you tell the difference between a method definition and a method call?
A method definition is the function.
A method call is just the objectName.method()
Ex: var calculator = { add: function (x, y) { var sum = x + y; return sum; }; In example, calculator.add(x, y) is method call. Add is method definition.
Describe method definition syntax (structure).
Give property name, define a function with parameters, opening curly brace, closing curly brace
Ex: var calculator = { add: function (x, y) { var sum = x + y; return sum; };
Describe method call syntax (structure).
Start with the object variable name, dot, name of the method with parameters
objectName.method()
Ex: var calculator = { add: function (x, y) { var sum = x + y; return sum; };
method call is calculator.add(x, y)
How is a method different from any other function?
Method is attached to an object. Function is defined outside.
What is the defining characteristic of Object-Oriented Programming?
objects can contain both data (as properties) and behavior (as methods).
What are the four “principles” of Object-Oriented Programming?
Abstraction
Encapsulation
Inheritance
Polymorphism
What is “abstraction”?
the process of removing physical, spatial, or temporal details or attributes in the study of objects or systems to focus attention on details of greater importance
What does API stand for?
Application Programming Interface
What is the purpose of an API?
to give programmers a way to interact with a system in a simplified, consistent fashion:
What is this in JavaScript?
an implicit parameter of all JavaScript functions.
the value of this is determined by how a function is called
What does it mean to say that this is an “implicit parameter”?
It means that it is available in a function’s code block even though it was never included in the function’s parameter list or declared with var
When is the value of this determined in a function; call time or definition time?
When the function is called, call time.
What does "this" refer to in the following code snippet? var character = { firstName: 'Mario', greet: function () { var message = 'It\'s-a-me, ' + this.firstName + '!'; console.log(message); } };
Given the above character object, what is the result of the following code snippet? Why?
character.greet();
Given the above character object, what is the result of the following code snippet? Why?
var hello = character.greet; hello();
This refers to character object.
It’s-a-me, Mario! Because this refers to character object.
It’s-a-me, undefined! Because the value of this is determined when the function is called, not when it is defined.
How can you tell what the value of this will be for a particular function or method definition?
the value of this can be recognized as “the object to the left of the dot” when the function is called (as a method).
How can you tell what the value of this is for a particular function or method call?
The object before the method. If nothing is there, it will be the global window.
What kind of inheritance does the JavaScript programming language use?
prototype-based (or prototypal) inheritance
What is a prototype in JavaScript?
object that contains properties and (predominantly) methods that can be used by other objects.
How is it possible to call methods on strings, arrays, and numbers even though those methods don’t actually exist on objects, arrays, and numbers?
They all have a prototype object within them.
If an object does not have it’s own property or method by a given key, where does JavaScript look for it?
In it’s prototype chain
What does the new operator do?
create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.
What property of JavaScript functions can store shared behavior for instances created with new?
prototype
What does the instanceof operator do?
tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object. The return value is a boolean value.
What is a “callback” function?
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
Passing a function into another function as an argument
Besides adding an event listener callback function to an element or the document, what is one way to delay the execution of a JavaScript function until some point in the future?
By setting a delay on the setTimeout()
How can you set up a function to be called repeatedly without using a loop?
By using a set interval
What is the default time delay if you omit the delay parameter from setTimeout() or setInterval()?
0
What do setTimeout() and setInterval() return?
setTimeout()
The returned timeoutID is a positive integer value which identifies the timer created by the call to setTimeout().
setInterval()
The returned intervalID is a numeric, non-zero value which identifies the timer created by the call to setInterval(); this value can be passed to clearInterval() to cancel the interval.
What is a client?
Clients, also known as service requesters, are pieces of computer hardware or server software that request resources and services made available by a server.
What is a server?
the providers of a resource or service
Which HTTP method does a browser issue to a web server when you visit a URL?
GET Method
What three things are on the start-line of an HTTP request message?
1) An Http method
2) the request target (Usually URL)
3) Http version
What three things are on the start-line of an HTTP response message?
Protocol version, a status code, status text
What are HTTP headers?
HTTP headers let the client and the server pass additional information with an HTTP request or response. An HTTP header consists of its case-insensitive name followed by a colon (:), then by its value.
Where would you go if you wanted to learn more about a specific HTTP Header?
MDN
Is a body required for a valid HTTP request or response message?
No
What is AJAX?
is a programming practice of building complex, dynamic webpages using a technology known as XMLHttpRequest.
What does the AJAX acronym stand for?
Asynchronous JavaScript And XML
Which object is built into the browser for making HTTP requests in JavaScript?
XMLHttpRequest
What event is fired by XMLHttpRequest objects when they are finished loading the data from the server?
Load event
An XMLHttpRequest object has an addEventListener() method just like DOM elements. How is it possible that they both share this functionality?
Because of prototype
What is a code block? What are some examples of a code block?
A block of code written in between curly braces. Ex: If statement, for loop, functions
What does block scope mean?
A block scoped variable means that the variable defined within a block will not be accessible from outside the block
What is the scope of a variable declared with const or let?
Block scoped
What is the difference between let and const?
Let is immutable meaning you change the value. Const is not immutable.
Why is it possible to .push() a new value into a const variable that points to an Array?
Because the cont only holds a pointer value to where the array is stored in memory. We’re not changing the memory address at all when pushing.
Because it functions similarly to updating an object values. It’s already declared and assigned, you’re just adding to the “list” that the constant points to.
How should you decide on which type of declaration to use?
If the value never changes, use const. If the value of the variable needs to change then you use let.
Make everything const, second you find out you have to change it, change to let. Const more efficient.
What is the syntax for writing a template literal?
Wrap text in back ticks `. Substitute variables using ${}
What is “string interpolation”?
the ability to substitute part of the string for the values of variables or expressions. Substitute variables using ${} wrapped in curly braces
What is destructuring, conceptually?
Breaking down the contents of an object or an array into variables to be called later
What is the syntax for Object destructuring?
const { firstName, lastName, middleName } = person;
const { firstName: fname, lastName: lname } = person;
^ To change the name of the property ^
const foo = ['one', 'two', 'three']; const [red, yellow, green] = foo;
console. log(red); // “one”
console. log(yellow); // “two”
console. log(green); // “three”
What is the syntax for Array destructuring?
const [x, y, z] = person;
How can you tell the difference between destructuring and creating Object/Array literals?
Arrays use brackets
Destructuring object takes place on the left hand sind on equal sign
Destructing array take place on the right hand side of equal sign
What is the syntax for defining an arrow function?
let add = (x, y) => x + y; let add = (x, y) => {
When an arrow function’s body is left without curly braces, what changes in its functionality?
Only the first line will be returned. It is an implicit return.
The parenthesis are returning a single value, the curly braces are executing multiple lines of code like a normal function.
How is the value of this determined within an arrow function?
Arrow functions have a lexical this and its value within the arrow function is determined by the surrounding scope.
What is a CLI?
Command Line Interfaces
What is a GUI?
Graphical User Interface
Give at least one use case for each of the commands listed in this exercise
Man: gives manual page for any command (manual)
cat: concatenate files and view contents of file (concatenate)
ls: list directory contents (list segment)
pwd: print name of current/working directory to check which folder you are in (print working directory)
echo: display a line of text
touch: create new files. Also change timestamps
mkdir: create new directories (make directory)
mv: move (rename) files or folders (move)
rm: delete files or directories (remove). Use -r to remove contents within
cp: copy files or directories (copy). Use -r to copy contents within
What are the three virtues of a great programmer?
Laziness: The quality that makes you go to great effort to reduce overall energy expenditure. It makes you write labor-saving programs that other people will find useful and document what you wrote so you don’t have to answer so many questions about it.
Impatience: Impatience: The anger you feel when the computer is being lazy. This makes you write programs that don’t just react to your needs, but actually anticipate them. Or at least pretend to.
Hubris: The quality that makes you write (and maintain) programs that other people won’t want to say bad things about.
How are ES Modules different from CommonJS modules?
Es6 uses import/export statements
CommonJS uses require/module.export
What kind of modules can Webpack support?
ECMAScript modules. CommonJS modules. AMD modules.
Front End Uses
ES Modules
Import/export statements
Back End uses
CommonJS modules
require()/module.export