JavaScript Flashcards
What is the purpose of variables?
Gives us a way to call data later
How do you declare a variable?
var varName;
How do you initialize (assign a value to) a variable?
Set the variable equal to the desired value var varName = value;
What characters are allowed in variable names?
Any number, letter, _ , or $
But they must start with a letter, underscore (_), or $
What does it mean to say that variable names are “case sensitive”?
You must capitalize the variable’s spelling the same, in order to use it
var weTall is not the same as var wetall
What is the purpose of a string?
Stings are the form of data that allow you to enter a chain of text.
What is the purpose of a number?
Numbers are used for calculations and placement
What is the purpose of a boolean?
Booleans are true and false
They are used to decide whether an action should be taken or not
What does the = operator mean in JavaScript?
It assigns a value to a variable
The assignment operator
How do you update the value of a variable?
Set it equal to a different value, lower in the code var name = 'old name'; name = 'new name';
What is the difference between null and undefined?
Null means the items do not exist yet. Its data type is an object which was defined by a developer intentionally.
Undefined means the variable has not been given a value yet. Its data type undefined.
Why is it a good habit to include “labels” when you log values to the browser console?
You can know, in the console, what you are logging and make sure you are referring to the correct data.
Give five examples of JavaScript primitives.
Numbers String Boolean Null undefined
What data type is returned by an arithmetic operation?
numbers
arithmetic: involving numbers (numeric)
What is string concatenation?
Adding two or more strings to make one new, larger string
‘Sting’ + ‘ adding’ = ‘Strings adding’
What purpose(s) does the + plus operator serve in JavaScript?
Adding numbers together
Concatenating strings
What data type is returned by comparing two values (, ===, etc)?
Booleans
True or false
What does the += “plus-equals” operator do?
+=: addition assignment operator
Adds the item on the right, to the item on the left. THEN it replaced the item on the left with the new value
What are objects used for?
Give us a way to collect our data into smaller groups
What are object properties?
The items within an object. Keys & their values
Describe object literal notation.
var varName = {
property: value,
property: value
}
How do you remove a property from an object?
delete object.property;
What are the two ways to get or update the value of a property?
Dot notation: object.property = x
Bracket notation: object[‘property’] = x
What are arrays used for?
To make a series of data you can tie to a specific number
When you dont know how many pieces of that data you need
Groups of data that have the same type of data
Describe array literal notation.
var varName = [‘item’, ‘item’, ‘item’]
How are arrays different from “plain” objects?
The values are assigned to counted indexes, as opposed to random, unordered properties
What number represents the first index of an array?
0
Arrays start on 0 and count up
What is the length property of an array?
arrayName.length gives the total number of an array
How do you calculate the last index of an array?
Since the array indexing starts at 0, to get the last value in your array, you can subtract 1 from the array.length
var endItem = arrayName.length -1;
What is a function in JavaScript?
A faster way to access a chain of commands we need to use once or several times, throughout our program
Describe the parts of a function definition.
function sayHello(name) { var $fullGreeting = "Hello, " + name; return $fullGreeting; } var fullGreeting = sayHello("John"); console.log(fullGreeting); -------------------------------------------------- "Hello, John"
Describe the parts of a function call.
function: function keyword
functionName
(paramaters, parameters)
{….code….}: code block
When comparing them side-by-side, what are the differences between a function call and a function definition?
Definition: This would be to console the function without () at the end. The result would be the full view of the function.
Calling the function would be to run it and expect a result. This is done by adding () at the end of the function’s name.
What is the difference between a parameter and an argument?
Parameters go into the structure of the function. They act as placeholders for the data users will be inputting
Arguments are the actual data users input which, will be used in our function accordingly.
Why are function parameters useful?
Parameters are the placeholders for functions.
They will be replaced in the code block with the data users provide.
What two effects does a return statement have on the behavior of a function?
It sends the desired variable out of the scope of the function, which can then be used by another variable: function greet (name) { var greeting = "Hello, " + name; return myName; } var sayHi = greet('john'); console.log(sayHi);
It ends the code block from running any lines below it.
Why do we log things to the console?
We log things to the console to make sure the value of an object is as intended.
What is a method?
A method is a function stored as a property inside of an object.
How is a method different from any other function?
A method is a function saved onto an object
We call them by naming the object, adding a DOT, and then the name of the method
sting.method();
How do you remove the last element from an array?
array.push()
How do you round a number down to the nearest integer?
Math.floor()
How do you generate a random number?
Math.random();
The number is a decimal between 0 and 1
How do you delete an element from an array?
.pop() remove last item
.shift() removed first
.splice(startIndex, # to delete, items to insert)
How do you append an element to an array?
.push() add to last
.unshift() add to first
.splice(startIndex, # to delete, items to insert)
How do you break a string up into an array?
array.split(‘separate indicator’);
If you want to separate each word, the separate indicator would be (“ “)
Each letter (“”)
Do string methods change the original string? How would you check if you weren’t sure?
No, they make copies you can assign to new variables
Roughly how many string methods are there according to the MDN Web docs?
There are lots!
Around 40 or so
Is the return value of a function or method useful in every situation?
Sometimes, but not always needed
Roughly how many array methods are there according to the MDN Web docs?
There are lots!
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.
=== < > !== <= >=
What data type do comparison expressions evaluate to?
Booleans, true or false
What is the purpose of an if statement?
To make decisions
Is else required in order to use an if statement?
No. The default would just be for the code to do nothing.
Describe the syntax (structure) of an if statement.
if (operand comparison-operator operand) { Code to run if test === true } else { Code to run if test != true }
What are the three logical operators?
&& and
|| or
! not
How do you compare two different expressions in the same condition?
Logical AND (&&) or logical OR (||)
What is the purpose of a loop?
Loops allow us to repeat the behavior in a code with a stopping point.
What is the purpose of a condition expression in a loop?
The condition needs to be true for the loop’s code to run again
What does “iteration” mean in the context of loops?
One passthrough of the code
When does the condition expression of a while loop get evaluated?
Before each iteration/passthrough
When does the initialization expression of a for loop get evaluated?
Once, at the very beginning.
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 of the code block
Besides a return statement, which exits its entire function block, which keyword exits a loop before its condition expression evaluates to false?
break;
What does the ++ increment operator do?
i++ adds one additional amount to the value of i
How do you iterate through the keys of an object?
For…in loops
var person = {name: "Dave", age: 26}; ----------------------------------------------- function keysInObject(person) { var placeHolder = []; for (var properties in person) { placeHolder.push(properties); } return placeHolder; } ----------------------------------------------- keysInObject(person); ["name", "age"]
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? What would it do to an unchecked checkbox?
even.preventDefault();
It stops an event from doing the actions of an object by default
When you click on the unchecked checkbox, a check would not appear
What does submitting a form without event.preventDefault() do?
It sends the values of the form up into the url of the page
What property of a form element object contains all of the form’s controls.
formVar.element
What property of form a control object gets and sets its value?
formVar.element.name.value
What is one risk of writing a lot of code without checking to see if it works so far?
Without constant checks to your code, step by step, you won’t know where the issue arises from.
What is an advantage of having your console open when writing a JavaScript program?
You can constantly see the changes you are making to your code and test the functionality.
What is the event.target?
The literal thing that was used by the user to trigger the event
What is the affect of setting an element to display: none?
The element doesn’t not appear on the web page
What does the element.matches() method take as an argument and what does it return?
It takes a CSS selector, as a string
It returns a boolean for weather or not the element you are comparing contains the same item
event.target.matches(“.tab”)
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?
Any time the value of an item may be defined or changed
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?
I’d need to an a separate event listener for the specific new tab, which would make me copy all the code over again.
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?
I would have one IF condition for each tab, to make sure the value of the tab matched the event.target.
What is JSON?
JavaScript Object Notation (JSON)
A standardized text-based format for representing structured data, but in a form that can be sent over the internet
It’s based on JavaScript object syntax
What are serialization and deserialization?
Serialization: (JSON.stringify(object);) The process of converting your JavaScript object into a string of bites for transferring data to another place.
Deserialization: (JSON.pase(JSONstring);) The process of converting the string of bites back into an object for JavaScript.
Why are serialization and deserialization useful?
They allow us to date data structures and convert them into something we can send into a place, like something in our network to into memory.
How do you serialize a data structure into a JSON string using JavaScript?
var object = [ { name: 'Bob' , age: 35 }, { name: 'Phil' , age: 40 } ] JSON.stringify(object);
How do you deserialize a JSON string into a data structure using JavaScript?
var JSONstring = '[{"name":"Bob","age":35},{"name": "Phil","age":40}]' JSON.parce(JSONstring);
How to you store data in localStorage?
localStorage.setItem(‘keyName’, objectJSON);
How to you retrieve data from localStorage?
var objectJSON = localStorage.getItem(‘keyName’);
What data type can localStorage save in the browser?
The key of the an object, and the value, as a JSON string
When does the ‘beforeunload’ event fire on the window object?
It fires right before a web page closes.
How can you tell the difference between a method definition and a method call?
The return of a method definition will describe the content of said method.
The return of the method call will be the result produced by the method and its commands.
Describe method definition syntax (structure).
var calculator = { sum: function (x, y) { return x + y; }, multiply: function (x, y) { return x * y; } }
Describe method call syntax (structure).
calculator.sum(5, 9);
How is a method different from any other function?
Methods are called as part of an object which contains them.
What is the defining characteristic of Object-Oriented Programming?
We use objects which contain data and code, together.
What are the four “principles” of Object-Oriented Programming?
1) Inheritance
2) Abstraction
3) Encapsulation
4) Polymorphism
What is “abstraction”?
The process of taking a complex task and simplifying it with the use of tools.
(Like turning on a light with a light switch)
What does API stand for?
Application Programming Interface
What is the purpose of an API?
It is the connection between two or more different “types” of things. Such as one software to another or software to hardware, etc
What is THIS in JavaScript?
A parameter for a function which is implicit (not exactly defined, but implied, based on from where the function containing this would be called.)
What does it mean to say that THIS is an “implicit parameter”?
It is not specifically defined. It is implied from where it is called.
Explicit parameters are something we clearly define.
Implicit parameters are determined by the location of the call.
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); } };
It is not being called yet, so this is not referring to anything yet.
Given the above character object, what is the result of the following code snippet? Why?
character. greet();
“It’s-a-me, Mario!”
this.firstName is referring to the firstName property value, in the “character” object
var hello = character.greet;
hello();
The greet method of the character object becomes the function definition for “hello”
Running hello(); will return with “It’s-a-me, undefined!” because the hello object does not contain anything names firstName.
How can you tell what the value of this will be for a particular function or method definition?
You can’t. On its definition, it is still not being used by something, therefore this is referring to nothing
How can you tell what the value of this is for a particular function or method call?
You can look to the left of the dot ( object.method )
If there is nothing to the left of the dot, this is referring to the global window object
What is a prototype in JavaScript?
A general version of an object that other objects can use
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?
Methods live on a prototype the data in the object uses
If an object does not have it’s own property or method by a given key, where does JavaScript look for it?
It’ll go thorough the object’s __proto__ object, to find the method
What does the new operator do?
It creates a new object which will contain the result of your constructor function’s code.
1) Created an object
2) Adds prototype object from the construction function
3) Binds THIS to the current, blank object
4) Runs constructor function
What property of JavaScript functions can store shared behavior for instances created with new?
.prototype
construtorFunction.prototype.behaviorName
What does the instanceOf operator do?
It checks to see if an object was created using a given constructor
object instanceof constructorFunction
What is a “callback” function?
A function being passed into another function as an argument.
greetFullName(fullName()) {
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?
We can use setTimeout(function, delayedMilliseconds)
How can you set up a function to be called repeatedly without using a loop?
var intervalID = setInterval(function, intervalInMilliseconds);
What is the default time delay if you omit the delay parameter from setTimeout() or setInterval()?
0 milliseconds
What do setTimeout() and setInterval() return?
They timeoutID is returned that counts the amount of times the interval has occurred, for a unique ID for each.
What is AJAX?
A technology which allows us to load data into part of our page, without having to refresh our page.
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
So when we want to make a new call, we use var xyz = new XMLHttpRequest()
What event is fired by XMLHttpRequest objects when they are finished loading the data from the server?
Load
We can add an event listener on our new XMLHttpRequest object for ‘load’.
Bonus Question: An XMLHttpRequest object has an addEventListener() method just like DOM elements. How is it possible that they both share this functionality?
They share the same EventTarget prototype