Javascript Flashcards
What is the purpose of variables?
Store data/information
How do youdeclarea variable?
Start with variable keyword (const, var, or let) follow by a variable name
How do you initialize (assign a value to) a variable?
Using the assignment operator ‘’=’
What characters are allowed in variable names?
dollarsign ($) and underscore (_), letters and numbers
What does it mean to say that variable names are “case sensitive”?
The cases matter. “one” is not the same as “One”
What is the purpose of a string?
To store text as values
What is the purpose of a number?
To store numeric values
What is the purpose of a boolean?
To show true or false
What does the=operator mean in JavaScript?
assign
• How do you update the value of a variable?
assign a new value to that variable
What is the difference betweennullandundefined?
null is intentionally empty, will be updated later. undefined means a value has been declared by has no value.
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 and in what order. Good for debugging
Give five examples of JavaScript primitives.
string, boolean, number, undefined and null
What data type is returned by an arithmetic operation?
number
What is string concatenation?
Process of joining together two or more strings
What purpose(s) does the+plus operator serve in JavaScript?
it can serve as an addition for arithmetic operators and a string operator for concatenation
What data type is returned by comparing two values (,===, etc)?
boolean
What does the+=”plus-equals” operator do?
adds values and then it re-assigns to same variable
What are objects used for?
grouping together a set of variables and functions with property values and methods; used to model real-life objects
What are object properties?
properties are variables that are part of an object; objects can store any data types
Describe object literal notation.
{}; opening and closing curly braces.
How do you remove a property from an object?
delete operator
What are the two ways to get or update the value of a property?
dot and bracket notation
What are arrays used for?
used for storing lists of data, numerically indexed
Describe array literal notation.
square brackets [ ]
How are arrays different from “plain” objects?
numerically indexed from 0 while objects aren’t numerically indexed
What is thelengthproperty of an array?
it measures how long the array is; how many indexes are in an array
How do you calculate the last index of an array?
array[array.length-1]
What number represents the first index of an array?
0
What is a function in JavaScript?
a block of code designed to perform a particular task.
Describe the parts of a function call.
the function name and the arguments being passed inside the parenthesis
When comparing them side-by-side, what are the differences between a function call and a function definition?
The function definition has the parameter and the code block { }. The call takes the arguments that are passed into the function.
What is the difference between a parameter and an argument?
Parameters are variables listed as a part of the function definition. Arguments are values passed to the function when it is invoked
Why are function parameters useful?
allows you to pass information into the function
What two effects does a return statement have on the behavior of a function?
returns the value of code and stops executing the code block
Why do we log things to the console?
To debug and check data
What is a method?
A method is a function which is a property of an object.
How is a method different from any other function?
Methods exist as a property on an object
How is a method different from any other function?
Methods exist as a property on an object/ methods can use items in the object.
How do you round a number down to the nearest integer?
Math.floor( ) method
How do you generate a random number?
Math.random( ) method
How do you delete an element from an array?
.splice ( ), .pop ( ), .shift( )
How do you delete an element from an array?
.splice ( ) method
How do you append an element to an array?
.push ( ) method
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?
no; check by using the console log & MDN
Roughly how many string methods are there according to the MDN Web docs?
A lot; 40ish
Roughly how many array methods are there according to the MDN Web docs?
A lot; more than 30
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.
Less than () Greater than or equal (>=) Loosely equal to (==) Strictly equal to (===) Not loosely equal to (!=) Not strictly equal to (!==)
What data type do comparison expressions evaluate to?
boolean
What is the purpose of an if statement?
A conditional statement to check whether or not to do certain actions/ make a decision
Is else required in order to use an if statement?
No
Describe the syntax (structure) of an if statement.
a “if”keyword followed by a condition in parentheses ( ) and an opening curly brace for the code block and closing curly brace
What are the three logical operators?
&& (and / ampersand),
| | (or/ double pipe),
! (not / bang)
How do you compare two different expressions in the same condition?
logical operators
What is the purpose of a loop?
to repeat an action/code
What is the purpose of a condition expression in a loop?
the purpose to sets the rules for the loop and tell it when to end.
What does “iteration” mean in the context of loops?
the number of times it runs
When does the condition expression of a while loop get evaluated?
before each iteration
When does the initialization expression of a for loop get evaluated?
before the condition/the loops start
When does the condition expression of a for loop get evaluated?
1
When does the final expression of a for loop get evaluated?
end of each loop iteration
Besides a return statement, which exits its entire function block, which keyword exits a loop before its condition expression evaluates to false?
break
What does the ++ increment operator do?
increase the value by 1
How do you iterate through the keys of an object?
for in loop
Why do we log things to the console?
to test and to debug code
What is a “model”?
a recreation of something to be used as an example
Which “document” is being referred to in the phrase Document Object Model?
the HTML document
What is the word “object” referring to in the phrase Document Object Model?
the elements
What is a DOM Tree?
a recreation of the html elements on the page that can be acc
Give two examples of document methods that retrieve a single element from the DOM.
getElementById(), querySelector()
Give one example of a document method that retrieves multiple elements from the DOM at once.
getElementByClassName()
querySelectorAll()
Why might you want to assign the return value of a DOM query to a variable?
to store the location of the element and to stop searcgubg
What console method allows you to inspect the properties of a DOM element object?
the dir method of the console object
Why would a tag need to be placed at the bottom of the HTML content instead of at the top
JS needs to load after the HTML - so the DOM can load first
What does document.querySelector() take as its argument and what does it return?
an element selector and that selector
What does document.querySelectorAll() take as its argument and what does it return?
CSS selector and returns the NodeList
Why do we log things to the console?
checking functionality and check data; test code and debug
What is the purpose of events and event handling?
Events - the browser’s way of indicating when something has happened: page finished loading, button has been clicked
Event handlers- let you indicate which event you are waiting for on any particular element.
Overall - to trigger a function; make the page feel more interactive
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 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.
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?
It is a reference to the value of the object onto which the event was dispatched. Check with MDN
What is the difference between these two snippets of code?
- element.addEventListener(‘click’, handleClick)
- element.addEventListener(‘click’, handleClick())
The first one is a callback function and second one is calling the function. The second one immediately calls the function
What is the difference between these two snippets of code?
- element.addEventListener(‘click’, handleClick)
- element.addEventListener(‘click’, handleClick())
The first one is a callback function and second one is calling the function. The second one immediately calls the function
What is the className property of element objects?
The className property of the Element interface gets and sets the value of the class attribute of the specified element.
How do you update the CSS class attribute of an element using JavaScript?
By using className property and selecting the CSS property
What is the textContent property of element objects?
It represents the text content of the node and its descendants.
It selects and changes the text of the selected element and all its node
How do you update the text within an element using JavaScript?
textContent or innerText property
Is the event parameter of an event listener callback always useful?
generally useful but not always
Would this assignment be simpler or more complicated if we didn’t use a variable to keep track of the number of clicks?
more complicated
Why is storing information about a program in variables better than only storing it in the DOM?
May cause more work and we can’t depend on the DOM
What event is fired when a user places their cursor in a form control?
focus event
What event is fired when a user’s cursor leaves a form control?
blur event
What event is fired as a user changes the value of a form control?
input event
What event is fired when a user clicks the “submit” button within a ?
submit event
What does the event.preventDefault() method do?
to prevent the browser from automatically reloading the page (its default action should not be taken as it normally would be)
What does submitting a form without event.preventDefault() do?
reloads the page
What property of a form element object contains all of the form’s controls.
elements; The HTMLFormElement property elements returns an HTMLFormControlsCollection
What property of form a control object gets and sets its value?
the value property (.value)
What is one risk of writing a lot of code without checking to see if it works so far?
Not knowing where to start when an error occurs
What is an advantage of having your console open when writing a JavaScript program?
checking and debugging code in real time
Does the document.createElement() method insert a new element into the page?
No it doesn’t; it simply creates an element node (stored in a variable) that is ready to be inserted
How do you add an element as a child to another element?
the appendChild() method
What do you pass as the arguments to the element.setAttribute() method?
name, value
What steps do you need to take in order to insert a new element into the page?
create the element, set the element’s text content (optional), append the element to a parent node
What is the textContent property of an element object for?
represents the text content of the node and its descendants.
Name two ways to set the class attribute of a DOM element.
The className property and setAttribute() method.
ex. var firstltem=document.getElementByld(‘one’);
firstltem. className = ‘complete ‘
What are two advantages of defining a function to do create something (like the work of creating a DOM tree)?
saves time and automation/ don’t have to repeat yourself. use it for different purposes
What is the event.target?
The target property of the Event interface is a reference to the object onto which the event was dispatched.
The target event property returns the element that triggered the event.
The target property gets the element on which the event originally occurred
Why is it possible to listen for events on one element that actually happen its descendent elements?
event bubbling
What DOM element property tells you what type of element it is?
tagName property
What does the element.closest() method take as its argument and what does it return?
it takes a string selector and returns the closest ancestor of the selected element or 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?
add the event listener to the parent node and delegate the child nodes
What is the event.target?
The target property of the Event interface is a reference to the object onto which the event was dispatched.
The target event property returns the element that triggered the event.
The target property gets the element on which the event originally occurred
What is the affect of setting an element to display: none?
it makes it invisible; the element is not displayed and is completely removed from the document flow.
What does the element.matches() method take as an argument and what does it return?
it takes a selectorString and returns a boolean value
How can you retrieve the value of an element’s attribute?
.getAttribute( attributeName ) method
At what steps of the solution would it be helpful to log things to the console?
every line/step
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?
you would have to event list every .tab element with multiple event listener
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 have to event list every individual .view container and assign it with if statements
What is JSON?
JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax
What are serialization and deserialization?
Serialization is the process of turning an object in memory into a stream of bytes so you can do stuff like store it on disk or send it over the network. (converting an object to a string)
Deserialization is the reverse process: turning a stream of bytes into an object in memory. (converting a string into an object)
Why are serialization and deserialization useful?
network transmission, useful in transferring/storing data to a database, file or to memory
How do you serialize a data structure into a JSON string using JavaScript?
the JSON.stringify method
How do you deserialize a JSON string into a data structure using JavaScript?
the JSON.parse method
How to you store data in localStorage?
localStorage.setItem( ) method
How to you retrieve data from localStorage?
localStorage.getItem( ) method
What data type can localStorage save in the browser?
string values
When does the ‘beforeunload’ event fire on the window object?
The beforeunload event is fired 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.
There are two kind of methods: Instance Methods which are built-in tasks performed by an object instance, or Static Methods which are tasks that are called directly on an object constructor.
How can you tell the difference between a method definition and a method call?
method definition has a function keyword with it being defined while method call just has the method name with parentheses
Describe method definition syntax (structure).
property in an object with function keyword and parameters in parenthesis with code in the code block between the curly braces
ex: var object = { methodDefinition: function { } }
Describe method call syntax (structure).
dot notation to access the method in the object
ex: object.methodcall( )
How is a method different from any other function?
it is a property of an object
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”?
Abstraction is a way to reduce complexity and allow efficient design and implementation in complex software systems. It hides the technical complexity of systems behind simpler APIs.
advantage: Helps the user to avoid writing low level code. Avoids code duplication and increases reusability. Can change internal implementation of class independently without affecting the user. Helps to increase security of an application or program as only important details are provided to the user.
What does API stand for?
application programming interface
What is the purpose of an API?
API is a computing interface that defines interactions between multiple software intermediaries;
It gives programmers a way to interact with the system in a simplified consistent fashion
What is “this” in JavaScript?
This reference current object that you’re working on.
This is an implicit parameter of all JavaScript Functions; a keyword this is determined/defined at the call time
What does it mean to say that “this” is an “implicit parameter”?
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?
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); } };
the character object
Given the above character object, what is the result of the following code snippet? Why?
character.greet ( );
“It’s-a-me, Mario!”
The greet property has a function and this.firstName is character.firstName
Given the above character object, what is the result of the following code snippet? Why?
var hello = character.greet; hello( );
Undefined.
The property “greet” of the “character” object is being assigned to the “hello” variable, but since greet is a method that includes other properties of the “character” object that is noted with “this”, it would not be picked up.
How can you tell what the value of “this” will be for a particular function or method definition?
You can’t determine until it’s being called.
How can you tell what the value of “this” is for a particular function or method call
the value of this can be recognized as “the object to the left of the dot” when the function is called (as a method)
What kind of inheritance does the JavaScript programming language use?
prototype-based (or prototypal) inheritance
What is a prototype in JavaScript?
an object that will hold methods and properties that can be reused 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?
by using their prototype object that contains those methods
If an object does not have it’s own property or method by a given key, where does JavaScript look for it?
the prototype object; prototype chain
What does the “new” operator do?
The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.
creates a new object type:
- Creates a blank, plain JavaScript object.
- Adds a property to the new object (__proto__) that links to the constructor function’s prototype object
- Binds the newly created object instance as the this context (i.e. all references to this in the constructor function now refer to the object created in the first step).
- Returns this if the function doesn’t return an object.
What property of JavaScript functions can store shared behavior for instances created with “new”?
the prototype property
What does the “instanceof” operator do?
The instanceof operator 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.
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?
the setTimeout( ) function
How can you set up a function to be called repeatedly without using a loop?
the setInterval( ) function
What is the default time delay if you omit the delay parameter from setTimeout() or setInterval()?
0 seconds / no delay
What do setTimeout() and setInterval() return?
a positive integer value for the intervalID
What is AJAX?
Ajax is a technique for loading data into part of a page without having to refresh the entire page. The data is often sent in a format called JavaScript Object Notation (or JSON).
a programming practice of building complex, dynamic webpages using a technology known as XMLHttpRequest.
MDN: Ajax allows you to update parts of the DOM of an HTML page instead without the need for a full page refresh. Ajax also lets you work asynchronously, meaning your code continues to run while the targeted part of your web page is trying to reload (compared to synchronously, which blocks your code from running until that part of your page is done reloading).
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
Bonus Question: An XMLHttpRequest object has an addEventListener() method just like DOM elements. How is it possible that they both share this functionality?
it inherits the EventTarget prototype functionality which has the event listener function
What is a code block? What are some examples of a code block?
the code between curly braces
ex: if, switch conditions or for and while loops
What does block scope mean?
it means its scope is not global and is attached and exists only inside the current block (local)
What is the scope of a variable declared with const or let?
block scope
What is the difference between let and const?
const keyword creates block-scoped variables whose values can’t be reassigned vs let can be reassigned
Why is it possible to .push() a new value into a const variable that points to an Array?
the value of the const variable can be changed but the value itself can’t be reassigned.
How should you decide on which type of declaration to use?
If you know the value is going to change, use let. If not, stick with const
What is the syntax for writing a template literal?
${variable name/expression}
What is “string interpolation”?
the ability to substitute part of the string for the values of variables or expressions. (also know as string formatting)
What is destructuring, conceptually?
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
takes values from arrays or properties from objects and set them to local variables
What is the syntax for Object destructuring?
const or let { propName, PropName2, PropName3 } = objectName;
What is the syntax for Array destructuring?
const [variable names that we want to take out]= array name we want to destruct
How can you tell the difference between destructuring and creating Object/Array literals?
If it is happening on the left of the assignment operator, it is destructuring. If it is on the right side, it is defining.
What is the syntax for defining an arrow function?
(parameter) => {code block}
When an arrow function’s body is left without curly braces, what changes in its functionality?
you do not need a return statement
How is the value of this determined within an arrow function?
an arrow function captures the this value of the enclosing context instead of creating its own this context.
The value of this is defined when it is definition time, not when it’s called.
What is Node.js?
A program that allows JavaScript to be run outside of a web browser.
What can Node.js be used for?
It is commonly used to build back ends for Web applications, command-line programs, or any kind of automation that developers wish to perform.
What is a REPL?
read-eval-print-loop – a simple programming environment that takes single user inputs, executes them, and returns the result to user; it is executed piecewise.
When was Node.js created?
2009
What back end languages have you heard of?
Python, PHP, Ruby, Java, .net/C#
What is a computer process?
instance of a computer program that is being executed by one or many threads – a process is the actual execution of instructions
Roughly how many computer processes are running on your host operating system (Task Manager or Activity Monitor)?
about 150 process
Why should a full stack Web developer know that computer processes exist?
Full stack Web development is based on making multiple processes work together to form one application
What is the process object in a Node.js program?
The process object is a global that provides information about, and control over, the current Node.js process. As a global, it is always available to Node.js applications without using require().
How do you access the process object in a Node.js program?
console.log (process)
you just type process it since it is global and always available
What is the data type of process.argv in Node.js?
array
What is a JavaScript module?
a single .js file.
What values are passed into a Node.js module’s local scope?
exports, require, module, __filename, __dirname
(function(exports, require, module, \_\_filename, \_\_dirname) { // Module code actually lives in here });
Give two examples of truly global variables in a Node.js program.
console, process, and global
What is the purpose of module.exports in a Node.js module?
Module exports are the instruction that tells Node.js which bits of code (functions, objects, strings, etc.) to “export” from a given file so other files are allowed to access the exported code.
How do you import functionality into a Node.js module from another Node.js module?
use require( ) function with the other Node.js as the argument
What is the JavaScript Event Loop?
The event loop’s job is to look at the stack and look at the task queue. If the stack is empty it takes the first thing on the queue and pushes it on to the stack which effectively run it.
What is different between “blocking” and “non-blocking” with respect to how code is executed?
Blocking assignment executes “in series” because a blocking assignment blocks execution of the next statement until it completes. – slow
Non-blocking assignment executes in parallel because it describes assignments that all occur at the same time.
What is a directory?
File systems typically have directories – (also called folders) which allow the user to group files into separate collections
location where you store files.
What is a relative file path?
refers to a location that is relative to a current directory. a single dot represents the current directory itself.
- starting from current working directory.
- usually starts with ./
What is an absolute file path?
the exact path to a file from anywhere
full path/ complete location of the file or folder including which drive it is on.
- starting from root directory
- starts with forward slash /
What module does Node.js include for manipulating the file system?
fs module
What method is available in the Node.js fs module for writing data to a file?
writeFile( )
Are file operations using the fs module synchronous or asynchronous?
asynchronous
What are the three states a Promise can be in?
pending: initial state, neither fulfilled nor rejected.
fulfilled: meaning that the operation was completed successfully.
rejected: meaning that the operation failed.
How do you handle the fulfillment of a Promise?
by using then( ) method
How do you handle the rejection of a Promise?
by using catch( ) method
What is Array.prototype.filter useful for?
filtering through an array without having to make for loops
What is Array.prototype.map useful for?
when you want to perform functions on an array and use the returned array
What is Array.prototype.reduce useful for?
to combine values in an array into one single value
What does fetch() return?
returns a promise containing the response (a Response object)
note: fetch() allows you to make network requests similar to XMLHttpRequest (XHR)
What is the default request method used by fetch()?
get
How do you specify the request method (GET, POST, etc.) when calling fetch?
fetch(resource [, init])
-add in the optional, init arguments as an object specifying ‘POST’ to the property, ‘method’.
What must the return value of myFunction be if the following expression is possible?
myFunction()();
call myFunction first then
*calling its return value of the function inside of myFunction
What does this code do?
const wrap = value => () => value;
function wrap(value) => { return () => { return value } }
defines a function that returns a function
- the anonymous function is defined when the wrap is called
In JavaScript, when is a function’s scope determined; when it is called or when it is defined?
when the function is defined
What allows JavaScript functions to “remember” values from their surroundings?
closures