JavaScript Flashcards
What is the purpose of variables?
The purpose of variables is to store value.
Why does this help? Variables can change & it exists for a longer time.(data permanence)
How do you declare a variable?
You declare a variable by using the var keyword and giving the variable a name.
How do you initialize (assign a value to) a variable?
You initialize (assign a value to) a variable with the = operator.
What characters are allowed in variable names?
Letters, numbers, dollar sign($), and underscore(_).
Note: dash(-) or period( . ) or question-mark(?) are not allowed & Numbers cannot go first.
What does it mean to say that variable names are “case sensitive”?
When it is said that variable names are “case sensitive” it means that capitalization matters.
Ex: String and string are not the same.
What is the purpose of a string?
The purpose of a string is to store text.
What is the purpose of a number?
The purpose of a number is to use it for math and calculations.
What is the purpose of a boolean?
The purpose of a boolean is to store if something is true or false. Booleans exist for decision making.
What does the = operator mean in JavaScript?
The = operator in JavaScript means that we are assigning a value to something.
How do you update the value of a variable?
You update the value of a variable by assigning a new value to the variable.
Note: You don’t need the var keyword to assign a new value to an existing variable.
What is the difference between null and undefined?
Null: Primitive value that represents a reference that points, generally intentionally, to a nonexistent or invalid object or address. Null always need to be assigned to something.
Undefined: Primitive value automatically assigned to variables that have only been declared. Also assigned to formal arguments where there are no actual arguments.
What data-type is returned by an arithmetic operation?
A Number value is returned by an arithmetic operation.
What is string concatenation?
String concatenation is adding two or more strings to make a longer string.
What purpose(s) does the + plus operator serve in JavaScript?
The + plus operator adds numbers and concatenates strings in JavaScript.
What data type is returned by comparing two values (< , >, ===, etc)?
A Boolean value is returned by comparing two values (< , >, ===, etc).
What does the += “plus-equals” operator do?
A value on the right-side will be added to the variable, and the variable will then be updated to that new value.
What are objects used for?
Objects are used to group together a set of properties and methods to create a model of something.
What are object properties?
Object properties are variables glued to that object.
Describe object literal notation.
var hotel = { name: 'Cosmopolitan', rooms: 500, booked: 300, checkAvailability: function( ) { return this.rooms - this.booked; } };
How do you remove a property from an object?
Removing a property from an object using the dot notation:
delete objectname.propertyname.
Removing a property from an object using the bracket notation:
delete objectname[‘propertyname’].
What are the two ways to get or update the value of a property?
Updating/getting a property from an object using the dot notation: variablename.propertyname.
Updating/getting a property from an object using the bracket notation: variablename[‘propertyname’].
What are arrays used for?
Arrays are used to store a list of data with number indexes.
Describe array literal notation.
colors = [‘white’, ‘blue’, ‘red’]
How are arrays different from “plain” objects?
Arrays have orders to them unlike “plain” objects. Arrays will repair itself if a data is deleted.
What number represents the first index of an array?
0 represents the first index of an array.
What is the length property of an array?
The length property of an array tells us the number of data stored in an array.
How do you calculate the last index of an array?
We calculate the last index of an array by:
arrayname.length - 1
What is a function in JavaScript?
A function in JavaScript is giving a name to some amount of code so that it can be reused and also read easier.
Describe the parts of a function definition.
function functionName (parameters) { return }
Describe the parts of a function call.
functionName (arguments)
Note: Arguments don’t have to be there.
When comparing them side-by-side, what are the differences between a function call and a function definition?
function definition - name of data get passed as parameters.
function call - actual values get passed as arguments.
Why are function parameters useful?
It functions as a placeholder.
Why are function parameters useful?
Parameters are useful because they function as placeholders.
Adds reusability and adaptability.
What two effects does a return statement have on the behavior of a function?
- Causes the function to return 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?
We log things to the console for debugging purposes.
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?
A function becomes a method once it is passed in as a property for an object. Method has to say where it is coming from.
How do you remove the last element from an array?
You can remove the last element from an array by using the pop( ) method.
How do you round a number down to the nearest integer?
You can round a number down to the nearest integer by using the Math.floor( ) method.
How do you generate a random number?
You can generate a random number in a range by:
Ex: Math.floor(Math.random( ) * 10);
How do you delete an element from an array?
You can delete an element from an array by using the: pop( ) method, shift( ) method, and/or splice( ) method.
How do you append an element to an array?
You can add an element to an array by using the: push( ) method, unshift( ) method, and or splice( ).
How do you break a string up into an array?
You can break a string up into an array by using the split( ) method.
Do string methods change the original string? How would you check if you weren’t sure?
No. You can check by using console.log ( ).
Roughly how many string methods are there according to the MDN Web docs?
A lot. Learn it when you need it.
Is the return value of a function or method useful in every situation?
No.
The push ( ), unshift ( ), pop( ), shift( ), and splice( ) are good examples for when you are solely just trying to manipulate the array.
Roughly how many array methods are there according to the MDN Web docs?
A lot. Learn it when you need it.
Give 6 examples of comparison operators.
==, !=, ===, !==, < , <= , >, and >=
What data type do comparison expressions evaluate to?
Comparison expressions evaluate to Booleans.
What is the purpose of an if statement?
The purpose of an if statement is for decision making.
Is else required in order to use an if statement?
No.
Describe the syntax (structure) of an if statement.
if ( condition ) {
}
What are the three logical operators?
&&, | |, and !.
How do you compare two different expressions in the same condition?
You compare two different expressions in the same condition by using logical && or logical | | operator.
What is the purpose of a loop?
The purpose of a loop is to offer a quick and easy way to do something repeatedly.
What is the purpose of a condition expression in a loop?
The purpose of a condition expression in a loop is to test if the loop-code-block should be executed or not. (To keep going or not)
What does “iteration” mean in the context of loops?
“Iteration” in the context of loops means a cycle of the loop.
When does the condition expression of a while loop get evaluated?
The condition expression of a while loop gets evaluated in the beginning.
When does the initialization expression of a for loop get evaluated?
The initialization expression of a for loop gets evaluated in the beginning.
(initialization = before anything)
When does the condition expression of a for loop get evaluated?
The condition expression of a for loop gets evaluated before each iteration.
(condition = before each iteration)
When does the final expression of a for loop get evaluated?
The final expression of for loop gets evaluated after the loop-code-block was executed.
(final expression = 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?
The “break” keyword.
What does the ++ increment operator do?
The ++ increment operators increments by 1.
How do you iterate through the keys of an object?
You can iterate through the keys of an object by using the for…in loop.
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 ?
submit
What does the event.preventDefault( method do?
Prevents the page from doing what it usually does.
What does submitting a form without event.preventDefault( ) do?
Sends the data of key value pair to URL. (Query String) The data gets sent back to the current page.
What property of a form element object contains all of the form’s controls.
elements
What property of form a control object gets and sets its value?
value
What is one risk of writing a lot of code without checking to see if it works so far?
Harder to debug.
What is an advantage of having your console open when writing a JavaScript program?
Easier to debug.
What is the event.target?
It is the dom object of the element where the event was fired.
What is the affect of setting an element to display: none?
It hides the content.
What does the element.matches( ) method take as an argument and what does it return?
It takes a CSS selector as an argument and returns a boolean.
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?
Almost at 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?
We would need event listeners for 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?
We need to check through each element individually.
What is JSON?
JSON is a text-based data format following JavaScript object syntax.
JSON exists as a string — useful when you want to transmit data across a network. It needs to be converted to a native JavaScript object when you want to access the data.
What are serialization and deserialization?
Serialization: a process of converting an Object into stream of bytes so that it can be transferred over a network or stored in a persistent storage.
Deserialization: a process of fetching a stream of bytes from a network or persistence storage and convert it back to the Object with 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 do you store data in localStorage?
localStorage.setItem(‘key’, ‘value’ )
How do 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?
Before the window unloads.
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?
Method definition is a function that is a value of object:
Ex: Property: function ( )
Method call is property of object:
Ex: Object.method( )
Describe method definition syntax (structure).
Ex:
var calculator = { add: function (x, y) { return x + y; },
Describe method call syntax (structure).
object.method( )
How is a method different from any other function?
Methods are functions attached to objects.
What is the defining characteristic of Object-Oriented Programming?
Objects can contain both data (as properties) and behavior (as methods).
What is “abstraction”?
Being able to work with (possibly) complex things in simple ways.
Example: Automatic Car Transmission
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: aka, an abstraction.
What is ‘this’ in JavaScript?
‘this’ is an implicit parameter of all JavaScript functions.
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); } };
‘this’ refers to the object ‘character’.
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); } };
Since the method is not being used, ‘this’ does not have anything inside.
Given the below character object:
var character = { firstName: 'Mario', greet: function () { var message = 'It\'s-a-me, ' + this.firstName + '!'; console.log(message); } };
What is the result of the following code snippet? Why?
character.greet();
The result will be ‘It’s a me, Mario!”
Because the value of the parameter greet is ‘It's-a-me, ‘ + this.firstName + ‘!’;.
Given the below character object:
var character = { firstName: 'Mario', greet: function () { var message = 'It\'s-a-me, ' + this.firstName + '!'; console.log(message); } };
What is the result of the following code snippet? Why?
var hello = character.greet; hello();
The result will be ‘It’s a me, undefined!”
Because the greet method hasn’t been called.
The value of ‘this’ is still window.
The window object does not have a property firstName.
How can you tell what the value of this will be for a particular function or method definition?
You can’t. If you cannot see the function being called, then you do not know what the value of ‘this’ will be.
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).
When is the value of ‘this’ determined in a function; call time or definition time?
call time
What kind of inheritance does the JavaScript programming language use?
JavaScript includes a specific kind of inheritance known as prototype-based (or prototypal) inheritance. JavaScript objects give certain behaviors (methods) or data (properties) to other objects.
Prototypal inheritance in JavaScript is a fairly simple concept (especially compared to ‘this’). The ultimate goal is to move properties and methods that we’d like to reuse into a “prototype” object and then tell other objects to simply delegate (verb) to that “prototype” object when they aren’t able to perform the required tasks themselves.
What is a prototype in JavaScript?
JavaScript prototype is simply an 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?
The methods exist in their prototype object.
If an object does not have its own property or method by a given key, where does JavaScript look for it?
In the __proto__ object.
What does the new operator do?
- Creates a blank, plain JavaScript object.
- Adds a property to the new object (__proto__) that links to the constructor function’s prototype object.
Note: Properties/objects added to the construction function prototype are therefore accessible to all instances created from the constructor function (using new).
- 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?
.prototype
Example:
Student.prototype.getFullName = function () { var fullName = this.firstName + ' ' + this.lastName; return fullName; };
What does the instanceof operator do?
Checks if an instance is an instance of a specific object or not.
Returns a boolean.
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?
using setTimeout( )
How can you set up a function to be called repeatedly without using a loop?
using setInterval( )
What is the default time delay if you omit the delay parameter from setTimeout() or setInterval()?
0
What do setTimeout() and setInterval() return?
It returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval().
interval ID is an integer.
What is AJAX?
AJAX is a technique for loading data into part of a page without having to refresh the entire page.
Use 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
Bonus Question: An XMLHttpRequest object has an addEventListener() method just like DOM elements. How is it possible that they both share this functionality?
It is in the prototype.
Both branching off of the same prototype.
What is a code block? What are some examples of a code block?
Code in-between { } to be executed together that are statements.
Examples of a code block are function code blocks, conditional code blocks, loop code blocks.
What does block scope mean?
In ES6, const and let keywords allow developers to declare variables in the block scope, which means those variables exist only within the corresponding block.
What is the scope of a variable declared with const or let?
block scope
What is the difference between let and const?
You can’t reassign values declared in const.
Why is it possible to .push() a new value into a const variable that points to an Array?
Can’t reassign but we can manipulate the value.
How should you decide on which type of declaration to use?
If the value is going to be reassigned, use let.
If not, use const.
Use const everywhere unless you can’t.
What is the syntax for writing a template literal?
${variable}
What is “string interpolation”?
The ability to substitute part of the string for the values of variables or expressions.
What is destructuring, conceptually?
Destructuring broadly means extracting data from arrays or objects. Using destructuring, we can break a complex array or object into smaller parts. Destructuring also offers us the ability to extract multiple data at once from an object or array. It also provides the ability to set a default value of the property if it’s already not set.
What is the syntax for Object destructuring?
var obj {
}
const/let {keyName: variableName} = obj
or
const/let {keyName/varibleName} = obj
if the the key name and variable name are the same.
What is the syntax for Array destructuring?
var array [
]
const/let [arrayValue] = array
if only grabbing first value of array and putting it into a variable.
or
const/let {index:variableName} if using object destructuring.
How can you tell the difference between destructuring and creating Object/Array literals?
The { } and [ ] followed with the name of the object/array after the =.
Creating: const/let array = [ ]
Destructuring:
const/let [arrayValue] = arrayName
What is the syntax for defining an arrow function?
const greet = (who) => { return `Hello, ${who}!`; }
When an arrow function’s body is left without curly braces, what changes in its functionality?
It has an implicit return but the statement must be in one-line. (The right side of the arrow is the expression)
How is the value of ‘this’ determined within an arrow function?
In regular functions the ‘this’ keyword represented the object that called the function, which could be the window, the document, a button or whatever. ‘this’ is determined at function call.
With arrow functions the this keyword always represents the object that defined the arrow function. ‘this’ is determined at function definition. Go up one level and search for ‘this’.
What is Array.prototype.filter useful for?
To make a new array from specific elements of an existing array.
What is Array.prototype.map useful for?
To make a new array after the elements have been altered.
What is Array.prototype.reduce useful for?
Take all elements of an array and combine them somehow.
What is “syntactic sugar”?
syntax within a programming language that is designed to make things easier to read or to express. It makes the language “sweeter” for human use: things can be expressed more clearly, more concisely, or in an alternative style that some may prefer.
What is the “typeof” an ES6 class?
function
Describe ES6 class syntax.
class Person { constructor(name) { this.name = name; } getName( ) { return this.name; } }
What does fetch() return?
a promise. The promise is for a response at all.
What is the default request method used by fetch()?
GET
How do you specify the request method (GET, POST, etc.) when calling fetch?
Pass the method as the second argument.
What must the return value of myFunction be if the following expression is possible?
myFunction( )( );
Must be a function.
Second () is calling the return of myFunction.
What does this code do?
const wrap = value => ( ) => value;
It is assigning an anonymous function with a single parameter “value” to the const variable wrap. And in the code-block, another anonymous function is defined with the parameter value.
The code assigns the value of the parameter to const variable wrap.
In JavaScript, when is a function’s scope determined; when it is called or when it is defined?
When it is defined.
What allows JavaScript functions to “remember” values from their surroundings?
closures / lexical environment