Implement program flow (25%) Flashcards

1
Q

What does the == operator do?

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What does the === operator do?

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the two ways to create arrays?

A
var cars = ["Saab", "Volvo", "BMW"];
var cars = new Array("Saab", "Volvo", "BMW");
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Why should you avoid using the new keyword to create arrays?

A
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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What kind of indexing do arrays support?

A

numeric

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How do you create an array that supports string indexing?

A

use an object instead

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you resize an array?

A

var anArray = new Array(5);
alert(anArray.length);
anArray[9] = ‘soccer’; // anArray is dynamically resized
alert(anArray.length);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What does the indexOf method of arrays do?

A

Returns the first index at which a given element can be found in the array, or -1 if it is not present.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What does the join method of arrays do?

A

Joins all elements of an array into a string.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What does the lastIndexOf method of arrays do?

A

Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What does the pop method of arrays do?

A

Removes the last element from an array and returns that element.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What does the push method of arrays do?

A

Adds one or more elements to the end of an array and returns the new length of the array.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What does the reverse method of arrays do?

A

Reverses the order of the elements of an array in place — the first becomes the last, and the last becomes the first.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What does the shift method of arrays do?

A

Removes the first element from an array and returns that element.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What does the sort method of arrays do?

A

Sorts the elements of an array in place and returns the array.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What does the splice method of arrays do?

A

Adds and/or removes elements from an array.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What does the toString method of arrays do?

A

Returns a string representing the array and its elements.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What does the unshift method of arrays do?

A

Adds one or more elements to the front of an array and returns the new length of the array.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What does the valueOf method of arrays do?

A

Returns the array as a comma separated string.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What does the concat method of arrays do?

A

Returns a new array comprised of this array joined with other array(s) and/or value(s).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What does the slice method of arrays do?

A

Extracts a section of an array and returns a new array.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Which methods of arrays return new arrays?

A

concat, slice, sort, splice

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How do you create a multi-dimensional array?

A
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';
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What are the parameters for the slice method of the Array object?

