Javascript Flashcards

1
Q

How many types of number does Javascript have?

A

A single number type (represented by a 64bit float internally)

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

Is NaN equal to NaN?

A

No - it is equal to nothing else, therefore the only way to test for it is to use the function isNaN(number)

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

In Javascript, is ‘C’ + ‘a’ + ‘t’ === “Cat”?

A

Yes

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

Do strings have methods?

A

Yes - think of things like String1.toUppercase();

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

In Javascript do blocks create new scope?

A

No - so variables should be declared at the top of a function

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

What values typically evaluate to false?

A

false, null, undefined, ‘’, 0, NaN

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

What does the string ‘false’ evaluate to in Javascript

A

True

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

What is the ‘for in’ structure in Javascript?

A

A for loop.

for (var myvar in obj) {
 // Loop through
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is a label in a break statement?

A

You can break to another location (labelled by label). i.e.

break myLabel;

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

What are the simple types in JavaScript?

A

numbers, strings, booleans, null and undefined

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

Are numbers, strings and booleans objects?

A

No - but they do have methods

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

Objects in JavaScript are…

A

Mutable keyed collections

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

Do you need to have a class in JavaScript to create an object?

A

No, objects in JavaScript are class free.

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

What is an object literal?

A

A pair of curly braces surrounding zero or more name/value pairs. i.e.

var empty_object = { };

var stooge = {
“first-name”: “jerome”,
“last-name”: “Howard”
};

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

What names must be enclosed in quotes in an object literal?

A

Names that don’t conform to normal variable naming conventions.

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

How do retrieve a variable from an object literal?

A

Using the [ ] operator

myObj[“name”]

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

How can you fill in a “default” value when assigning a value from an object literal?

A

var val = obj[“first-name”] || “(none)”;

(i.e. it will either provide the first-name element of the object or “(none)”

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

What happens when you try to retrieve values from “undefined”?

A

Throws a TypeError exception.

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

How do you prevent JavaScript throwing an exception when you accidentally try to access an element of an object that is undefined?

A

Use the && operator

flight.equipment // undefined
flight.equipment.model // throw “TypeError”
flight.equipment && flight.equipment.model // undefined
(I guess it fails on the left hand operand like other languages and doesn’t execute the right hand operand)

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

Objects in Javascript are passed by…

A

reference

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

What does setting “defer” on a script tag do?

A

It indicates to the browser that the script can start downloading immediately, but it wont’ be run until the page is loaded. It should only be used when using external

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

How would you specify the defer attribute in XHTML?

A

defer=”defer”

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

What is the async attribute used for?

A

To specify that a script can be run as soon as it is loaded (not wait for the page)

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

What is the potential issue with having multiple external scripts labeled as async?

A

They may run out of order, so there should be no dependancies between them.

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

What options are available to prevent code being interpreted as HTML when embedding javascript in XHTML?

A

Use the html codes for > or < signs (or they will be interpreted as tags) - or use < ! [CDATA [ block

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

What is quirksmode?

A

It was a mode that IE used in version 5.5 - turning it on made it behave like I.E. 5 (non-standard) and switching it to standards mode (5.5) made it behave in a more standards compliant way.

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

In ANY browser, how do you turn off quirksmode?

A

By adding a correct doctype. (i.e. HTML 4.01 strict, XHTML or HTML5)

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

In ANY browser, how do you enable “almost standards mode”?

A

By using the transitional and frameset doctypes

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

What is the only only element that can be included in the body tag, but not in the noscript tag?

A

script

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

How do you inform a user that they require a javascript enabled browser?

A
By using the noscript tag
< body>
  < noscript>
  < p>You require Javascript dude </>
  < /noscript>
< / body>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

The first letter of a Javascript identifier must be…

A

a letter, an underscore or a dollar sign

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

How do you enable strict mode in Javascript?

A

Place
“use strict”
at the top of the script

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

Is it possible to leave out the ‘;’ in a statement?

A

Yes - although not recommended.

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

Variables in javascript are ….. typed.

A

Loosely

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q
Is the following valid?
var message = "hi";
message = 100;
A

Yes - but not recommended (you are changing the type of the variable, which could be confusing)

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

What is the difference between using var and not using var to declare a variable?

A

Using var makes the variable local to the block. I.e.

function foo() {
  var message = "Hi";
}

message will be destroyed when execution leaves that function block.

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

Global variables (declared without using var) are not recommended - how do you detect their use in your code?

A

By setting “use strict” on the script, a ReferenceError will be thrown

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

How do you declare multiple variables in a single line?

A
var message = "hi",
      found = false,
      age = 29;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

If you have received the following the error - what happened?
Uncaught SyntaxError: Unexpected eval or arguments in strict mode

A

You declared a variable named eval or arguments in strict mode (which is not allowed).

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

What operator do you use to determine the type of a variable?

A

typeof varName;

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

What results does typeof return?

A
undefined
boolean
string
number
object
function
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

Functions are considered …… in ECMAscript?

A

objects (although they have some unique properties to themselves)

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

If a variable is declared using var and not assigned anything, what is it’s value?

A

undefined

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

Should you ever explicitly set the value of a variable to undefined?

A

No - setting them to null is fine - but not to undefined

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

How do you convert a variable to a boolean type?

A

Use the boolean casting function

Boolean(var);

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

What types are converted to true if passed to the Boolean function (and consequently an if statement)?

A

true
Any non-empty string
Any non-zero number including infinity (negative numbers too)
Any object

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

What types are converted to false if passed to the Boolean function (and consequently an if statement)?

A
false
(empty string)
0, NaN
null
undefined
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q
Is this a valid octal number?
var octalNum2 = 079;
A

No - there is a number 9 in there, which is out of range for a valid octal number - the 0 will be discarded and the number will be 79

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q
Is this a valid octal number?
var octalNum1 = 070;
A

Yes - the leading 0 is important to tell Javascript that this is an octal number (and the numbers are within range (0-7))

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

Numbers using octal or hex format are treated as ….. in all artithmetic operations?

A

decimal

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

There is only one numeric type in Javascript (number) how do you define a floating point number?

A
Just give it a decimal.
var floatNum = 1.1;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

ECMAScript always looks for ways to convert floats back to ints, why is that?

A

They take twice as much memory as an int.

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

How do you determine the smallest and largest numbers that can be represented in ECMAScript?

A

Number.MIN_VALUE;

Number.MAX_VALUE;

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

What does the following expression return?

NaN == NaN

A

False (NaN is not equal to ANYTHING)

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

How do you test if a number is NaN?

A

isNaN(variable);

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

What happens if you apply isNaN to an object?

A

The objects method “valueOf()” is called, if that doesn’t work, then it calls the “toString()” method

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

What are the three functions used to convert non-numeric values to numbers?

A

Number()
parseInt()
parseFloat()

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

What unary operator works the same way as the Number() function?

A

Unary +

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

What is wrong with the following statement - and how would you fix it?
parseInt(“070”);

A

The user may be intending 070 to be parsed as an octal number. However, it will be parsed as a string and give 70. To fix it pass parseInt the radix
parseInt(“070”, 8);

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

What is the difference between parseInt and parseFloat?

A

There is no radix mode as parseFloat only ever parses decimal values.

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

Are strings mutable or immutable in ECMAScript?

A

immutable

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

How do you convert a value to a string?

A

Most values have a .toString() method -
var age = 11;
age.toString();

Or add an empty string to it…
age + “”;

NOTE: When used on a number, you can pass it the radix of the value to convert to binary etc.

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

What does the hasOwnProperty method do on an object?

A

Checks to see if the method being queried exists on that object, and not part of a prototype

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

What are the base methods for an object in ECMAScript?

A
constructor
hasOwnProperty(propertyName)
isPrototypeOf(object0
propertyIsEnumerable(propertyName)
toLocaleString()
toString()
valueOf()

(All objects have these in ECMAScript)

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

What happens in this instance?
var stringNum = “1”;
++stringNum;

A

stringNum is converted to a string then incremented.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
66
Q
What happens in the following instance?
var stringNum = "1";
var num = +stringNum;
A

The value of stringNum is converted to a number and assigned to num.

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

Can the order that object properties appear in a “for-in” statement be predicted?

A

No, object properties are unordered in ECMA script

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

What is the ‘with’ statement?

A
A convenience statement, it basically negates the need to explictly call an object repeatedly in a given block of code
// NOTE: search, hostname and href 
// are properties of location
with(location) {
   var qs = search.substring(1);
   var hostname = hostname;
   var url = href;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
69
Q

When is using the with statement invalid and an error?

A

In strict mode, it is not allowed (NOTE: It also has a negative impact on performance, and makes debugging difficult) - not good in production code

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

What data types does switch work with in ECMA Script?

A

All data types, including expressions, i.e.

case num > 0 && num <= 10:

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

How do you access the arguments passed to a function?

A

ECMA Script has an ‘array’ like structure that can be accessed in the function called ‘arguments’. Use length to find out how many arguments.

arguments.length;

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

Is function overloading possible in ECMA Script?

A

No - if two functions have the same name, the final function is the one used.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
73
Q
What is wrong with the following code?
var name = "Steveybigs";
name.age = 27;
A

You can’t add properties to a primitive type (strings are primitives in Javascript) - Note, you wont get an error, but accessing name.age is undefined.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
74
Q
What is wrong with the following code?
var person = new Object();
person.name = "Bill chumpbucket";
A

Nothing - it is perfectly valid to add properties to an object (reference type) in Javascript.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
75
Q
var obj1 = new Object();
var obj2 = obj1;
obj1.name = "Dickhead";
alert(obj2.name);

What will be printed out

A

Dickhead. Because obj2 and obj1 now point to the same object, adding the property ‘name’ on either obj2 or obj1 results in it being accessable from either variable.

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

All function arguments are pass by…

A

value

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
77
Q
function setName(obj) {
  obj.name = "hershey";
  obj = new Object();
  obj.name = "Greg";
}
var person = new Object();
setName(person);
alert(person.name);

What will be printed?

A

“hershey”. Remember, variables, even objects are passed by value, not by reference.

You can of course change the properties of an object as if it were pass by reference, but that’s because what is passed is a COPY of the objects reference. Not the actual reference (so internals can be changed by reference, but you can’t change the actual object because it’s a copy, not the actual reference).

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

typeof can be used to determine what type a variable is - but why isn’t it useful for reference types?

A

Because it will simply tell you it’s an object. To determine specificaly what type of object, use instanceof.

alert(person instanceof MyObject);

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

What is the execution context?

A

It determines what other data a variable or function has access to, as well as how to behave.

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

In a browser, the global context is said to be…

A

the window object

(so all global variables and functions are created as properties and methods of the window object.

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

When a function is executing, it’s context is pushed onto…

A

the context stack

and it is popped when finished, returning the context to the previously executing context

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

What is a scope chain?

A

When code is executed in a context, a scope chain of variable objects is created. It always starts at the variable object of the context whose code is executing and works it’s way back to global scope. This is then used to resolve usage of variable names, starting at the closest scope and working its’ way back to global scope.

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

In c, the iterator variable in a for loop is local to the for loop - what about Javascript?

A

No - it’s available outside the for block, as Javascript does not have block level variable scope.

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

When a variable is declared, it is added to the most immediate context, in the case of a ‘with’ block - what is the most immediate context?

A

The containing functions local scope.

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

Why is it important to break the link between a native javascript variable and a DOM object when it is no longer used?

A

Because DOM objects use reference counting. Javascript uses mark and sweep. DOM objects with Javascript objects can lead to circular references.

Use null to sever the connection.

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

Is a reference type a class?

A

No - there are no classes in ECMAScript

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

Why are Object reference types so useful?

A

They can be quickly created and have properties added - useful for passing data around in a program quickly.

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

Define an object literal named ‘person’ with properties name and age.

A

var person = {
name : “Jizzbomb”,
age: 29
};

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

What is potentially different with the way you declare properties when using object literal notation?

A

You can use strings and numbers as the identifiers.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
90
Q
Write an object literal statement that is the same as:
var person = new Object();
A

var person = { }; // Not really recommended

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

What is unusual about constructor behavior when defining an object via object literal notation?

A

The constructor is never called.

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

How would you use an object literal to pass data to a function?

A
function displayInfo(args) { /* do stuff */ }
displayInfo({
     name: "Foobaz",
     age: 20
});
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
93
Q

What is the difference between
person[“name”] and
person.name

A

Nothing - they effectively do the same thing.

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

What is the advantage of using bracket notation when accessing properties in an object?

A

You can pass variables into the brackets.

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

What makes an array different in ECMAScript compared to other languages?

A

Each slot can hold it’s own data type

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

Write five different ways to create an array in ECMAScript?

A
var myArray = new Array();
var myArray = new Array(20); // Set the size
var myArray = new Array("Red", "yellow", "Green");
var myArray = Array("Greg"); // You can ommit the 'new'
var myArray = ["red", "blue", "Green"];
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
97
Q
Is this a valid way of creating an array?
var values = [1, 2, ];
A

Yes, but AVOID it, as it creates an array with 2 OR 3 elements (note the trailing comma) depending on browser. And the last item MAY be undefined.

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

What is similar about creating objects and arrays using the literal notation?

A

The constructors are not called for either.

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

var color = [“red”, “Yellow”, “Blue”];

How do you get the length of the array?

A

var len = color.length;

100
Q

Is it valid to set the length property of an array?

A
Yes, you can remove items by doing something like:
var colors = ["red", "Yellow", "Blue"];
colors.length = 2;
101
Q

What is wrong with this code?
var colors = [“Red”, “Blue”, “Yellow”];
colors.length = 2;
alert(colors[2]);

A

colors[2] refers to the third element which no longer exists thanks to the color.length = 2 statement;

102
Q

Write a statement that adds a new color to the end of an array called colors.

A

colors[color.length] = “Aubergine”;

103
Q

How do you determine if an Array is an Array?

A

Array.isArray(value);

Available in IE 9+, FF4+, S5+ O10.5+ and Chrome

104
Q

What is the difference between toString and valueOf when called on an Array?

A

Nothing - they both return comma-seperated string containing the values of the array.

105
Q

How could you simulate the output of Array.toString with the join method?

A

myArray.join(“,”);

106
Q

How could an Array be used to behave like a stack?

A

The Array object contains methods like push and pop which makes it behave like a LIFO object.

107
Q

What functions allow an Array object to behave like a Queue?

A

push and shift

108
Q

How would you sort a basic numeric array?

A

myNumArray.sort(compare); // Were compare is a user defined comparison function

109
Q

What is the issue with using just ‘sort’ with no user defined comparison function on a numeric array?

A

The numbers are sorted as strings, which means they will be out of numeric order.

110
Q

Write a simple, but fast compare function that works for numeric arrays?

A
function compare(num1, num2) {
  return num2 - num1;
}
111
Q

How could you use concat to add an array literal to an existing array?

A
var myColors = ["red", "green", "Blue"];
myColors = myColors.concat(["purple", "black"]);
112
Q

What does the slice method do on an array?

A
Using slice you can copy a section of an array
var myArray = [1, 2, 3, 4, 5];
myArray = myArray.slice(1); // 2, 3, 4, 5
myArray = myArray.slice(1, 2); // 2
myArray = myArray.slice(1, 3); // 2,3
With two values it returns the numbers between the first number and the last number, not including the last number. The numbers are the same as array indexes (i.e. start at 0)
113
Q

What is the splice method used for on an array?

A

It can be used to delete, insert and replace items in an array

114
Q

Remove the first item form the following array using splice

colors = [“red”, “gree”, “blue”];

A

var removed = colors.splice(0, 1); // Remove the first item

115
Q

Insert two items at position 1 using splice given the following array:
colors = [“red”, “gree”, “blue”];

A

var removed = colors.splice(1, 0, “yellow”, “orange”); // note, nothing is removed in this example

116
Q

Insert two values, but delete one using splice from the following array
colors = [“red”, “yellow”, “green”];

A

var removed = colors.splice(1, 1, “red”, “purple”);

117
Q

What functions can you use on an array to determine the lcoation of an item?

A

colors. indexOf(“red”);

colors. lastIndexOf(“red”);

118
Q

What does the “every” iterator do on an array?

A

It is run on every element of an array, and returns true if the function returns true on every item.

119
Q

What does the “some” iterator do on an array?

A

It is run on every element of the array and returns true if SOME of the elements of the array are evaluated as true.

120
Q

What does the “filter” iterator do on an array?

A
It is run on every element and returns an array of elements that meet the criteria of the given function
var numbers = [ 1, 2, 3, 4, 5, 6 ];
var filterResult = numbers.filter(function(item, index, array) {
   return item > 2;
});

alert(filterResult); // [3, 4, 5, 6]

121
Q

What does the “map” iterator do on an array?

A
It will run over every element in the array and perform an operation returning an array of the results
var numbers = [ 1, 2, 4, 5];
var result = numbers.map(function(item, index, array) {
   return item * 2;
});
alert(result); // [2, 4, 8, 10];
122
Q

What does the forEach() iterator do on an array?

A

Runs over every element in the array, running the provided function. But note: there is no return value, it’s essentially equivalent to a for loop.

numbers.forEach(item, index, array) {
   // Do stuff here.
});
123
Q

What are the reduction methods in ECMAScript?

A

They are Array methods that iterate over an array, and apply a function to each element. The goal is to eventually accumulate all the values and provide a single result.
There are two - reduce and reduceRight();

var value = [1, 2, 3, 4, 5];
var sum = values.reduce(function(prev,  cur, index, array) {
   return prev + cur;
}

alert(sum); // 15

124
Q

To convert a string representation of a date to milliseconds (since 1970), what function do you use?

A

Date.parse()

// Date format can either be
// m/d/y (6/13/2014)
// month_name date, year (January 12, 2004)
// day_of_week month_name date year hours:minutes:seconds time_zone
//YYYY-MM-DDTHH:mm:ss.sssZ
125
Q

If you pass nonsense into Date.parse(), what does it return?

A

NaN

126
Q

What is another way of using Date.parse() that reduces the amount of code required?

A

var someDate = new Date(“May 25, 2004”);

It calls Date.parse() in the constructor

127
Q

If I wanted to get the exact date as of now - what function would I use?

A

Date.now()

128
Q

In older versions of ECMAScript there is a difference between a regex literal and a RegExp object, what is it?

A

The regex literal only has one instance, so in a loop multiple calls to it would not create a new instance, and it search from the last place it left of. HOWEVER, a RegExp object would call it’s constructor each iteration, meaning the search was performed each iteration from the start of the string. New versions make the two consistent and Reg Ex literals now behave as though the constructor is called each time.

129
Q

What is the main method used to perform a reg ex test on input when using the RegExp object?

A
RegExp.exec()
var text = "mom dad";
var pattern = /mom/;
var matches = pattern.exec(text);
// NOTE matches will be an array of matches, if applicable
130
Q
Write the following statement again, using assignment of the function:
function sum(var1, var2) {
   return var1 + var2;
}
A
var sum = function (var1, var 2) {
   return var1 + var2;
}
131
Q
Write the following function again, using a function constructor
function sum(var1, var2) {
  return var1 + var2;
}
A
var sum = new Function("var1", "var2", "return num1 + num2");
NOTE: This is not recommended way of doing things... It requires double interpretation, once for the object, and once for the strings that are passed in.
132
Q

Why is function overloading not allowed in ECMAScript?

A

Because of the nature of functions in ECMAScript, they are basically pointers to a Function object, and that means redeclaring the same function overwrites the previous data. So it’s a side effect of functions being treated as objects.

133
Q

What is function declaration hoisting?

A

The javascript engine parses the source and ‘hoists’ the declarations to the top of the source tree (so functions can be called BEFORE they are defined.

134
Q

When does function declaration hoisting not help you?

A
When you have used a function expression
var sum = function(num1, num2) { }
The function must be called AFTER the delcaration of sum.
135
Q

Is this code okay?
alert(sum(10, 10));
function sum(num1, num2) { }

A

Yes - function declaration hoisting makes sure the declaration is known before the code is executed

136
Q

is this code okay?
alert (sum(10, 10));
var sum = function (num1, num2) {}

A

No - this will cause an error - as a function expression has been used, which is not subject to function declaration hoisting.

137
Q

When you might you use a function as a return type?

A

Using the array / object sort function. It takes a single parameter (sort order function), you can use the function to the field to sort on as a parameter. The function then returns a function that does the sort (using the two appropriate objects to sort on).

   function createCompFunction(propertyName) {
      return function(object1, object2) {
         var value1 = object1[propertyName];
         var value2 = object2[propertyName];
         if (value1 < value2) {
            return -1;
         } else if (value1 > value2) {
            return 1;
         } else {
            return 0;
         }
      };
   }
138
Q

What are the two special objects in a Javascript function?

A

arguments and this

139
Q

How would you decouple a recursive function from it’s own name (in case the function name changes?)

A
// NOTE the arguments.callee method
function factorial (num) {
  if (num <= 1) 
     return 1;
  else
      return num * arguments.callee(num-1);
140
Q

In Javascript, if you use this inside a function at the global level, to what does ‘this’ refer?

A

The window object (so values at a global scope)

141
Q

What does the caller property do?

A

Accessed through the function (i.e. if your function is called inner, inner.caller). It references the function that called this function.

142
Q

Rather than accessing the caller property through the function, how else can you get it to reduce coupling?

A

arguments.callee.caller

143
Q

What is the value of arguments.callee.caller if called from the global scope?

A

null

144
Q

Can arguments.callee be accessed in strict mode?

A

No

145
Q

Why was arguments.callee removed in strict mode?

A

To prevent a security issue where 3rd party code running in the same context could inspect the code.

146
Q

What does the length property contain on a function?

A

The number of named arguments that are expected

147
Q

Is the prototype property enumerable?

A

No, so it can’t be found in a for-in clause

148
Q

Where do the instance methods (such as toString and valueOf) live on a reference type?

A

On the prototype property

149
Q
What does the following code do?
function sum(num1, num2) {
   return num1 + num 2);
}
function callSum1(num1, num2) {
   return sum.apply(this, arguments);
}
A

The use of the built in apply method (from the sum function), sets the ‘this’ value for inside the the sum function. It then passes in the arguments object for the callSum1 function.

150
Q

In strict mode, if a function is called without a context object, is the ‘this’ value coercd to ‘window’?

A

No - instead this becomes undefined, unless explicitly set by either attaching the function to an object or using apply() or call()

151
Q

What is the difference between the call and apply methods?

A

The way arguments are passed- apply will take an array or reference object, call takes each argument individually

152
Q
Is the following equivalent?
var value="25";
var number=Number(value); // casting
alert(typeof number);
var obj = new Number (value);
alert(typeof obj);
A

No - typeof obj will display “object”
typeof number will display “number”

So - using a casting function and calling a primitive wrapper function using “new” is not the same thing.

153
Q

What is wrong with this code?
var str1 = “This is a string”;
str1.color = “red”;
alert(str1.color);

A

str1.color is undefined, as it is a simple type. A wrapper object is created when str1 is accessed in read mode, but it’s immediately destroyed. So there is no persistent object present for str1 in order to add a property.

154
Q

What is wrong with this code?
var str1 = new String(“this is a string”);
str1.color = “red”;
alert(str1.color);

A

Nothing - because str1 is created as a basic type wrapper object, the object is persistent until it’s destroyed or out of scope. So adding a property is perfectly valid.

155
Q

Calling typeof on an instance of a basic type wrapper object will return what?

A

Object

156
Q
Is number a basic wrapper object, or a primitive type after this code?
var value = "25";
var number = Number(value);
alert(typeof number);
A

Primitive type. This is a casting operation and doesn’t use new. The casting functions have the same name as the Basic Wrapper object constructors.

157
Q

Write a line of code to create a Boolean object (wrapper object):

A

var bool = new Boolean(true);

158
Q

What is the problem with using Boolean objects in boolean expressions?

A

Boolean objects will evaluate to true, no matter what their actual value.

159
Q

How would you remove any trailing and leading whitespace on a string?

A
var str = "   this is a string with a lot of whitespace    ";
var trimmed = str.trim();
160
Q
Given:
var text = "cat, bat, sat, fat";
var pattern = /.at/;
Write this following expression in another way:
pattern.exec(text);
A

var matches = text.match(pattern);

161
Q

The string method .replace can use a function as a second argument, how?

A
text.replace(/[<>"&]/g, function (match, pos, originalText) { 
   switch($match) {
      case "": return "&rt;";
      case "&": return "&amp;";
      case "\"": return "&quot;";
   }
});
}
162
Q

What are the two singleton built in objects in ECMAScript?

A

Math and Global

163
Q

What is different about the Global object?

A

It’s not directly accessible. Any global vars / functions you create actually belong to this object.

164
Q

What is the difference between encodeURI and encodeURIComponent?

A

encodeURI only encodes spaces, so it is suitable for passing a URL to it. encodeURIComponent encodes any and all non-alphanumeric characters, so it’s only suitable for use on strings which are going to be added to the end of a URI.

165
Q

If I receive a string that has been encodeing using encodeURI and a part of the string also was encoded using encodeURIComponent, what do I do to return it to the original state?

A
var uri = "long url with encoding in it";
var url = decodeURIComponent(uri);

decodeURIComponent decodes all parts. You can also use decodeURI to change the %20’s back to spaces.

166
Q

While Global is not accessible directly, what object acts as the Global objects delegate, allowing direct access to global variables?

A
window
var color = "red";
alert(window.color); // Okay
167
Q

What are the two types of properties that can be defined on an object?

A

Data property

Accessor property

168
Q

What are the four attributes given to a data property in an object?

A

[[Configurable]] - can the property be redefined by removing the property via delete

[[Enumerable]] - Will the property be returned in a for-in loop?

[[Writable]] - Can the value be changed

[[Value]] - The actual data for the property

169
Q

What are the default attributes given to a data property?

A
[[Configurable]] = true;
[[Enumerable]] = true;
[[Writable]] = true;
[[Value]] = The value of the property
170
Q

How would you create a person object with an attribute “name” that is not writable?

A
var person = { };
Object.defineProperty(person, "name", {
   writable: false;
   value: "Nicholas"
});
171
Q

What happens if you try to change a property that is defined as “writable: false”

A

In non-strict mode, it’s simply ignored. In strict mode, and error is thrown.

172
Q

If you’ve set configurable on a property, can it be changed?

A

No - the only thing you can change on a data property once configurable is false is whether it is writable.

173
Q

What are the Accessor properties?

A

[[Configurable]] // Can we remove the property using delete

[[Enumerable]] // Will the property be returned in a for-in loop?

[[Get]] - The function to call when property is read from (default undefined)

[[Set]] - The function to call when property is written to (default is undefined)

174
Q

Is it possible to define an accessor property explicitly?

A

No - you must use the Object defineProperty() method.

175
Q

Give an example of setting an accessor property for get and set:

A

var book = {
_year: 2004;
edition: 1;
}

Object.defineProperty(book, "year",  {
  get: function() {
     return this._year;
  },
  set: function(newValue) {
     if (newValue > 2004) {
       this._year = newValue;
       this.edition += newValue - 2004;
     }
  }
});
176
Q

If I assign a getter using defineProperty, what happens if I try to set the value?

A

Nothing - it will be ignored (strict mode, it will throw an error).

177
Q

It’s common to have to define more than one property, what method can be used to do this?

A

Object.defineProperties()

178
Q

How would you add a property called _year to an object using the defineProperty method?

A
var obj = {};
Object.defineProperty(book, {
   _year: {
        value: 2001
   }
});
179
Q

How can you get information about an objects properties?

A

var descriptor= Object.getOwnPropertyDescriptor(obj, “var”);
alert(descriptor.value);
alert(descriptor.configurable) etc…

180
Q

What pattern did developers start using to create objects in ECMAScript (to avoid code duplication)

A

Factory pattern

function CreatePerson(name) {
  var o = new Object();
  o.name = name;
  o.sayName = function() {alert(this.name); };
  return o;
}
// NOTE THIS has the issue that you cant determine what type of object it is, as it will always be 'Object'
181
Q

What other method is more popular for creating objects?

A
function Person(name) {
  this.name = name;
  this.sayName = function() {alert(this.name)};
}
var person1 = new Person("Steveo");
182
Q

Objects in java have a property called ‘constructor’ - what can this be used for?

A

You can determine the type of an object like such:
personObj.constructor === Person; // True

But using instanceof is considered more safe

personObj instanceof Person; // True

183
Q

If you create two objects from the same constructor, and each have the function myFunc, what does the following give?
obj1.myFunc == obj2.myFunc

A

False. Because each function is unique (i.e. recreated) for each object.

184
Q

How can you get around the fact the constructor pattern creates a new version of any functions defined within the constructor?

A
Declare it outside the constructor
function Person () {
  this.func = func;
}
function func() {
}
185
Q

When a function is created, it receives a prototype member that has a constructor member - what does this point to?

A

It points back to the function that it belongs to (so a function called Person will have a prototype member with a constructor member that points to Person)

186
Q

If I declare a prototype to have the following attribute…
Person.prototype.age
can I access it like this?
personObj.age?

A

Yes - even though it’s part of the prototype object, the lookup system finds age when referenced directly from the obj handle.

187
Q

What function can we use to determine if a prototype is of a particular type?

A

Person.prototype.isPrototypeOf(person1);

188
Q

What function can be used to get the prototype of an object?

A

Object.getPrototypeOf(person1)

NOTE: It’s a method on the Object object.

189
Q

If a property is accessed for reading on an object, how is the search performed?

A

First it looks on the object instance. If found, the value is returned, else it looks at the objects pointer to it’s prototype - if found, the value is returned

190
Q

If you create a property on an object with the same name as a property in it’s protoype, what happens?

A

The prototype version is masked. Note, you can’t overwrite the property, just ask it.

191
Q
Why does the following code result in only one instance of the function in the object, rather than one per object?
function Person() {
  this.sayName = sayName;
}
function sayName() {
}
A

Because this.sayName is a pointer to the function sayName, not an actual instance.

192
Q

What property is created with each Javascript Function?

A

the prototype property

193
Q

What is useful about the prototype property?

A

It is available to all variables of a particular reference type.

194
Q

What is the only way to remove a property that is masking a property of the same name in a prototype?

A

Using delete keyword. Setting the property to null will do nothing.

195
Q

What are the two ways the ‘in’ operator can be used?

A

In the for-in loop, and to test whether a variable is accessible within an object.

(i.e. “name” in person1; // True)

196
Q

If a property is hidden by existing on both the prototype and the object, what will hasPrototypeProperty return?

A

false - because it will be picked up on the object first, and the prototype is not checked.

197
Q

When creating an object using the ‘dynamic prototype’ method… what should you do?

A

You should test for the existence of the prototype, and only create it if it doesn’t exist already.

198
Q

How would you test for the existence of a prototype when creating an object using the dynamic prototype pattern?

A

You would test for the existence of a method that should exist if the prototype exists. You only have to test for one method - any will do (and create all prototype functions within that block.

199
Q

What is the parasitic constructor pattern?

A
An object is created and populated within a function. The object is assigned the values passed to the function, and then returned to the caller.
function Person(name) {
  var o = new Object();
  o.name = name;
  o.sayName = function() {
     alert(o.name);
  };
  return o;
}

var p = new Person(“Harrold”);

200
Q

Why is the parasitic constructor pattern useful?

A

You can use it to extend functionality of existing (but not accessible) code. You wrap the function (say array), do whatever else you need to do with it, then return array.

201
Q

What does the !! operator do?

A

Essentially a cast to Boolean. First bang coerced the value to the opposite of its Boolean value, the second bang reverts it back to its correct Boolean value. Note - doing this creates a primitive Boolean type - whereas casting using the Boolean() function creates a boxed type.

202
Q

What does the ‘in’ operator do?

A

It takes a left hand operand (must be either string, or something that can convert to string). The right hand operand must be an object.

It returns true if the left hand operand exists in the object.

203
Q

Using the typeof operator you can determine whether an object is of a certain type, what is another way?

A
// Where obj is of type Vector2 and Vector2
// is a class
if (obj.constructor === Vector2) {
}
204
Q

What is a property in Javascript?

A

It is (similar to C# properties) - a way to implement setters and getters. It defines what happens when you try to get or set a value in the object.

205
Q

Given an object called ‘cannon’ - implement a read-only property for a variable called ‘center’ that returns it’s position.

A
Object.defineProperty(Cannon.prototype, 'center', {
  get: function() {
    return new Vector2(this.currentColor.width / 2, this.currentColor.height / 2);
  }
});
206
Q

What is the name of the object that you use to create a property?

A

Object

207
Q

What method on Object is used to create a property?

A

defineProperty

208
Q

Is the ‘this’ member valid within an Object.defineProperty declaration?

A

Yes - ‘this’ will be available within the callback functions for ‘get:’ and ‘set:’. It refers to the object prototype passed as the first parameter to defineProperty.

209
Q

How would you make a property on an object that returns a zero vector (assuming the vector object is called Vector2, and creating a new Vector2 object without arguments creates an empty vector).

A

object.defineProperty(Vector2, ‘zero’, {
get: function() {
return new Vector2();
}
});

210
Q

What is another, shorter way of adding a property to an object?

A
Vector2['zero'] = function() {
   return new Vector2();
};
211
Q

Methods that are defined using the defineProperty method (on an object) are like what in a class based language?

A

Static methods in that they are accessed through the class (function in javascript), and not through the instance.

212
Q

Are set and get properties defined in the same code block?

A

Yes

object.defineProperty(Vector2, ‘zero’, {
get: function() {
return new Vector2();
},
set: function(v) {
this.x = v.x;
this.y = v.y;
}
});

213
Q

What does a closure implementation look like?

A
var add = (function () {
    var counter = 0;
    return function () {return counter += 1;}
})();

** NOTE: This is a self calling function. It calls itself once, setting counter to 0 and returning a reference to the anonymous function within. Then, when you call add(), the anonymous function that was returned increments the counter by one. This is called a closure - because it has access to the variable ‘counter’ in the parent scope - creating essentially, a private variable.

214
Q

What has better performance, getter in closure form, or a getter implemented on the prototype?

A

A getter implemented on the prototype.

215
Q

How do you implement inheritence in Javascript.

A
By copying the prototype of one object (the parent) into the child objects prototype. Assume there is a class called Vehicle.
function Car() 
{
   Vehicle.call(this); // Calling the parent   constructor
}
Car.prototype = Object.create(Vehicle.prototype);
216
Q

What is the non-jquery way of calling javascript only when the entire page is loaded?

A
window.onload = function() {
   // Do stuff
};
217
Q

Does the script tag use the href or src attribute to point to the external file?

A

src

218
Q

How do you override a method in Javascript.

A

Simply redefine the method on the prototype of the child / subclass.

Canon.prototype.draw = function() { }

219
Q

When does a function invocation become a constructor invocation?

A

When it is preceded by the keyword new.

220
Q

Is it possible to run an arbitrary function in the context of any object?

A

Yes, using the call, or apply functions, you can specify the object that will be used as the ‘this’ keyword in the function.

221
Q

What would be the idiomatic way of writing the following expression?

if (a === undefined) a = [];

A

a = a || [];

// Because the || operator returns the first truthy argument

222
Q

What is a good idea to do in the parameter list of a function if a parameter is optional?

A
Use a comment
function foobar (a, /*optional*/b) {
}
223
Q

How would you use the arguments array to determine if the function is executed with the correct number of arguments?

A
function foobar(a, b, c) {
   if (arguments.length != 3) {
      throw new Error (stuff);
   }
}
224
Q

What is one very legitimate use for using the arguments array?

A

Writing functions that will take an unlimited number of parameters

function max(1, 4, 2, 67, 23, 234234, 4, 2, 34234, 234) {
    for (i = 0; i
225
Q

Arguments array is not actually an array, but an object, what is one weird thing it can do in non-strict mode?

A

You can modify the value of the actual original parameters, by assigning a value to the appropriate element of the array.

// Don’t do this!

226
Q

Can you use the parameter or local variable name ‘arguments’ in strict-mode?

A

No - in strict mode arguments acts like a keyword, and cannot be used.

227
Q

What happens if you write too, or reference the callee and caller properties of the Arguments object in strict-mode?

A

It is guarenteed to throw a TypeError

228
Q

What does the callee field of the Arguments object refer to?

A

The currently running function

229
Q

What does the caller field of the Arguments object refer to?

A

It refers to the callstack - but note - this is a non-standard feature

230
Q

What would be one use for the callee attribute on the Arguments object?

A

Recursive functions - allowing the function to call itself. This is particularly useful in un-named functions.

231
Q

If you have a function that requires lots of parameters, what is one way to simplify the process of remembering each parameter name and order?

A

Pass an object instead that requires keyword:value pairs. The order of the parameters no longer matters

232
Q

Is this legal, and if so how would you invoke the following function?
a = [function() { x * x; }, 10];

A

Yes it is legal.

a0;

233
Q

Can a function be an element of an array?

A

Yes - functions are just data, and can be assigned to things just like data - such as variables and array elements.

234
Q

How can you simulate a static variable in a JavaScript function?

A

Use a property (either as a property, or an array element on the function).

uniqueInteger.integer = 0;
function uniqueInteger() { return uniqueInteger.integer++; }
235
Q

How can you emulate a namespace in JavaScript?

A

Use a function, since variables have function scope.

function myModule() {
   // module code goes here.
}
myModule(); // Remember to invoke!!

// Idiomatic way of doing it using an IIFE

(function myModule() {
   // Module code goes here.
}());
236
Q

Which of the following is the correct way to invoke an IIFE?

(function() { // code goes here }());

(function() { // Code goes here })();

A

Both are correct.

237
Q

What does lexical scoping mean?

A

It’s the method by which the javascript compiler determines the scope of variables - it uses the variable scope that was in effect when it was written, not when it is invoked.

238
Q

What does this return?

var scope = "global scope"; // A global variable
function checkscope() {
 var scope = "local scope"; // A local variable
 function f() { return scope; } // Return the value in scope here
 return f();
}
checkscope()
A

“local scope”

239
Q
What does this return?
var scope = "global scope"; // A global variable
function checkscope() {
 var scope = "local scope"; // A local variable
 function f() { return scope; } // Return the value in scope here
 return f;
}
checkscope()() // What does this return?
A

“local scope”

// Remember - lexical scoping says that the scope chain 
// that was in effect at the time of writing is used, not the
// scope chain that is in-effect at time of calling!

note: checkscope()() - is invoking checkscope() then invoking the inner fucnction that is returned, f. It would be the same as

f = checkscope();
f();

240
Q

What benefit does using a closure like below have?

var uniqueInteger = (function() { // Define and invoke
 var counter = 0; 
 return function() { return counter++; };
 }()); // IIFE
A

Because function() is a closure, it continues to have access to the counter variable. But that variable has become inaccessible to the outside world through any other means, effectively making it private.

241
Q

Is it possible to create a closure where multiple functions can reference the same variable?

A

Yes.

function counter() {
    var n = 0;
    return {
        count: function() { return n++; },
        reset: function() { n = 0; }
    };
}

var a = counter();

a. count();
a. reset();

242
Q

Can the use of a shared variable and closure, be used with a accessors?

A

yes

function counter(n) { // Function argument n is the private variable
 return {
    get count() { return n++; },
    set count(m) {
        if (m >= n) n = m;
             else throw Error("count can only be set to a larger value");
    }
  };
}

a. count = 2000;
console. log(a.count); // 2000

// We use the parameter n here instead of the global variable so that we can specify the initial value on original invocation.

243
Q

When checking the ‘length’ property of a function, what does it reference?

A

The ‘arity of the function - i.e. the number of parameters it expects.

244
Q

In non-strict mode - how could you use the ‘length’ attribute to determine how many parameters should have been passed, from WITHIN the function?

A

arguments.callee.length

245
Q

The call and apply function methods allow you to invoke an function as if it was…

A

a member of another object

246
Q

What does the bind() function do?

A

It binds a method to an object.

// i.e. 
var myobject = {
    "foobar": 10
};
function myFunc(num) {
    console.log(this.foobar + " and another number: " + num);
}
var x = myFunc.bind(myobject);
x(21);