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
What options are available to prevent code being interpreted as HTML when embedding javascript in XHTML?
Use the html codes for > or < signs (or they will be interpreted as tags) - or use < ! [CDATA [ block
26
What is quirksmode?
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.
27
In ANY browser, how do you turn off quirksmode?
By adding a correct doctype. (i.e. HTML 4.01 strict, XHTML or HTML5)
28
In ANY browser, how do you enable "almost standards mode"?
By using the transitional and frameset doctypes
29
What is the only only element that can be included in the body tag, but not in the noscript tag?
script
30
How do you inform a user that they require a javascript enabled browser?
``` By using the noscript tag < body> < noscript> < p>You require Javascript dude < /noscript> < / body> ```
31
The first letter of a Javascript identifier must be...
a letter, an underscore or a dollar sign
32
How do you enable strict mode in Javascript?
Place "use strict" at the top of the script
33
Is it possible to leave out the ';' in a statement?
Yes - although not recommended.
34
Variables in javascript are ..... typed.
Loosely
35
``` Is the following valid? var message = "hi"; message = 100; ```
Yes - but not recommended (you are changing the type of the variable, which could be confusing)
36
What is the difference between using var and not using var to declare a variable?
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.
37
Global variables (declared without using var) are not recommended - how do you detect their use in your code?
By setting "use strict" on the script, a ReferenceError will be thrown
38
How do you declare multiple variables in a single line?
``` var message = "hi", found = false, age = 29; ```
39
If you have received the following the error - what happened? Uncaught SyntaxError: Unexpected eval or arguments in strict mode
You declared a variable named eval or arguments in strict mode (which is not allowed).
40
What operator do you use to determine the type of a variable?
typeof varName;
41
What results does typeof return?
``` undefined boolean string number object function ```
42
Functions are considered ...... in ECMAscript?
objects (although they have some unique properties to themselves)
43
If a variable is declared using var and not assigned anything, what is it's value?
undefined
44
Should you ever explicitly set the value of a variable to undefined?
No - setting them to null is fine - but not to undefined
45
How do you convert a variable to a boolean type?
Use the boolean casting function | Boolean(var);
46
What types are converted to true if passed to the Boolean function (and consequently an if statement)?
true Any non-empty string Any non-zero number including infinity (negative numbers too) Any object
47
What types are converted to false if passed to the Boolean function (and consequently an if statement)?
``` false (empty string) 0, NaN null undefined ```
48
``` Is this a valid octal number? var octalNum2 = 079; ```
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
49
``` Is this a valid octal number? var octalNum1 = 070; ```
Yes - the leading 0 is important to tell Javascript that this is an octal number (and the numbers are within range (0-7))
50
Numbers using octal or hex format are treated as ..... in all artithmetic operations?
decimal
51
There is only one numeric type in Javascript (number) how do you define a floating point number?
``` Just give it a decimal. var floatNum = 1.1; ```
52
ECMAScript always looks for ways to convert floats back to ints, why is that?
They take twice as much memory as an int.
53
How do you determine the smallest and largest numbers that can be represented in ECMAScript?
Number.MIN_VALUE; | Number.MAX_VALUE;
54
What does the following expression return? | NaN == NaN
False (NaN is not equal to ANYTHING)
55
How do you test if a number is NaN?
isNaN(variable);
56
What happens if you apply isNaN to an object?
The objects method "valueOf()" is called, if that doesn't work, then it calls the "toString()" method
57
What are the three functions used to convert non-numeric values to numbers?
Number() parseInt() parseFloat()
58
What unary operator works the same way as the Number() function?
Unary +
59
What is wrong with the following statement - and how would you fix it? parseInt("070");
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);
60
What is the difference between parseInt and parseFloat?
There is no radix mode as parseFloat only ever parses decimal values.
61
Are strings mutable or immutable in ECMAScript?
immutable
62
How do you convert a value to a string?
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.
63
What does the hasOwnProperty method do on an object?
Checks to see if the method being queried exists on that object, and not part of a prototype
64
What are the base methods for an object in ECMAScript?
``` constructor hasOwnProperty(propertyName) isPrototypeOf(object0 propertyIsEnumerable(propertyName) toLocaleString() toString() valueOf() ``` (All objects have these in ECMAScript)
65
What happens in this instance? var stringNum = "1"; ++stringNum;
stringNum is converted to a string then incremented.
66
``` What happens in the following instance? var stringNum = "1"; var num = +stringNum; ```
The value of stringNum is converted to a number and assigned to num.
67
Can the order that object properties appear in a "for-in" statement be predicted?
No, object properties are unordered in ECMA script
68
What is the 'with' statement?
``` 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; } ```
69
When is using the with statement invalid and an error?
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
70
What data types does switch work with in ECMA Script?
All data types, including expressions, i.e. | case num > 0 && num <= 10:
71
How do you access the arguments passed to a function?
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;
72
Is function overloading possible in ECMA Script?
No - if two functions have the same name, the final function is the one used.
73
``` What is wrong with the following code? var name = "Steveybigs"; name.age = 27; ```
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.
74
``` What is wrong with the following code? var person = new Object(); person.name = "Bill chumpbucket"; ```
Nothing - it is perfectly valid to add properties to an object (reference type) in Javascript.
75
``` var obj1 = new Object(); var obj2 = obj1; obj1.name = "Dickhead"; alert(obj2.name); ``` What will be printed out
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.
76
All function arguments are pass by...
value
77
``` 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?
"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).
78
typeof can be used to determine what type a variable is - but why isn't it useful for reference types?
Because it will simply tell you it's an object. To determine specificaly what type of object, use instanceof. alert(person instanceof MyObject);
79
What is the execution context?
It determines what other data a variable or function has access to, as well as how to behave.
80
In a browser, the global context is said to be...
the window object | (so all global variables and functions are created as properties and methods of the window object.
81
When a function is executing, it's context is pushed onto...
the context stack | and it is popped when finished, returning the context to the previously executing context
82
What is a scope chain?
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.
83
In c, the iterator variable in a for loop is local to the for loop - what about Javascript?
No - it's available outside the for block, as Javascript does not have block level variable scope.
84
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?
The containing functions local scope.
85
Why is it important to break the link between a native javascript variable and a DOM object when it is no longer used?
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.
86
Is a reference type a class?
No - there are no classes in ECMAScript
87
Why are Object reference types so useful?
They can be quickly created and have properties added - useful for passing data around in a program quickly.
88
Define an object literal named 'person' with properties name and age.
var person = { name : "Jizzbomb", age: 29 };
89
What is potentially different with the way you declare properties when using object literal notation?
You can use strings and numbers as the identifiers.
90
``` Write an object literal statement that is the same as: var person = new Object(); ```
var person = { }; // Not really recommended
91
What is unusual about constructor behavior when defining an object via object literal notation?
The constructor is never called.
92
How would you use an object literal to pass data to a function?
``` function displayInfo(args) { /* do stuff */ } displayInfo({ name: "Foobaz", age: 20 }); ```
93
What is the difference between person["name"] and person.name
Nothing - they effectively do the same thing.
94
What is the advantage of using bracket notation when accessing properties in an object?
You can pass variables into the brackets.
95
What makes an array different in ECMAScript compared to other languages?
Each slot can hold it's own data type
96
Write five different ways to create an array in ECMAScript?
``` 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"]; ```
97
``` Is this a valid way of creating an array? var values = [1, 2, ]; ```
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.
98
What is similar about creating objects and arrays using the literal notation?
The constructors are not called for either.
99
var color = ["red", "Yellow", "Blue"]; How do you get the length of the array?
var len = color.length;
100
Is it valid to set the length property of an array?
``` Yes, you can remove items by doing something like: var colors = ["red", "Yellow", "Blue"]; colors.length = 2; ```
101
What is wrong with this code? var colors = ["Red", "Blue", "Yellow"]; colors.length = 2; alert(colors[2]);
colors[2] refers to the third element which no longer exists thanks to the color.length = 2 statement;
102
Write a statement that adds a new color to the end of an array called colors.
colors[color.length] = "Aubergine";
103
How do you determine if an Array is an Array?
Array.isArray(value); Available in IE 9+, FF4+, S5+ O10.5+ and Chrome
104
What is the difference between toString and valueOf when called on an Array?
Nothing - they both return comma-seperated string containing the values of the array.
105
How could you simulate the output of Array.toString with the join method?
myArray.join(",");
106
How could an Array be used to behave like a stack?
The Array object contains methods like push and pop which makes it behave like a LIFO object.
107
What functions allow an Array object to behave like a Queue?
push and shift
108
How would you sort a basic numeric array?
myNumArray.sort(compare); // Were compare is a user defined comparison function
109
What is the issue with using just 'sort' with no user defined comparison function on a numeric array?
The numbers are sorted as strings, which means they will be out of numeric order.
110
Write a simple, but fast compare function that works for numeric arrays?
``` function compare(num1, num2) { return num2 - num1; } ```
111
How could you use concat to add an array literal to an existing array?
``` var myColors = ["red", "green", "Blue"]; myColors = myColors.concat(["purple", "black"]); ```
112
What does the slice method do on an array?
``` 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
What is the splice method used for on an array?
It can be used to delete, insert and replace items in an array
114
Remove the first item form the following array using splice | colors = ["red", "gree", "blue"];
var removed = colors.splice(0, 1); // Remove the first item
115
Insert two items at position 1 using splice given the following array: colors = ["red", "gree", "blue"];
var removed = colors.splice(1, 0, "yellow", "orange"); // note, nothing is removed in this example
116
Insert two values, but delete one using splice from the following array colors = ["red", "yellow", "green"];
var removed = colors.splice(1, 1, "red", "purple");
117
What functions can you use on an array to determine the lcoation of an item?
colors. indexOf("red"); | colors. lastIndexOf("red");
118
What does the "every" iterator do on an array?
It is run on every element of an array, and returns true if the function returns true on every item.
119
What does the "some" iterator do on an array?
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
What does the "filter" iterator do on an array?
``` 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
What does the "map" iterator do on an array?
``` 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
What does the forEach() iterator do on an array?
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
What are the reduction methods in ECMAScript?
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
To convert a string representation of a date to milliseconds (since 1970), what function do you use?
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
If you pass nonsense into Date.parse(), what does it return?
NaN
126
What is another way of using Date.parse() that reduces the amount of code required?
var someDate = new Date("May 25, 2004"); | It calls Date.parse() in the constructor
127
If I wanted to get the exact date as of now - what function would I use?
Date.now()
128
In older versions of ECMAScript there is a difference between a regex literal and a RegExp object, what is it?
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
What is the main method used to perform a reg ex test on input when using the RegExp object?
``` 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
``` Write the following statement again, using assignment of the function: function sum(var1, var2) { return var1 + var2; } ```
``` var sum = function (var1, var 2) { return var1 + var2; } ```
131
``` Write the following function again, using a function constructor function sum(var1, var2) { return var1 + var2; } ```
``` 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
Why is function overloading not allowed in ECMAScript?
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
What is function declaration hoisting?
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
When does function declaration hoisting not help you?
``` When you have used a function expression var sum = function(num1, num2) { } The function must be called AFTER the delcaration of sum. ```
135
Is this code okay? alert(sum(10, 10)); function sum(num1, num2) { }
Yes - function declaration hoisting makes sure the declaration is known before the code is executed
136
is this code okay? alert (sum(10, 10)); var sum = function (num1, num2) {}
No - this will cause an error - as a function expression has been used, which is not subject to function declaration hoisting.
137
When you might you use a function as a return type?
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
What are the two special objects in a Javascript function?
arguments and this
139
How would you decouple a recursive function from it's own name (in case the function name changes?)
``` // NOTE the arguments.callee method function factorial (num) { if (num <= 1) return 1; else return num * arguments.callee(num-1); ```
140
In Javascript, if you use this inside a function at the global level, to what does 'this' refer?
The window object (so values at a global scope)
141
What does the caller property do?
Accessed through the function (i.e. if your function is called inner, inner.caller). It references the function that called this function.
142
Rather than accessing the caller property through the function, how else can you get it to reduce coupling?
arguments.callee.caller
143
What is the value of arguments.callee.caller if called from the global scope?
null
144
Can arguments.callee be accessed in strict mode?
No
145
Why was arguments.callee removed in strict mode?
To prevent a security issue where 3rd party code running in the same context could inspect the code.
146
What does the length property contain on a function?
The number of named arguments that are expected
147
Is the prototype property enumerable?
No, so it can't be found in a for-in clause
148
Where do the instance methods (such as toString and valueOf) live on a reference type?
On the prototype property
149
``` What does the following code do? function sum(num1, num2) { return num1 + num 2); } function callSum1(num1, num2) { return sum.apply(this, arguments); } ```
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
In strict mode, if a function is called without a context object, is the 'this' value coercd to 'window'?
No - instead this becomes undefined, unless explicitly set by either attaching the function to an object or using apply() or call()
151
What is the difference between the call and apply methods?
The way arguments are passed- apply will take an array or reference object, call takes each argument individually
152
``` Is the following equivalent? var value="25"; var number=Number(value); // casting alert(typeof number); ``` ``` var obj = new Number (value); alert(typeof obj); ```
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
What is wrong with this code? var str1 = "This is a string"; str1.color = "red"; alert(str1.color);
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
What is wrong with this code? var str1 = new String("this is a string"); str1.color = "red"; alert(str1.color);
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
Calling typeof on an instance of a basic type wrapper object will return what?
Object
156
``` Is number a basic wrapper object, or a primitive type after this code? var value = "25"; var number = Number(value); alert(typeof number); ```
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
Write a line of code to create a Boolean object (wrapper object):
var bool = new Boolean(true);
158
What is the problem with using Boolean objects in boolean expressions?
Boolean objects will evaluate to true, no matter what their actual value.
159
How would you remove any trailing and leading whitespace on a string?
``` var str = " this is a string with a lot of whitespace "; var trimmed = str.trim(); ```
160
``` Given: var text = "cat, bat, sat, fat"; var pattern = /.at/; Write this following expression in another way: pattern.exec(text); ```
var matches = text.match(pattern);
161
The string method .replace can use a function as a second argument, how?
``` text.replace(/[<>"&]/g, function (match, pos, originalText) { switch($match) { case "": return "&rt;"; case "&": return "&"; case "\"": return """; } }); } ```
162
What are the two singleton built in objects in ECMAScript?
Math and Global
163
What is different about the Global object?
It's not directly accessible. Any global vars / functions you create actually belong to this object.
164
What is the difference between encodeURI and encodeURIComponent?
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
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?
``` 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
While Global is not accessible directly, what object acts as the Global objects delegate, allowing direct access to global variables?
``` window var color = "red"; alert(window.color); // Okay ```
167
What are the two types of properties that can be defined on an object?
Data property | Accessor property
168
What are the four attributes given to a data property in an object?
[[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
What are the default attributes given to a data property?
``` [[Configurable]] = true; [[Enumerable]] = true; [[Writable]] = true; [[Value]] = The value of the property ```
170
How would you create a person object with an attribute "name" that is not writable?
``` var person = { }; Object.defineProperty(person, "name", { writable: false; value: "Nicholas" }); ```
171
What happens if you try to change a property that is defined as "writable: false"
In non-strict mode, it's simply ignored. In strict mode, and error is thrown.
172
If you've set configurable on a property, can it be changed?
No - the only thing you can change on a data property once configurable is false is whether it is writable.
173
What are the Accessor properties?
[[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
Is it possible to define an accessor property explicitly?
No - you must use the Object defineProperty() method.
175
Give an example of setting an accessor property for get and set:
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
If I assign a getter using defineProperty, what happens if I try to set the value?
Nothing - it will be ignored (strict mode, it will throw an error).
177
It's common to have to define more than one property, what method can be used to do this?
Object.defineProperties()
178
How would you add a property called _year to an object using the defineProperty method?
``` var obj = {}; Object.defineProperty(book, { _year: { value: 2001 } }); ```
179
How can you get information about an objects properties?
var descriptor= Object.getOwnPropertyDescriptor(obj, "var"); alert(descriptor.value); alert(descriptor.configurable) etc...
180
What pattern did developers start using to create objects in ECMAScript (to avoid code duplication)
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
What other method is more popular for creating objects?
``` function Person(name) { this.name = name; this.sayName = function() {alert(this.name)}; } var person1 = new Person("Steveo"); ```
182
Objects in java have a property called 'constructor' - what can this be used for?
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
If you create two objects from the same constructor, and each have the function myFunc, what does the following give? obj1.myFunc == obj2.myFunc
False. Because each function is unique (i.e. recreated) for each object.
184
How can you get around the fact the constructor pattern creates a new version of any functions defined within the constructor?
``` Declare it outside the constructor function Person () { this.func = func; } ``` ``` function func() { } ```
185
When a function is created, it receives a prototype member that has a constructor member - what does this point to?
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
If I declare a prototype to have the following attribute... Person.prototype.age can I access it like this? personObj.age?
Yes - even though it's part of the prototype object, the lookup system finds age when referenced directly from the obj handle.
187
What function can we use to determine if a prototype is of a particular type?
Person.prototype.isPrototypeOf(person1);
188
What function can be used to get the prototype of an object?
Object.getPrototypeOf(person1) NOTE: It's a method on the Object object.
189
If a property is accessed for reading on an object, how is the search performed?
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
If you create a property on an object with the same name as a property in it's protoype, what happens?
The prototype version is masked. Note, you can't overwrite the property, just ask it.
191
``` 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() { } ```
Because this.sayName is a pointer to the function sayName, not an actual instance.
192
What property is created with each Javascript Function?
the prototype property
193
What is useful about the prototype property?
It is available to all variables of a particular reference type.
194
What is the only way to remove a property that is masking a property of the same name in a prototype?
Using delete keyword. Setting the property to null will do nothing.
195
What are the two ways the 'in' operator can be used?
In the for-in loop, and to test whether a variable is accessible within an object. (i.e. "name" in person1; // True)
196
If a property is hidden by existing on both the prototype and the object, what will hasPrototypeProperty return?
false - because it will be picked up on the object first, and the prototype is not checked.
197
When creating an object using the 'dynamic prototype' method... what should you do?
You should test for the existence of the prototype, and only create it if it doesn't exist already.
198
How would you test for the existence of a prototype when creating an object using the dynamic prototype pattern?
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
What is the parasitic constructor pattern?
``` 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
Why is the parasitic constructor pattern useful?
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
What does the !! operator do?
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
What does the 'in' operator do?
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
Using the typeof operator you can determine whether an object is of a certain type, what is another way?
``` // Where obj is of type Vector2 and Vector2 // is a class if (obj.constructor === Vector2) { } ```
204
What is a property in Javascript?
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
Given an object called 'cannon' - implement a read-only property for a variable called 'center' that returns it's position.
``` Object.defineProperty(Cannon.prototype, 'center', { get: function() { return new Vector2(this.currentColor.width / 2, this.currentColor.height / 2); } }); ```
206
What is the name of the object that you use to create a property?
Object
207
What method on Object is used to create a property?
defineProperty
208
Is the 'this' member valid within an Object.defineProperty declaration?
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
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).
object.defineProperty(Vector2, 'zero', { get: function() { return new Vector2(); } });
210
What is another, shorter way of adding a property to an object?
``` Vector2['zero'] = function() { return new Vector2(); }; ```
211
Methods that are defined using the defineProperty method (on an object) are like what in a class based language?
Static methods in that they are accessed through the class (function in javascript), and not through the instance.
212
Are set and get properties defined in the same code block?
Yes object.defineProperty(Vector2, 'zero', { get: function() { return new Vector2(); }, set: function(v) { this.x = v.x; this.y = v.y; } });
213
What does a closure implementation look like?
``` 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
What has better performance, getter in closure form, or a getter implemented on the prototype?
A getter implemented on the prototype.
215
How do you implement inheritence in Javascript.
``` 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
What is the non-jquery way of calling javascript only when the entire page is loaded?
``` window.onload = function() { // Do stuff }; ```
217
Does the script tag use the href or src attribute to point to the external file?
src
218
How do you override a method in Javascript.
Simply redefine the method on the prototype of the child / subclass. Canon.prototype.draw = function() { }
219
When does a function invocation become a constructor invocation?
When it is preceded by the keyword new.
220
Is it possible to run an arbitrary function in the context of any object?
Yes, using the call, or apply functions, you can specify the object that will be used as the 'this' keyword in the function.
221
What would be the idiomatic way of writing the following expression? if (a === undefined) a = [];
a = a || []; // Because the || operator returns the first truthy argument
222
What is a good idea to do in the parameter list of a function if a parameter is optional?
``` Use a comment function foobar (a, /*optional*/b) { } ```
223
How would you use the arguments array to determine if the function is executed with the correct number of arguments?
``` function foobar(a, b, c) { if (arguments.length != 3) { throw new Error (stuff); } } ```
224
What is one very legitimate use for using the arguments array?
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
Arguments array is not actually an array, but an object, what is one weird thing it can do in non-strict mode?
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
Can you use the parameter or local variable name 'arguments' in strict-mode?
No - in strict mode arguments acts like a keyword, and cannot be used.
227
What happens if you write too, or reference the callee and caller properties of the Arguments object in strict-mode?
It is guarenteed to throw a TypeError
228
What does the callee field of the Arguments object refer to?
The currently running function
229
What does the caller field of the Arguments object refer to?
It refers to the callstack - but note - this is a non-standard feature
230
What would be one use for the callee attribute on the Arguments object?
Recursive functions - allowing the function to call itself. This is particularly useful in un-named functions.
231
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?
Pass an object instead that requires keyword:value pairs. The order of the parameters no longer matters
232
Is this legal, and if so how would you invoke the following function? a = [function() { x * x; }, 10];
Yes it is legal. | a[0](a[1]);
233
Can a function be an element of an array?
Yes - functions are just data, and can be assigned to things just like data - such as variables and array elements.
234
How can you simulate a static variable in a JavaScript function?
Use a property (either as a property, or an array element on the function). ``` uniqueInteger.integer = 0; function uniqueInteger() { return uniqueInteger.integer++; } ```
235
How can you emulate a namespace in JavaScript?
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
Which of the following is the correct way to invoke an IIFE? (function() { // code goes here }()); (function() { // Code goes here })();
Both are correct.
237
What does lexical scoping mean?
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
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() ```
"local scope"
239
``` 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? ```
"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
What benefit does using a closure like below have? ``` var uniqueInteger = (function() { // Define and invoke var counter = 0; return function() { return counter++; }; }()); // IIFE ```
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
Is it possible to create a closure where multiple functions can reference the same variable?
Yes. ``` function counter() { var n = 0; return { count: function() { return n++; }, reset: function() { n = 0; } }; } ``` var a = counter(); a. count(); a. reset();
242
Can the use of a shared variable and closure, be used with a accessors?
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
When checking the 'length' property of a function, what does it reference?
The 'arity of the function - i.e. the number of parameters it expects.
244
In non-strict mode - how could you use the 'length' attribute to determine how many parameters should have been passed, from WITHIN the function?
arguments.callee.length
245
The call and apply function methods allow you to invoke an function as if it was...
a member of another object
246
What does the bind() function do?
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); ```