A

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’.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
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'.
26
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();
27
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();
28
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.
29
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; } ```
30
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; } ```
31
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); } ```
32
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; } ```
33
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); } ```
34
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; } ```
35
In which direction does the reduce method of the Array object process its elements?
ascending
36
In which direction does the reduceRight method of the Array object process its elements?
descending
37
What is the syntax of the for loop?
for (var i = 0; i
38
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 }
39
What is the for..in loop used for?
Iterating over an object's properties.
40
What is the syntax of the while loop?
``` var i = 0; while (i ```
41
Which looping construct always runs at least once?
do..while ``` var canvas = document.getElementById("canvas1"); do { //stop traffic }while(canvas.styles.backgroundColor == 'red') ```
42
What is the syntax of the do..while loop?
``` var canvas = document.getElementById("canvas1"); do { //stop traffic }while(canvas.styles.backgroundColor == 'red') ```
43
What are the three ways to hook up an event handler?
1. Declare it directly in the HTML markup. 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.
44
What are the two types of functions which can be used as event handlers in JavaScript?
named and anonymous
45
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.
46
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.
47
In which order are events fired?
In the order they are added.
48
How do you remove an anonymous function as an event listener?
You can't unless you previously saved a reference to it.
49
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; } ```
50
In an event handler, what does the keyword 'this' represent?
The element that generated the event.
51
What event is fired when the value associated with an element changes?
change
52
What are the four events that are fired when an element receives and loses focus?
focusin, focus, focusout, blur
53
What event is fired when an element receives focus?
focus
54
What event is fired when an element loses focus?
blur
55
What event is fired just before an element receives focus?
focusin
56
What event is fired just before an element loses focus?
focusout
57
What event is commonly used to validate form fields?
blur
58
What method is called to set focus on any element that can receive focus?
focus
59
What are the three events raised in when the keyboard is used?
keydown, keypress, and keyup
60
What event is raised when a key is pushed down?
keydown
61
What event is raised when a key is released?
keyup
62
What event is raised when a key is completely pressed?
keypress
63
Which four properties of the Event object are available for keyboard events?
altKey, keyCode, ctrlKey, shiftKey
64
Which property of the Event object indicates whether the Alt key was pressed?
altKey
65
Which property of the Event object indicates the numeric code for the key that was pressed?
keyCode
66
Which property of the Event object indicates whether the Control key was pressed?
ctrlKey
67
Which property of the Event object indicates whether the Shift key was pressed?
shiftKey
68
Which keys only fire the keydown event?
arrow keys
69
Which events are raised when using the mouse?
click, dblclick, mousedown, mouseup, mouseenter, mouseover, mouseleave, mousemove
70
Which event is raised when the mouse performs a click?
click
71
Which event is raised when the mouse performs a double-click?
dblclick
72
Which event is raised when the mouse button is pressed down?
mousedown
73
Which event is raised when the mouse button is released?
mouseup
74
Which event is raised when the mouse cursor enters the space of an HTML element?
mouseenter or mouseover
75
Which event is raised when the mouse cursor leaves the space of an HTML element?
mouseleave
76
Which event is raised when the mouse cursor moves over an HTML element?
mousemove
77
Which six properties of the Event object are available for mouse events?
clientX, clientY, offsetX, offsetY, screenX, screenY
78
Which property of the Event object returns the x or horizontal position of the mouse cursor relative to the viewport boundaries ?
clientX
79
Which property of the Event object returns the y or vertical position of the mouse cursor relative to the viewport boundaries?
clientY
80
Which property of the Event object returns the x or horizontal position of the mouse cursor relative to the target element?
offsetX
81
Which property of the Event object returns the y or vertical position of the mouse cursor relative to the target element?
offsetY
82
Which property of the Event object returns the x or horizontal position of the mouse cursor relative to the upper-left corner of the screen?
screenX
83
Which property of the Event object returns the y or vertical position of the mouse cursor relative to the upper-left corner of the screen?
screenY
84
Which events are raised during drag-and-drop operations?
drag, dragend, dragenter, dragleave, dragover, dragstart, drop
85
Which event is raised continuously while the element is being dragged?
drag
86
Which event is raised on the element being dragged when the mouse is released to end the drop operation?
dragend
87
Which event is raised on a target element when a dragged element is dragged into its space?
dragenter
88
Which event is raised on a target element when a dragged element leaves its space?
dragleave
89
Which event is raised continuously on the target element while the dragged element is being dragged over it?
dragover
90
Which event is raised on the element being dragged when the drag operation is beginning?
dragstart
91
Which event is raised on the target element when the dragged element is released?
drop
92
In which drag-and-drop event do you set data to be transferred and used in the subsequent drop event during the same operation?
dragstart ``` var chip = document.getElementById("chip"); chip.addEventListener("dragstart", function () { window.event.dataTransfer.setData("Text", this.id); }); ```
93
How do you obtain the data transferred in the drop event of a drag-and-drop operation?
event.dataTransder.getData("Text"); b1.addEventListener("drop", function () { window.event.returnValue = false; var data = event.dataTransfer.getData("Text"); var d = document.getElementById(data); d.classList.remove("begin"); d.classList.add("dropped"); this.appendChild(d); });
94
In which drag-and-drop events should you provide visual feedback to the user?
dragevent and dragleave ``` var b1 = document.getElementById("bucket1"); b1.addEventListener("dragenter", function () { b1.classList.add("over"); window.event.returnValue = false; }); b1.addEventListener("dragleave", function () { b1.classList.remove("over"); }); ```
95
What must you do for elements that don't support drag-and-drop functionality by default?
You must cancel the event by setting event.returnValue to false.
96
How do you create a custom event?
``` myEvent = new CustomEvent( "customEventName", { detail: { description: "a description of the event", timeofevent: new Date(), eventcode: 2 }, bubbles: true, cancelable: true } ); ```
97
How do you handle a custom event?
object.addEventListener("customEventName", customEventHandler); ---------------------------------------------------------------- myEvent = new CustomEvent( "customEventName", { detail: { description: "a description of the event", timeofevent: new Date(), eventcode: 2 }, bubbles: true, cancelable: true } );
98
How do you raise a custom event?
object.dispatchEvent(myEvent); ---------------------------------------------------------------- myEvent = new CustomEvent( "customEventName", { detail: { description: "a description of the event", timeofevent: new Date(), eventcode: 2 }, bubbles: true, cancelable: true } );
99
Which browser does not support custom events?
Internet Explorer
100
What is the syntax of a try..catch..finally block?
try { } catch(e) { } finally { }
101
What properties are available on the exception object?
message, number, name
102
Which property on the exception object returns a textual description of the error that occurred?
message
103
Which property on the exception object returns a numeric error code?
number
104
Which property on the exception object returns the name of the exception object?
name
105
Which object and method are used to write messages to the console window?
console.log
106
What is the syntax to throw an exception?
throw new Error("error message");
107
Which API provides bidirectional communication support to your web applications?
WebSocket API
108
What types of data can be sent and received using the WebSocket API?
binary and text
109
Why should WebSocket API be used when possible rather than using HTTP?
Allows a connection directly to the server over a socket. Is a much lighter weight connection than HTTP. Is fully bidirectional.
110
What is required for a full-implementation of the WebSocket API?
A proper server-side implementation that can accept socket connections.
111
What applications are ideally served by WebSocket API?
messenger/chat apps, server-based games, WebRTC (Web Real-Time Communication) video conferencing
112
What is the syntax to create a web socket?
``` var wsConnection = new WebSocket('ws://studygroup.70480.com', ['soap', 'xmpp']); ```
113
What are the parameters required to create a WebSocket object?
1. The URL of the server-side socket to connect to, which is always prefixed with ws or wss for secure WebSocket connections 2. An optional list of subprotocols
114
Study this example use of WebSocket.
``` var wsUri = "ws://echo.websocket.org/"; var output; ``` ``` function init() { output = document.getElementById("output"); testWebSocket(); } ``` ``` function testWebSocket() { websocket = new WebSocket(wsUri); ``` websocket.onopen = function (evt) { writeToScreen("CONNECTED"); ``` writeToScreen("SENT: " + message); websocket.send(message); }; websocket.onclose = function (evt) { writeToScreen("DISCONNECTED"); }; websocket.onmessage = function (evt) { writeToScreen(evt.data); websocket.close(); }; websocket.onerror = function (evt) { writeToScreen(evt.data); }; } ```
115
What four events are raised by the WebSocket object?
open, close, message, error
116
What are the four possible values for the readyState property of the WebSocket object?
WebSocket.OPEN, WebSocket.CONNECTING, WebSocket.CLOSING, WebSocket.CLOSED
117
Study this example of using the jQuery AJAX method.
``` $.ajax({ url: searchPath, cache: false, // if true, a cached copy can be used dataType: "xml", // must be xml or json type: "GET", // or "POST" success: function (data) { // do stuff }, error: function(xhr, errorStatusNumber, errorThrown) { // do stuff } }); ```
118
What feature allows the creation of multi-threaded JavaScript applications?
web workers
119
What is required to use a web worker?
A separate JS file containing the script that will be processed on the separate thread.
120
What is the syntax to create a web worker?
var webWorker = new Worker("workercode.js");
121
What method of the Worker object starts the worker process?
postMessage
122
What parameters are required to call the postMessage method of the Worker object?
a single parameter containing the data to pass to the worker thread. webWorker.postMessage("some data");
123
What should be passed to the postMessage method of the Worker object if there is no data to pass?
an empty string ("") webWorker.postMessage("");
124
What method of the Worker object stops the worker process?
terminate
125
What event of the worker process is raised when the worker process is complete?
message var webWorker = new Worker("workercode.js"); ``` webWorker.onmessage = function(evt) { // Do stuff with results } ```
126
What event of the worker process is raised when an error occurs in the worker process?
error
127
What are the available properties of the event object passed to the function handing the error event of the Worker object?
message, filename, lineno
128
What is the required structure of a JS file when used in a web worker?
``` onmessage = function(e) { // This must be first in the file. // Do stuff self.postMessage(result); // Send result back to calling page } ```
129
What are the available properties of the event object passed to the function handling the message event of the Worker object?
data
130
What data types can be passed to the postMessage method of the Worker object?
strings, native data types, JSON, and XML. Functions cannot be passed. Native data types, JSON and XML are serialized when passed.
131
True or false. There is a limit to the number of web workers that can be created.
False. There is no limit on the number of workers, but creating workers is a heavy operation that involves creating threads at the operating system level. To use a high volume of workers, consider using a pool of workers that can be used in a round-robin fashion.
132
True or false. Web workers can modify the web page.
False. Web workers have no access to the DOM.
133
True or false. Web workers can create their own web workers.
True
134
How can you run a web worker after a delay or set interval?
use window.setTimeout and window.setInterval. ``` var work = new Worker("workerFile.js"); setTimeout(function(){ work.postMessage(""); },3000); // Runs after a 3-second delay. ``` ``` var work = new Worker("workerFile.js"); setInterval(function(){ work.postMessage(""); },3000); // Runs every 3 seconds. ```