Implement program flow (25%) Flashcards
What does the == operator do?
Evaluates whether the values are equal independent of the underlying data type.
var n = 2000, s = '2000'; alert(n == s); // True alert(n === s); // False, since the data types don't match
What does the === operator do?
Evaluates whether the values are equal both in value and underlying data type.
var n = 2000, s = '2000'; alert(n == s); // True alert(n === s); // False, since the data types don't match
What are the two ways to create arrays?
var cars = ["Saab", "Volvo", "BMW"]; var cars = new Array("Saab", "Volvo", "BMW");
Why should you avoid using the new keyword to create arrays?
Avoid using the new keyword to create arrays var numbers = new Array(40, 300); // creates array with 2 element var numbers = new Array(40); // creates array with 40 undefined elements
What kind of indexing do arrays support?
numeric
How do you create an array that supports string indexing?
use an object instead
How do you resize an array?
var anArray = new Array(5);
alert(anArray.length);
anArray[9] = ‘soccer’; // anArray is dynamically resized
alert(anArray.length);
What does the indexOf method of arrays do?
Returns the first index at which a given element can be found in the array, or -1 if it is not present.
What does the join method of arrays do?
Joins all elements of an array into a string.
What does the lastIndexOf method of arrays do?
Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.
What does the pop method of arrays do?
Removes the last element from an array and returns that element.
What does the push method of arrays do?
Adds one or more elements to the end of an array and returns the new length of the array.
What does the reverse method of arrays do?
Reverses the order of the elements of an array in place — the first becomes the last, and the last becomes the first.
What does the shift method of arrays do?
Removes the first element from an array and returns that element.
What does the sort method of arrays do?
Sorts the elements of an array in place and returns the array.
What does the splice method of arrays do?
Adds and/or removes elements from an array.
What does the toString method of arrays do?
Returns a string representing the array and its elements.
What does the unshift method of arrays do?
Adds one or more elements to the front of an array and returns the new length of the array.
What does the valueOf method of arrays do?
Returns the array as a comma separated string.
What does the concat method of arrays do?
Returns a new array comprised of this array joined with other array(s) and/or value(s).
What does the slice method of arrays do?
Extracts a section of an array and returns a new array.
Which methods of arrays return new arrays?
concat, slice, sort, splice
How do you create a multi-dimensional array?
var multiArray = new Array(3); multiArray[0] = new Array(3); multiArray[1] = new Array(3); multiArray[2] = new Array(3); multiArray[1][2] = 'ball sport';
What are the parameters for the slice method of the Array object?
startIndex, endIndex
var sports = new Array('soccer', 'basketball', 'hockey', 'football', 'cricket', 'rugby', 'tennis', 'badminton'); var someSports = sports.slice(1, 2);
The slice method takes two parameters: the indexes where the slice operation should begin and end. The ending index isn’t included in the slice. All copied elements are returned as an array from the slice method. In this example, because ‘basketball’ is at index 1 and the ending index is specified at index 2, the resulting array someSports contains only one element ‘basketball’.
What are the parameters for the splice method of the Array object?
startIndex, length, optional items to add to the array
var sports = new Array('soccer', 'basketball', 'hockey', 'football', 'cricket', 'rugby', 'tennis', 'badminton'); var splicedItems = sports.splice(1, 3, 'golf', 'curling', 'darts');
The splice method returns an array containing the items that are spliced out of the source that are spliced out of the source array. The first parameter is the index in the array where the splice operation should start. The second parameter is the number of items to splice, starting from the index specified in the first parameter. The optional last parameter lists items that are to replace the items being spliced out. The list doesn’t have to be the same length as the items being spliced out. In fact, if the last parameter is omitted, the spliced items are simply removed from the array and not replaced. In this example, three items are replaced, starting at index 1. So, ‘basketball’, ‘hockey’, and ‘football’ are replaced with ‘golf’, ‘curling’ and ‘darts’.
Which methods of the Array object are used to provide stack functionality?
pop and push
var sports = new Array();
sports.push(‘soccer’, ‘basketball’, ‘hockey’);
sports.push(‘football’);
var nextSport = sports.pop();
Which methods of the Array object are used to provide queue functionality?
push and shift
Array.prototype.enqueue = function(item)
{
this.push(item);
};
Array.prototype.dequeue = function()
{
return this.shift();
};
var queue = new Array();
queue. enqueue(1);
queue. enqueue(2);
queue. enqueue(3);
queue. enqueue(4);
var next = queue.dequeue();
Which methods of the Array object operate only on the beginning of the array?
shift and unshift
var sports = new Array();
sports.unshift(‘soccer’, ‘basketball’, ‘hockey’);
sports.unshift(‘football’);
var nextSport = sports.shift();
The shift and unshift methods work in the exact opposite way from the pop and push methods. The shift method removes and returns the first element of the array, whereas the unshift method inserts new elements at the beginning of the array.
Which method of the Array object tests whether ALL elements in the array pass the test implemented by the provided function?
every
var evenNumbers = new Array(0, 2, 4, 6, 8, 9, 10, 12); var allEven = evenNumbers.every(evenNumberCheck, this);
// allEven is false since 9 is not even if (allEven) { ... } else { ... }
function evenNumberCheck(value, index, array) { return (value % 2) == 0; }
Which method of the Array object tests whether ANY elements in the array pass the test implemented by the provided function?
some
var evenNumbers = new Array(0, 2, 4, 6, 8, 9, 10, 12); var someEven = evenNumbers.some(evenNumberCheck, this);
// someEven is true even though 9 is not even if (someEven) { ... } else { ... }
function evenNumberCheck(value, index, array) { return (value % 2) == 0; }
Which method of the Array object enables an application to process some logic against each item in the array?
forEach
This method runs for every single item and doesn’t produce a return value.
var sportsArray = [‘soccer’, ‘basketball’, ‘hockey’, ‘football’,
‘cricket’, ‘rugby’];
sportsArray.forEach(offerSport);
function offerSport(value, index, array) { var sportsList = document.getElementById("sportsList"); var bullet = document.createElement("li"); bullet.innerText = value; sportsList.appendChild(bullet); }
Which method of the Array object provides a way to remove items for an array based on some processing done in the callback function.?
filter
The filter method returns a new array containing the elements that are included based on a return value of true or false from the callback function.
var evenNumbers = new Array(0, 2, 4, 6, 8, 9, 10, 12); var allEven = evenNumbers.filter(evenNumberCheck, evenNumbers);
function evenNumberCheck(value, index, array) { return (value % 2) == 0; }
Which method of the Array object provides a way to replace values in the array?
map
Every element in the array is passed to a callback function. The callback function’s return value replaces the value for the position in the array that was passed in. The following example demonstrates having every number in an array rounded off appropriately:
var money = [12.8, 15.9, 21.7, 35.2]; var roundedMoney = money.map(roundOff, money);
function roundOff(value, position, array) { return Math.round(value); }
Which methods of the Array object are recursive?
reduce and reduceRight
Each result of the callback function is passed back into the callback method as the previous return value along with the current element to be passed in. This provides some interesting scenarios. The reduce method processes the elements of the array in ascending order, whereas the reduceRight processes the elements of the array in descending order. The following example demonstrates using the reduce method to calculate a factorial:
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; var factorials = numbers.reduce(factorial);
function factorial(previous, current) { return previous * current; }
In which direction does the reduce method of the Array object process its elements?
ascending
In which direction does the reduceRight method of the Array object process its elements?
descending
What is the syntax of the for loop?
for (var i = 0; i
What is the syntax of the for..in loop?
var person = { firstName: "Jane", lastName: "Doe", birthDate: "Jan 5, 1925", gender: "female" };
for (var prop in person) {
document.write(prop); // Writes property name
document.write(person[prop]); // Writes property value
}
What is the for..in loop used for?
Iterating over an object’s properties.
What is the syntax of the while loop?
var i = 0; while (i
Which looping construct always runs at least once?
do..while
var canvas = document.getElementById("canvas1"); do { //stop traffic }while(canvas.styles.backgroundColor == 'red')
What is the syntax of the do..while loop?
var canvas = document.getElementById("canvas1"); do { //stop traffic }while(canvas.styles.backgroundColor == 'red')
What are the three ways to hook up an event handler?
- Declare it directly in the HTML markup.
<body>
2. Assign the function to the event property of the element object through JavaScript.
window. onload = onloadHandler();
~~~
function onloadHandler() {
alert("hello event.");
}
~~~
~~~
// or use an anonymous function
window.onload = function() {
alert("hello event.");
};
~~~
3. Use the newer add and remove methods on the element object to associate event handlers.
object. addEventListener("eventName", function, useCapture);
object. removeEventListener("eventName", function, useCapture);
If useCapture is true, events are dispatched to parent objects before child objects.
If useCapture is false, events are dispatched to target objects first and then to parent objects.
</body>
What are the two types of functions which can be used as event handlers in JavaScript?
named and anonymous
How do you get a reference to the event object in an event handler?
var event = window.event;
In some browsers, the event is passed as a parameter to the handling function.
What are the parameters of the addEventListener and removeEventListener methods?
eventName, function, useCapture
If useCapture is true, events are dispatched to parent objects before child objects.
If useCapture is false, events are dispatched to target objects first and then to parent objects.
In which order are events fired?
In the order they are added.
How do you remove an anonymous function as an event listener?
You can’t unless you previously saved a reference to it.
How do you cancel an event?
return false or set window.event.returnValue to false
window.onload = function () { var a = document.getElementById("aLink"); a.onclick = OverrideAnchorClick; }
function OverrideAnchorClick() { //do custom logic for the anchor window.event.returnValue = false; //or return false; }
In an event handler, what does the keyword ‘this’ represent?
The element that generated the event.
What event is fired when the value associated with an element changes?
change
What are the four events that are fired when an element receives and loses focus?
focusin, focus, focusout, blur
What event is fired when an element receives focus?
focus