JavaScript Flashcards
What is the purpose of variables?
To store bits of data that the computer needs in order to do its tasks
How do you declare a variable?
with the keyword “var” followed by the identifier or variable name
How do you initialize (assign a value) to a variable?
with the assignment operator (=)
What characters are allowed in variable names?
letters of the alphabet, dollar sign ($), underscore, numbers (can’t start with number)
What does it mean to say that variable names are “case sensitive”?
e.g. the variables “test” and “Test” are different.
What is the purpose of a string?
sequence of characters that represent text
What is the purpose of a number?
represents a numeric data type that allows us to perform mathematical operations on it
What is the purpose of a boolean?
logical data type that only returns true or false. Useful for conditionals. Lets the computers ultimately decide what to do or not do.
What does the = operator mean in JavaScript
assignment operator. Assigns the value of the right to whatever is on the left.
How do you update the value of a variable?
the assignment operator can update the value of a variable. var keyword not necessary to update value
What is the difference between null and undefined?
undefined: JavaScript’s method of saying “empty”
null: developer’s way of saying “empty”; assigned intentionally
Why is it a good habit to include “labels” when you log values to the browser console?
Shows the user which logs represent which values. Logs without labels can cause confusion
Give five examples of JavaScript primitives
string, number, bigint, boolean, undefined, symbol, null
primitive: data that is not an object and has no methods. primitives can NOT be altered
What data type is returned by an arithmetic operation?
number
What is string concatenation?
using + to join together multiple things into a single string
What purposes does the plus (+) operator serve in JavaScript?
- addition
- string concatenation
What data type is returned by comparing two values (< , > , ===, etc)?
boolean
What does the += “plus-equals” operator do?
adds/concatenates the value on the right with the value on the left and then assigns it to the variable on the left.
What are objects used for?
to group relevant data together
What are object properties?
variables that live within an object
Describe object literal notation
declare a variable and assign it a value of a curly brace block. The contents of the curly brace block can be empty or consist of key, value pairs
How do you remove a property from an object?
Using the delete operator
delete object.property
What are the two ways to get or update the value of a property?
dot notation (object.property = value)
bracket notation (object[‘property’] = value)
What are arrays used for?
Useful when working with lists or groups of similar data
Describe array literal notation
var varName = [list contents (separated by comma)]
How are arrays different from “plain” objects?
values assigned to index numbers rather than keys
order is preserved in arrays
What number represents the first index of an array?
0
What is the length property of an array?
returns how many things are stored in the list
How do you calculate the last index of an array?
array.length - 1
What is a function in JavaScript?
A block of code that has a specific purpose and can be reused as many times as needed
Describe the parts of a function definition
keyword ‘function’ followed by optional name, zero to however many parameters, code block, optional return statement
function name(parameters,..) { return (optional) }
Describe the parts of a function call
functionName(arguments);
When comparing them side-by-side, what are the differences between a function call and a function definition?
a function call doesn’t need the code block, just function name followed by any arguments
function definition needs the initial code block and has parameters
What is the difference between a parameter and an argument?
Parameter is for function definition
argument is for function calls
Why are function parameters useful?
Allows the function to be dynamic
Can achieve different results depending on the data passed in
What two effects does a return statement have on the behavior of a function?
exits the code block immediately after executing a return line. (ends the function)
causes function to produce a value we can use in the program
Why do we log things to console?
In order to reduce confusion by keeping track of variables and making sure the data output is what we expected
What is a method?
function that is a property of an object
How is a method different from any other function?
They are properties of an object so they must be accessed as if they were a property (dot notation)
How do you remove the last element from an array?
array.pop( ); returns the removed element from the array
How do you round a number down to the nearest integer?
Math.floor( )
How do you generate a random number?
Math.random( ); Returns a number from 0 (inclusive) to 1 (not inclusive)
How do you delete an element from an array?
array.splice(n, x, y,…);
n: starting index
x: number of elements to remove (optional)
y: elements to add to the array (optional)
returns an array of the deleted elements
How do you append an element to an array?
array. unshift( ); adds to beginning of array
array. push( ); adds to end of an array
How do you break a string up into an array?
string.split(separator);
separator describes where the split should occur
Do string methods change the original string?
How to check if not sure?
No, can test in console by trying to change a string then console log the original string
Roughly how many string methods are there according to MDN Web docs?
37
Is the return value of a function or method useful in every situation?
No
Roughly how many array methods are there according to the MDN Web docs?
34
What 3 letter acronym should you always include in your Google search about a JavaScript method or CSS property?
MDN
Give 6 examples of comparison operators
, <=, >=, ===, !==
What data type do comparison expressions evaluate to?
boolean
What is the purpose of an if statement
Lets us choose what to do
Is else required in order to use an if statement?
no
Describe the syntax of if statement
if (conditional) {
code block
}
What are the three logical operators?
&& (and)
|| (or)
! (Logical not; inverts boolean)
How do you compare two different expressions in the same condition?
with logical operators (&& or ||)
What is the purpose of a loop?
When you want to repeat a chunk of code while certain conditions aren’t met
What is the purpose of a condition expression in a loop?
It makes it so loops have an exit point (not infinite loop)
What does “iteration” mean in the context of loops?
Each time the computer passes through the loop’s code block
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 everything (first thing that happens in a for loop)
When does the condition expression of a for loop get evaluated?
before each iteration
When does the final expression of a for loop get evaluated?
after each 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?
increments the variable by 1
How do you iterate through the keys of an object
with the for.. in loop
for key in object { }
What is the event.target?
The element that the user directly interacted with
What is the affect of setting an element to display: none?
It is taken out of the document flow
What does the element.matches( ) method take as an argument and what does it return?
element.matches(selector)
returns boolean
How can you retrieve the value of an element’s attribute?
element.getAttribute(attributeName)
At what steps of the solution would it be helpful to log things to the console?
Every 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?
Would have to add an event listener for each tab/view element.
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?
have to query each element and set their className manually
What is JSON?
JavaScript Object Notation
Takes an object/array/data and converts it into a string which can then be easily transmitted through network and later deserialized in order to access the data in its original state
What are serialization and deserialization?
serialization: take data and turn it into a stream of bytes which can be easily transferred
deserialization: take a stream of bytes and turn it into a data (allows us to use data)
Why are serialization and deserialization useful?
Can easily transfer data through network
Data is stored in memory locations so can’t easily transfer data from system to system.
How do you serialize a data structure into a JSON string using JavaScript?
using JSON.stringify(data)
How do you deserialize a JSON string into a data structure using JavaScript?
JSON.parse(JSON-string)
How do you store data in localStorage?
with storage.setItem(‘key’, ‘value’)
How do you retrieve data from localStorage?
storage.getItem(‘key’)
Returns value of key
What data type can localStorage save in the browser?
Strings
When does the ‘beforeunload’ event fire on the window object?
Right before the page is refreshed/closed
How can you tell the difference between a method definition and a method call?
method definition: inside an object, name is listed as a normal property, but the value being assigned to it is an anonymous function definition
method call: called as the property of an object, but with parentheses
Describe method definition syntax
defined inside an object as a normal property, but value assigned is an anonymous function definition
Describe method call syntax
similar to property of an object, but with parentheses containing any arguments
How is a method different from any other function?
They can only be called on an object which contains the method
What is the defining characteristic of Object-Oriented Programming?
It relies on the procedures and methods within an object to modify the properties and data within itself.
groups data and behavior (methods) together
What are the four “principles” of Object-Oriented Programming?
Abstraction
Encapsulation
Inheritance
Polymorphism
What is “abstraction”?
simplifying a complex thing
What does API stand for?
Application Programming Interface
What is the purpose of an API?
Used as tools that do specific things which simplify the process
What is “this” in JavaScript?
an implicit parameter whose value is determined by whenever the function is called
What does it mean to say that “this” is an implicit parameter?
It is available in a function’s code block as a parameter despite not being explicitly given
When is the value of “this” determined in a function?
whenever the function is called
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); } };
Nothing at the moment
Given the above character object, what is the result of the following code snippet? Why?
character.greet();
“It’s-a-me, Mario!”
this refers to the character object and it will get the firstName property of the character object
Given the above character object, what is the result of the following code snippet? Why?
var hello = character.greet; hello();
“It’s-a-me, undefined!”
hello stores the character.greet method, but when it is called, ‘this’ refers to the window object as there is no dot to the left of hello. Since there is no firstName property of window, it is undefined.
How can you tell what the value of ‘this’ will be for a particular function or method definition?
It is unknown on function definition
How can you tell what the value of ‘this’ is for a particular function or method call?
this refers to whatever object or function calls it
What kind of inheritance does the JavaScript programming language use?
prototype-based
What is a prototype in JavaScript?
an object that contains the methods which we can use through inheritance
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 acquire their methods through the prototype object via inheritance
If an object does not have it’s own property or method by a given key, where does JavaScript look for it?
in the prototype object
What does the new operator do?
lets developers create an instance of a user-defined object type or one of the built-in types that has a constructor function
1) Creates a blank, plain JS Object
2) Adds __proto__ property that points to constructor function’s prototype object
3) all references to ‘this’ refer to the newly created object
4) returns this if function doesn’t return an object
What property of JavaScript functions can store shared behavior for instances created with new?
an object’s prototype property
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.
object instanceof constructor
AKA was this object created by this constructor function
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?
setTimeout( )
setInterval( )
How can you set up a function to be called repeatedly without using a loop?
setInterval( )
What is the default time delay if you omit the delay parameter from setTimeout( ) or setInterval( )?
default time delay is 0
What do setTimeout( ) and setInterval( ) return?
a positive integer ID which identifies the setTimeout( ) or setInterval( ) call
What is AJAX?
Asynchronous JavaScript and XML
Tools for making network requests in code.
Allows us to update parts of the page without having to refresh the entire page.
What does AJAX acronym stand for?
Asynchronous JavaScript and XML
Which object is built into the browser for making HTTP requests in JavaScript?
XMLHttpRequest object
Which 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?
They are both event target objects so they both get the method through inheritance
What is a code block? What are some examples of a code block?
chunks of code within curly braces
if, for, function, while, etc
What does block scope mean?
data within a block can only be accessed within the same block
What is the scope of a variable declared with const or let?
block-scope
What is the difference between let and const?
let is mutable, const is immutable
const requires a value to be assigned to it during initialization
Why is it possible to .push( ) a new value into a const variable that points to an array?
The const variable just holds a reference to the array so you are able to change the array itself, but not assign a new array to the variable
How should you decide on which type of declaration to use?
var: if it needs to be global
let: if can be defined within a block and needs to be mutable
const: defined within a block and needs to be immutable
Try to use const, unless you can’t
What is the syntax for writing a template literal?
text surrounded by backticks
variables to be substituted are ${variable_name} within the backticks
What is “string interpolation”?
ability to substitute parts of a string with values of variables or expressions
What is destructuring, conceptually?
Taking the values/properties of an array/object and assigning them to variables in a shorthand expression
What is the syntax for object destructuring?
const/let { property: alias,… } = objectName;
alias is optional, if not included, property name will be the variable name
can also set default values with assignment
What is the syntax for Array destructuring?
const/let [ varName1, varName2,… ] = arrayName
can also set default values
How can you tell the difference between destructuring and creating Object/Array literals?
destructuring will have the object or array literal syntax on the left side of the assignment operator
What is the syntax for defining an arrow function?
(parameters) => expression
(parameters) => {statement}
When an arrow function’s body is left without curly braces, what changes in its functionality?
It will automatically return the expression
How is the value of this determined within an arrow function?
arrow function captures the this value of the enclosing context (parent blocks) instead of creating its own this context
DEFINITION TIME
What is the JavaScript Event loop?
Its purpose is to take processes in the task queue and place them into the stack only if the stack is clear.
What is different between “blocking” and “non-blocking” with respect to how code is executed?
blocking code: code that occupies the stack (synchronous)
non-blocking: taken out of the stack and placed into the task queue (asynchronous)
What are the three states a Promise can be in?
pending,
fulfilled,
rejected
How do you handle the fulfillment of a Promise?
then( )
How do you handle the rejection of a Promise?
catch( )
.then( ) but with 2 arguments (fulfilled, rejected) callback functions
What is Array.prototype.filter( ) useful for?
Taking an array and getting a new array with only the elements that satisfy the given condition
What is Array.prototype.map( ) useful for?
Take a given array and create a new one containing all the elements from the previous array with a transformation applied to it
What is Array.prototype.reduce( ) useful for?
Collapse/combine a bunch of data into one
What is “syntactic sugar”?
syntax within a programming language that is designed to make things easier to read or express.
What is the typeof an ES6 class?
function
Describe ES6 class syntax
class ClassName { constructor(params) { this.whatever = params }
methods }
What is “refactoring”?
restructuring existing code (usually in order to make it easier to read, improve efficiency, reduce complexity) without changing the behavior
How are ES modules different from CommonJS modules?
CommonJS: require( )
module.exports = …;
Part of Node
ES Modules: import { } from ‘path’
attach export keyword to anything you want to export
Official JS
What kind of modules can Webpack support?
CommonJS, ES Modules, AMD modules, Assets, WebAssembly modules
What does fetch( ) return?
A promise resolving to the response received from the server
What is the default request method used by fetch( )?
GET
How do you specify the request method (GET, POST, etc) when calling fetch?
By providing an optional object containing the method property as the second argument
What must the return value of myFunction be if the following expression is possible?
myFunction( )( );
another function
What does this code do?
const wrap = value => ( ) => value;
if you call wrap(value) it will return a function that if called on will return value.
What allows JavaScript functions to “remember” values from their surroundings?
closures;
In JS, functions remember their lexical environment