Javascript Flashcards
What does = operator do in Javascript?
It is the assignment operator typically used for variables
Which keyword is used to declare a variable in Javascript?
var
Which characters is a Javascript variable allowed to begin with?
- Uppercase letters
- lowercase letters
- underscore
- dollar sign
- numbers (cannot use numbers in the beginning of the variable however)
What are quotation marks used for in Javascript?
Used for string variables
What is the purpose of strings in Javascript?
Storing and manipulating text
What is the purpose of booleans in Javascript?
To find out if an expression is true or false
What is the purpose of numbers in Javascript?
Sets up a basis of counting and quantifies any math related value
What does null mean in JavaScript?
Intentional absence in value
What data types can object properties hold?
They can basically hold any variable like strings, numbers, booleans, etc
Describe the syntax (structure) of object literals in JavaScript?
var variableName = { key: 'value1' key2: 'value2' ];
What is the principal use of arrays?
Organized lists for variables that can be called upon
Describe the syntax (structure) of array-literals in JavaScript
var variableName = [value1, value2, value3];
What number represents the first index of an array?
0
How can you access the last element of an array?
(Length property of an array) subtract by 1
What are the five parts of a function definition?
function name(parameters) { code } - The function keyword, the name for a function (optional), the parameters, the code block, and the return statement(optional) - Function names can have letters, digits, underscores, and dollar signs
How do you call a function?
- Using the function name with the parentheses and semicolon
Example: myFunction();
What is the difference between a parameter and an argument?
Parameter - listed inside the parentheses in a function. Behave as local variables
Argument - values received by the function when it is invoked
What does strictly equal mean?
=== It means that the values being compared are of the same value and data type
What is the logical <b>and</b> operator?
Both statements have to be true in order to result in true.
Can you name some comparison operators?
== equal to === equal value and equal type != not equal !== not equal or not equal type > greater than < less than >= greater than or equal to <= les than or equal to
When is the first expression in the parentheses for a for loop (known as the initialization) evaluated?
The first expression (initialization) is used once before the code block is executed.
Typically written as (let i = 0).
Sets up the loop
When is the second expression in the parentheses for a for loop (known as the condition) evaluated?
The second expression (condition) is used to define the condition for executing the code block.
This is typically written as (i < number). The number representing how many times the loop will occur.
Lets computer know when to stop looping.
When is the third expression in the parentheses for a for loop (known as the final expression) evaluated?
The third expression (the final expression) is used to change the value each time the code block in the loop has been executed.
Can be written as (i++)
Helps to get the loop closer to stopping.
What is the purpose of the condition in a for loop?
Dictates when the loop will stop running.
What is the purpose of the final expression in a for loop?
Gets the loop closer to stopping
What is DOM?
Document Object Model which is created when a web page is loaded.
Defines a standard for accessing documents
HTML DOM is a standard object tree model and programming interface for HTML.
Sets the standard for how to get, change, add, or delete HTML elements
What does document.querySelector() return?
Returns the first element within a document that matches a specified selector or group of selectors. If no matches then it returns null.
How do you modify the text of elements on the DOM?
var simplifiedElement = document.querySelector('id.idName'); simplifiedElement.textContent = 'insert text here';
What arguments does the addEventListener method make?
document.addEventListener(event, function, useCapture)
Event - required, the event name, do not use “on” as prefix
Function - required, the function to run when event occurs. When the event occurs the object is passed to the function as the first parameter.
useCapture - optional, a boolean. Specifies if the event should be executed in the capturing or bubbling phase
Give five examples of Javascript events that can be listened for
Mouse - events that relate to the computer mouse. Used to notify when mouse is clicked, doubleclicked, up/down events, right-click, movement in and out of an element, text selection, etc.
DOMContentLoaded - occurs on events related to events being loaded on the document
Animation - events related to Web Animation API. Used to respond to changes in animation (ex. when it starts/ends)
Composition - Events related to entering text “indirectly” (i.e. text entered via a speech to text engine or using special key combinations that modify keyboard presses to represent new characters in another language
Drag’n’drop, Wheel - Events derived from mouse events. While this is occurred when using the mouse wheel or drag/drop
What does document.createElement() take as its assignment?
It takes tagName or an HTMLUknownElement if tagName isn’t recognized.
For example (h1, div, etc)
What does document.createElement() return?
Returns the new element
How do you append elements to the DOM?
appendChild(aChild)
Example ($parent.appendChild($child)).
What is the purpose of variables?
To store values that can be used later
How do you initialize (assign a value to) a variable?
var varName = value
What does it mean to say that variable names are “case sensitive”?
Variables with different casing can have completely different values
What does = operator mean in JavaScript?
It means assignment as in it assigns a variable to a value
How do you update the value of a variable?
varName = new value
No need to declare value again using var because it has already been stored
What is the difference between null and undefined?
Null = it was intentionally left blank
Undefined = can be missing a value for any multiple of reasons
Why is it a good habit to include “labels’ when you log values to the browser console?
Provides clarity to other users and yourself in the future.
Give five examples of JavaScript data type primitives.
- number
- string
- boolean
- undefined
- null
What data type is returned by an arithmetic operation?
Number data type
What is string concatenation?
Combining string values together
Strings are immutable, cannot be changed
What purpose(s) does the + plus operator serve in JavaScript?
Adds or concatenates values together
What data type is returned by comparing two values (, ===, etc.)?
Boolean data type
What does the += “plus-equals” operator do?
Adds or concatenates a value on the right side to the left side
What are objects used for?
To group together a set of variables and functions
What are object properties?
Variables that are part of an object.
Individual keys that correlate to a value
Describe object literal notation?
Object literal notation contains curly braces ({ })
How do you remove a property from an object?
Using the delete operator and the object.property
Ex. delete object.property
What are two ways to get or update the value of property?
Using a . to call on the object property
Using [ ] to call on the object property
square bracket notation - contains a variable with values you actually want
dot notation - straight away that calls on an object’s property
What are arrays used for?
Stores a set of values/lists of data
Describe array literal notation.
[ ]
var arrayName = [value1, value2, value3];
How are arrays different from “plain” objects?
- They don’t need an individual key or value
- Arrays don’t have alpha-numeric indexes (only numeric)
- Arrays have a length property
What number represents the first index of an array?
[0]
What is the length property of an array?
Stores the value of the length of the array’s list via arrayName.length
How do you calculate the last index of an array?
arrayName - 1
Length is true count of value, the - 1 takes into account of indexing
What is the notation for calling an array in an object?
objectName.objectProperty.objectValue[#];
What is a function in JavaScript?
Sets up code that can be called upon any time in a program.
Describe the parts of a function definition.
- function keyword
- function name (optional)
- function parameters (optional)
- Code block {using curly braces}
- Return statement (optional)
Describe the parts of a function call.
- functionName
- (arguments, in, parentheses)
- Does not require arguments
When comparing them side-by-side, what are the differences between a function call and a function definition?
Function Definition - function is defined with parameters in the parentheses
Function Call - function is called with arguments in the parentheses
What is the difference between a parameter and an argument?
Parameters are used when defining a function, placeholder for values
Arguments are used when calling a function, values are known
Why are function parameters useful?
Function parameters are useful because it allows other people to pass arguments when the function is called
Allows for reusability instead of single use (no parameters means one result)
What two effects does a return statement have on the behavior of a function?
The return statement produces a value and exits the function (no code after this return within the code block will run
Why do we log things to the console?
To make sure that we get the proper output from our code
What is a method?
A function which is a property of an object
i.e. Math.max(numberValues );
How is a method different from any other function?
Functions are objects while methods reference an object to a function
How do you remove the last element from an array?
arrayName.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?
object.splice();
How do you append an element to an array?
object.push();
How do you break a string into an array?
object.split();
Do string methods change the original string? How would you check if you weren’t sure?
No, strings are immutable.
Use the console.log and check the original string to see if it changed
Roughly how many string methods are there according to the MDN Web docs?
There are a lot… like 40-50
What three-letter acronym should you always include in your Google search about a JavaScript method or CSS property?
MDN
Is the return value of a function or a method useful in every situation?
Not always necessary
Roughly how many array methods are there according to the MDN Web docs?
There are a lot.. like 40-50
How to learn via documentation?
- Read the blurb that provides a definition/summary of the term/method you’re looking at.
- Syntax
- Read parameters
- Ignore info that doesn’t pertain to what you’re looking for
- Return Value
- Read original sample code
Give 6 examples of comparison operators
>, < >= <= == === != !==
What data type do comparison expressions evaluate to?
Boolean
What is the purpose of an if statement?
Create a path of code dependent on the user’s input/data
This is done by checking a condition. If the condition is true then the code block is executed.
Is else required in order to use an if statement?
No you can use just the if statement
Describe the syntax (structure) of an if statement?
keyword if
condition (yourConditionHere)
Code Block { }
Code to execute if true (inside the code block)
What are the three logical operators?
&&
||
!
How do you compare two different expressions in the same condition?
Using a logical operator
What is the purpose of a loop?
To run a piece of code a repeated number of times so long as the condition in the loop is true.
Once the condition of the loop is false then the code stops.
What is the purpose of a condition expression in a loop?
Sets the code up to repeatedly run so long as the conditions remain true and will stop the loop when the condition is false
What does “iteration” mean in the context of loops?
Each time the loop repeats
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?
In the beginning, before the loop happens
The initialization expression sets up the loop by creating a counter
Initialization is written as: var i = 0;
When does the condition expression for a for loop get evaluated?
After initialization and before each loop iteration
When does the final expression of a for loop get evaluated?
At the end of each loop iteration (before the next evaluation of the condition)
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 its operand and returns a value that reassigns the initialization value
How do you iterate through the keys of an object?
Use a for in loop
Why do we log things to the console?
In order to check to see if our code is functional and what is occurring
What is a “model”?
A recreation of an existing concept. In this case a recreation of the web page.
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 datatype object
What is a DOM Tree?
A parent element with its child elements with its nodes.
Give two examples of document methods that retrieve a single element from the DOM.
querySelector( )
getElementById( )
Give one example of a document method that retrieves multiple elements from the DOM at once.
querySelectorAll( )
Why might you want to assign the return value of a DOM query to a variable?
So it just runs once, stores the value in the variable, and you can just pull the up the result from the variable
What console method allows you to inspect the properties of a DOM element object?
console.dir( )
Why would a script tag need to be placed at the bottom of the HTML content instead of at the top?
HTML elements are read from top to bottom.
The script is put at the end so things can populate before the script line is executed
What does document.querySelector() take as an argument and what does it return?
Argument of a string that contains a css selector and the return will be the first element that matches that selector
What does document.querySelectorAll() take as its argument and what does it return?
The argument is a string with the value of a CSS selector
It returns a node list which is a like an array object BUT ITS NOT AN ARRAY
What is DOM?
The Document Object Model
A Javascript object that is the model of the HTML document.
- It is not the HTML itself
What is the purpose of events and event handling?
When user interaction occurs this allows things like events and event handling to respond to certain instances
Are all possible parameters required to use a Javascript method or function?
No it depends on the method or function but usually only the event and function name is required.
What method of element objects lets you set up a function to be called when a specific type of event occurs?
addEventListener( );
What is a callback function?
A function that is called in another function as an argument. This is used to complete some kind of action.
What object is passed into an event listener callback when the event fires?
The object that has all the data for the event that just happened
What is the event.target? If you weren’t sure, how would you check? Where could you get more information about it?
Reads the object that was used in order for the event to occur. You could check this via console.log and you could get more info from MDN.
What is the difference between these two snippets of code?
element. addEventListener(‘click’, handleClick)
element. addEventListener(‘click’, handleClick())
The first one there is a function being named
The second one there’s a function with a return value
What is the syntax of an event listener?
element.addEventListener (‘event’, functionName, [Boolean] );
What is the className property of element objects?
It gets and sets the value of a class attribute of a specified element
How do you update the CSS class attribute of an element using JavaScript?
var $varName = document.querySelector(‘itemName’)
$varName.className = (‘updatedClassName’);
What is the textContent property of element objects?
Represents the text content of the node and its descendants.
How do you update the text within an element using JavaScript?
var $varName = document.querySelector(‘.className’)
$varName.textContent = ‘Text Content’;
Is the event parameter of an event listener callback always useful?
Not always.
The event parameter helps in understanding that it is an event handler function
Would this assignment be simpler or more complicated if we didn’t use a variable to keep track of the number of clicks?
It would be more complicated.
You would have to add more text content and turn certain text content into numbers.
Why is storing information about a program in variables better than only storing it in the DOM?
It’s easier for JavaScript to work with it
Allows for efficiency and easy to edit if issues arise
What event is fired when a user places their cursor in a form control?
‘focus’ event will occur
What event is fired when a user’s cursor leaves a form control?
‘blur’ event will occur
What event is fired as a user changes the value of a form control?
‘input’ event will occur
What event is fired when a user clicks the “submit” button within a form?
‘submit’ event will occur
What does the event.preventDefault() method do?
Prevents the default behavior of an event from occurring
What does submitting a form without event.preventDefault() do?
Submits the form and creates a new form
What property of a form control object gets and sets its value?
The value property
What is one risk of writing a lot of code without checking to see if it works so far?
Knowing where progress is and when code broke/contained error
What is an advantage of having your console open when writing a Javascript program?
Knowing when an error occurred and seeing when things are happening in real time
What property of a form element object contains all of the form controls.
Elements property on the form which contains individual properties
Does the document.createElement() method insert a new element into the page?
No it stores the element node in a variable
How do you add an element as a child to another element?
appendChild method
Which adds a child element to the parent element. It will be added as the last child.
What do you pass as the arguments to the element.setAttribute( ) method?
name = a DOMstring specifying the name of the attribute whose value is to be set
value = a DOMstring containing the value to assign to the attribute
What steps do you need to take in order to insert a new element into the page?
Create the element
Set the attributes to the element
Query the DOM for the target parent element
Append the child to the parent element
node.appendChild(aChild);
What is the textContent property of an element object for?
Used to read what the text content is but can also assign new text content as well
Name two ways to set the class attribute of a DOM element.
element. setAttribute( )
element. className( )
What are two advantages of defining a function to do create something (like the work of creating a DOM tree)?
Get to test out the code to make sure its functional
Get to reuse the function
What is the event.target?
Refers to an object that the event is being done on
Why is it possible to listen for events on one element that actually happen in its descendent elements?
Because the descendent elements are children of the one element that is being listened on due to the flow events from event bubbling (child to parent flow)
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 name of a selector in DOMString that can be a selector like elementName, className, etc.
How can you remove an element from the DOM?
elementName.remove( )
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?
Put the event listener on the parent element that will contain these new elements
What is the affect of setting an element to display: none?
The content and any of it’s children’s content wouldn’t be shown
What does the element.matches( ) method take as an argument and what does it return?
It takes the selectorString which is a string representing the selector that will be tested
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?
After any piece of code that can alter the webpage
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?
createElement( )
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?
display: none
What is JSON?
JavaScript Object Notation is a standard text-based format for representing structured data based on JavaScript object syntax.
What are serialization and deserialization?
Serialization = turning an object that’s stored into a bytes to store it in a desk or send over the network
Deserialization = turning bytes into an object in storage
Why are serialization and deserialization useful?
Serialization/Deserialization is important because it stores and transfers objects through a standardized process
How do you serialize a data structure into a JSON string using JavaScript?
JSON.stringify( )
How do you deserialize a JSON string using JavaScript?
JSON.parse( )
How do you deserialize a JSON string into a data structure using JavaScript?
var dataStructure = JSON.parse(jsonString);
How do you store data in localStorage?
localStorage.(‘key’, ‘value’);
How do you retrieve data from localStorage?
localStorage.getItem(‘value’);
What data type can localStorage save in the browser?
Strings
When does the ‘beforeunload’ event fire on the window object?
Allows a web page to trigger a confirmation dialog asking the user if they really want to leave the page
What is a method?
A function that is a property of an object
Example:
objectName.methodName(argumentName)
How can you tell the difference between a method and a method call?
Method = Has a code block that defines the method, has the function keyword, has parameters, function will be assigned to a property
Method call = is a property of the object and contains arguments
Describe method definition syntax (structure).
Declare the Object methods will work with: var objectName = { methodName: function ( ) { return valueName; } };
Describe method call syntax (structure)
objectName.methodName(arguments)
How is a method different from any other function?
Functions are objects while methods reference an object from the function
What is the defining characteristic of Object-Oriented Programming?
Objects can contain both data (as properties) and behavior (as methods).
What are four “principles” of Object-Oriented Programming?
Abstraction
Encapsulation
Inheritance
Polymorphism
What is “abstraction”?
Being able to work with complex things in simple ways.
What does API stand for?
Application Programming Interface
What is the purpose of an API?
Give programmers a way to interact with a system in a simple, consistent fashion
What is this in Javascript?
- An implicit parameter of all Javascript functions
- Its value is determined when it is called
- Value of this is determined as the object left of the dot when the function is called (as a method)
- If no value to left of the dot when function is called then it is by default the global window object
- If you cannot see the function being called, then you do not know what the value of this will be
What does it mean to say that this is an “implicit parameter”?
A parameter that is available in a function code block even though it was never in the function 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); } };
There is no this value
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();
It’s-a-me, Mario!
Because there is an object being assigned to character and since character object is to the left of the greet method which contains ‘this’ then it will use character as the object for this.firstName
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?
var hello = character.greet; hello();
Undefined
hello is a free floating variable. Since its being called without a stated object then the default object is window. Because window has no firstName property then there’s nothing to return
How can you tell what value of this will be for a particular function or method definition?
You don’t. Because there’s no object so there’s no method being called
How can you tell what the value of this is for a particular function or method call?
Value of this is whatever object is to the left of the method call.
What kind of inheritance does JavaScript programming language use?
Prototype-based inheritance which is used to move properties and methods to the prototype object so other objects can use prototype object to perform tasks
What is a prototype in JavaScript?
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?
Set these methods in a prototype variable and then put the object as a parameter when calling the method
If an object does not have its own property or method by a given key, where does JavaScript look for it?
In its respective prototype object
What is the syntax to set a prototype to an object?
Object.setPrototypeOf(objectName, prototype)
objectName = object that will have its prototype set
prototype = the object’s new prototype (object or null)
The return will be the specified object
How would you write a prototype method?
var prototypeName = { propertyName: function ( ) { } };
Object.setPrototypeOf(objectName, prototypeName);
What does the new operator do?
Allows user to create a user-defined object type or a built-in object type that has a constructor function
- Creates a blank JavaScript object
- Adds a property to the new object’s prototype that links to the constructor function’s prototype object
- When this is used it will reference to the new operator’s object
- Returns this if object is non-existent
What property of JavaScript functions can store shared behavior for instances created with new?
prototype property
What does the instanceof operator do?
Checks if there’s a prototype property in an object
What is the syntax of the new operator?
new constructor[ ( [arguments] ) ]
constructor = class or function that specifies the type of object
arguments = a list of values the constructor will be called with
What is the syntax of using an instanceof operator?
object instanceof constructor
object = the object to test constructor = function to test again
What does an instanceof operator return?
A boolean value
What does the new operator return?
An object or this if an object isn’t returned
What is the syntax for a constructor function in regards to creating an object?
function objectName(parameter 1, 2, 3) { this.parameter1 = parameter1; this.parameter2 = parameter2; this.parameter3= parameter3; }
What is a “callback” function?
A function that is used in 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?
setTimeout( )
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( )?
Value of 0 meaning execute the code immediately or the next event cycle
What do setTimeout( ) and setInterval( ) return?
timeoutID which is a positive integer
What is the syntax of setTimeout( )?
setTimeout (function[delay, arg1, arg2, …] )
function = function to be used when timer expires
delay = time in milliseconds that the function is to be executed
arg1, arg2… = additional arguments for the function being executed
What is the syntax of setInterval( )?
var intervalID = setInterval (function, delay , arguments)
function = function to be executed
delay = time in milliseconds interval occurs
arguments = list of arguments to pass through the function
What is the syntax of clearInterval( )?
clearInterval ( intervalID )
intervalID = identifier of the setInterval that is supposed to be cleared
What is a client?
A software uses a service or resource from a server
What is a server?
A software provides a service or resource to a client
Which HTTP method does a browser issue to a web server when you visit a URL?
GET
What three things are on the start-line of an HTTP request message?
- An HTTP method
- The request target
- The HTTP version
What three things are on the start-line of an HTTP response message?
- The protocol version
- The status code
- Status text
What are HTTP headers?
They let the client and server pass additional info with an HTTP request or response
Gives additional info (similar to head element in html)
Where would you go if you wanted to learn more about a specific HTTP Header?
MDN
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers
Is a body required for a valid HTTP request or response message?
No because some HTTP methods don’t need one
What is AJAX?
Web application allows the request of data without having to reload the whole page
What does AJAX acronym stand for?
Asynchronous JavaScript And XML
Which object is built in 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’
An XMLHttpRequest object has an addEventListener( ) method just like DOM elements. How is it possible that they both share this functionality?
Prototype inheritance
What is the JavaScript Event Loop?
One of the four major concepts in JavaScript.
The event loop takes the first item from callback queue and sends it to the JavaScript callback stack. Once the process is finished the event loop pushes the next callback item to the callback stack.
What is different between “blocking” and “non-blocking” with respect to how code is executed?
Blocking: code takes effect immediately when the block is being processed
Non-blocking: code takes effect at the end of the block being processed.
What are the four major concepts of JavaScript?
Prototypal Inheritance
How this works
Closures
Event Loop
What must the return value of myFunction be if the following expression is possible?
myFunction( ) ( );
A function
The return of myFunction is being called
What does this code do?
const wrap = value => { ( ) => { value; } }
Value of wrap is a function definition
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
What is a closure?
A closure is a combination of a function and the lexical environment within which the function was declared