Javascript 2 Flashcards

1
Q

Why is the statement “use strict”; a string literal?

A

Because of backwards compatibility. There is no sideeffect to evaluating a string literal, so in engines that don’t support strict mode, they will work fine.

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

What is the biggest issue with ‘strict mode’;

A

When concatenating files for deployment, you may have libraries that don’t use strict mode, or files that don’t use strict mode. However, the act of concatenating them may cause files that weren’t written with strict mode in mind to have it enabled.

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

What is one way of getting around the “strict mode” file concatenation issue?

A

Wrap the code in immediately invoked function expressions and use “use strict” at the top of each function.

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

What is an IIFE?

A

Immediately Invoked Function Expression - a function that is called as soon as it is loaded - with no need for the user to call it explicitly.

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

What will the following produce:

var num1 = 1;
var num2 = 2.34;

console. log(typeof num1);
console. log(typeof num2);

A

number
number

(NOTE: All javascript numbers are of type number)

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

All numbers in javascript are treated as 64bit (double precision floating point) numbers - with one exception. What is that?

A

When using bit wise operators. The number is converted to a 32bit, big-endian, twos compliment number

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

How would you print the value of a number in binary?

A
var num = 128;
num.toString(2);

The number in the parameters defines the radix - 2 = binary

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

Are the following equivalent?

        console. log((0.1 + 0.2) + 0.3);
        console. log(0.1 + (0.2 + 0.3));
A

No - they should be - but floating point math is inaccurate at best - and you can’t guarantee it is associative (unlike in maths, where it would be).

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

3 + true = 4 // This is true in Javascript

What is this process called?

A

Coercion, the values are coerced into the type appropriate to make the statement work.

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

Which operators perform coercian?

A

The maths operators - however, ‘+’ is a bit subtle, since when you use a string in the expression, it will convert the value to a string, rather than a number.

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

What does “2” + 3 == in Javascript?

A

“23”

Note - not a number

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

What does (1 + 2) + “3” == in javascript?

A

“33”

Because addition groups to the left

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

What is the biggest issue with coercions?

A

A number that is null won’t fail in a maths operation - it will be converted to 0. This could hide errors.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q
var x = NaN;
x === NaN;

What is the result?

A

false

NaN is not equal to itself.

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

Because there are other values that can be coerced to NaN - what is the most reliable way for testing for NaN?

A
var a = NaN;
a !== a; // true

This works because NaN is the only value in Javascript that is not equal to itself.

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

Write a utility function that tests for NaN - reliably.

A
function isReallyNaN(x)
{
   return x !== x;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Can an object be coerced into being a primitive?

A

Yes - particularly objects to strings

“the math object” + Math; // “the math object: [object Math]”

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

How is an object converted to a string?

A

By calling the toString method (this is done implicitly in a coercion, or the user can do it themselves as required).

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

What is the issue with the valueOf method in regards to coercion?

A

valueOf only really works well on objects that are supposed to be numbers (i.e. a Number object). So when adding two objects using the ‘+’ operator, javascript isn’t really sure of the intent, is it concatenation, or addition, and blindly calls the valueOf method - but this may not have been intended.

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

What is ‘truthiness’?

A

When an object is coerced into a boolean expression.

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

There are seven falsy values in Javascript - what are they?

A

Null, NaN, 0, -0, “”, false, and undefined

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

What is the error in the following code?

function point(x) {
   if (!x) {
      x = 100;
   }
}
A

x is relying on coercion, unfortunately 0 is a valid number for this function, but would be evaluated to false. So we need to use a different test.

if (typeof x === undefined) {
x = 100;
}

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

Type errors can be hidden by…

A

implicit coercions

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

The + operator is overloaded to do addition or concatenation depending on…

A

it’s argument types

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Objects are coerced to number via...
valueOf
26
Objects are coerced to strings via...
toString
27
Objects with a valueOf method should provide a toString method that does what?
Returns a string representation of the number generated by valueOf
28
Rather than using 'truthiness' for testing undefined values, what should you use?
typeof or comparison to 'undefined'.
29
What is different between the ECMA script standard and Javascript in regards to how 'null' is reported by the operator 'typeof'?
According to the standard null should be it's own type, however Javascript reports null as an object.
30
What are the five primitive types in Javascript?
``` booleans, numbers, strings, null, undefined ```
31
Strings are primitive types in Javascript, and yet you can create a string using new. Why? var string = new String('superstring');
This is a 'boxed' type - it's a string wrapped in an object.
32
``` What is the result of the following code? var str1 = "My fun string"; var str2 = new String("My fun string"); ``` console. log(str1 == str2); console. log(str1 === str2);
true true The object is coerced to a string.
33
``` What is the result of the following code? var str1 = new String("My fun string"); var str2 = new String("My fun string"); ``` console. log(str1 == str2); console. log(str1 === str2);
false false The comparisons are actually checking that the objects are the same - they are obviously two different objects (this code does NOT check the value of the objects).
34
What is the result of the following? "hello".newProperty = 10; console.log("hello".newProperty); And why?
undefined Strings are implicitly wrapped by the string object, which allows you to add properties to it. However, this serves no purpose, as when you reference it in this manner, a new string is created each time. Hence the undefined value.
35
Getting and setting properties on primitives does what?
Implicitly creates an object wrapper.
36
Object wrappers have the same behavior as their primitive types when testing for equality - true or false?
False - they do not behave in the same way - making it difficult to compare values when using the object wrappers.
37
Is using the == operator okay with mixed types?
You should avoid using it with mixed types.
38
When reading data from a form, should you just use coercion to test for equality?
No - use Number or the unary + operator to convert to a true number before testing.
39
When values are of the same type - is there any difference between the == and === operators?
No - but you should use the === anyway - as it tells other programmers reading your code that you are definitely not expecting coercion to occur in this segment of code.
40
What coercion takes place when you have: null == undefined
None; always true
41
What coercion takes place when you have | null or undefined == anything other than null or undefined
None: always false
42
What coercion takes place when you have Primitive String, Number, Boolean == Date Object
Primitive => number | Date Object => Primitive (first try toString, then valueOf)
43
What coercion takes place when you have Primitive String, Number, Boolean == Non Date Object
Primitive => number | Non Date Object => Primitive (first try valueOf, then toString)
44
What coercion takes place when you have Primitive String, Number, Boolean == Primitive String, Number, Boolean
Primitive => number
45
What is a good rule of thumb with regards to using the == operator for things like dates?
Create explicit application logic, for instance a function that takes a date object and formats it in a way that you will use in your application - this makes the intention explicit.
46
Semi colons are only ever inserted...
before the } token, after one or more newlines, or at the end of program input. Semicolons are only ever inserted when the next input token cannot be parsed.
47
Is the following legal code? function area(r) { r = +r return Math.PI * r * r }
No - as the +r does not have a semicolon after it, and the return statement is not on a new line - so the automatic semicolon insertion doesn't work in this context. This would be an error.
48
Is a semicolon added in this context? a = b f();
Yes - because: a = b f(); is not valid code - so the JS engine will attempt to add a semicolon after the b - before the next token it couldn't parse f().
49
Is a semicolon added in this context? a = b (f());
No - because: a = b(f()); is valid code - a semicolon would not be required.
50
Even if you are not deliberately using semi-colon completion functionality - it can hide or cause some weird errors - why is that?
Some characters can be problematic, because by leaving the semicolon off on the previous line - they may still form a valid - yet unintetional statement. The characters to look out for are: (, [, +, -, and /. The issue is most common with parenthesis (i.e. function brackets) and array literals.
51
Is the following code 1 or 2 statements? a = b ["r", "g", "b"].forEach(function (key) { background[key] = foreground[key] / 2; }
1 - because no semicolon was inserted after b, and because b[] is a valid statement, the JS engine did not add a semicolon - and this will cause an error.
52
Why might you a semicolon preceding a statement as in the following code? a = b var x ;(f());
If a programmer is using the 'auto semicolon' feature of JS - then it is pragmatic to add a semicolon in front of any of the "problematic" characters in JS. (i.e. the (, [, +, -, and / characters). This is to avoid errors that can be caused when the previous line and the current line inadvertently create a valid (but incorrect) statement.
53
When is the 'global object' created?
Whenever a JavaScript interpreter is started, for instance when a new page is loaded in a browser.
54
What is created as part of the 'global object'?
Definitions for NaN, undefined, Infinity, global functions such as isNaN, parseInt etc and constructor functions such as Date(), RegExp(), String(), Object(), and Array(). Also - objects such as Math and JSON
55
In client side JavaScript, what serves as the global object?
The window object Instead of using this - it has it's own self referential name, window.
56
A 'truthy' value converts to...
true
57
A 'falsy' value converts to...
false
58
In nested functions, what happens to variable scope?
Each function has it's own scope
59
In a function, if a variable is declared without the var keyword, what happens to it's scope?
It is essentially global. Even thought it was declared within a function, it can be accessed and called almost anywhere (even from within other functions).
60
A variable defined with var is...
non-configurable (i.e. can't be deleted with 'delete' keyword.)
61
JavaScript is a ............. scoped language?
lexically (i.e. the scope of the variable can be thought of as the set of source code lines for which the variable is defined)
62
In a top level non-nested function, what does the scope chain consist of?
Two objects, the function itself, with it's declared variables and parameters. And the global object and it's variables.
63
Normally you access properties using the . operator. If the property that you want to access on an object is not a valid name, or a reserved name, how do you access it?
You can also use the [] (square bracket) access notation - with the name in quotes.
64
What is an 'invocation expression'?
The typical format for calling (or invoking) a function. i.e. supermanfunction();
65
What is the order of evaluation when using 'invocation expressions'?
The function itself is evaluated first, then any argument expressions are evaluated, which allows a list of parameters to be build up.
66
If an invocation expression before the parenthesis contains an access operator, what does this mean?
It is a method invocation (i.e. a method on an object)
67
The object that method invocation is called on becomes...
the value of the 'this' operator within the method itself while the body of the function is being executed.
68
In a top level function (i.e. at root level), the 'this' operator contains a different value depending on whether the script is run in strict mode or not, what are the two options?
In ECMA script 5 - if strict mode is enabled, the 'this' operator is 'undefined' on a top level function. If it is not enabled, then it refers to the global object.
69
Most operators in JavaScript have left to right associativity. Which ones have Right to Left associativity?
unary, assignment and ternary conditional operators.
70
What does the unary (+/-) operators do?
Converts the value to a number (or NaN) and returns the value.
71
What is the difference between the bitwise operators >> and >>>
>> shifts right and preserves the sign, whereas >>> shifts right and zero fills from the left.
72
JavaScript objects are compare by...
reference, not value. (i.e. a JavaScript object is equal to itself, but not to any other object - even if they have identical properties).
73
When using the === (strict equality operator) are the following equal? null === null undefined === undefined
yes, they are both equal
74
If var1 is a string of "1" and var2 is a number of 1, are they equal when using the === operator?
No - the first step in the equality test when using the === operator is to determine if they are of the same type.
75
The "in" operator expects the left side to be a string (or something that can be converted to a string) - what is the right side?
An object.
76
When does the "in" operator evaluate to true?
When the string named in the left hand side is found as a property name on the object on the right hand side.
77
Given an object (MyObject) that is defined as { "1": "superman" }, would the following evaluate to true? 1 in MyObject
Yes - 1 would be converted to a string, which is in that object.
78
The "instanceof" operator expects the left hand side to be an object, the right hand side should be a....
class of objects
79
When evaluating an "instanceof" expression, what is checked on the object?
The prototype value. So if we are checking if O is an instance of F. We check F's F.prototype value, and then search for it in O's prototype chain. If it finds it - then O is either an instance or a superclass of F.
80
With logical operators you should avoid right hand side operators that...?
Have a side effect, as they may not always be called if the left hand operator is not truthy.
81
What is the following code doing? ``` function copy(o, p) { p = p || { }; } ```
It is applying default arguments to parameters. If the left hand side of the logical or expression is true, then it will assign that value to p. If it is not truthy, then it will receive an empty object.
82
Why is it a good idea to use the = within brackets when using it in large expressions?
= has very low precedence, you could get unexpected results if you don't use parenthesis.
83
If you pass a string to eval(), what does it do?
It tries to parse it as JavaScript.
84
If you pass anything other than a string to eval(), what does it do?
Returns that value.
85
What does typeof null return?
object
86
In general, typeof may return object for a number of different types, so what is a more pragmatic approach to determining an objects type?
Use instanceof
87
Does delete remove a property, or set it to undefined?
It completely removes the property - trying to access it will result in undefined, however, the test 'property' in MyObject, will return false - demonstrating it no longer exists on the object.
88
What is the 'void' operator?
It is a unary operator that evaluates it's operand, then discards the result. Only useful if the operand has a side effect, most commonly used in client side apps where you want to execute a command, but want the result suppressed.
89
What is the comma operator?
An operator ',' that evaluates the left hand operand, then the right hand operand, and discards the left hand result. Only really useful if the left hand operand has a side effect. Most commonly seen in for loops: for (i=0, j=10; i
90
What is a statement block?
``` A series of statements that are enclosed within braces. { // statements; } // NOTE: Doesn't end with a semi colon ```
91
Write a statement that initialises an array a[] to all 0's in one line.
for (i = 0; i
92
If a variable is defined with the declaration operator 'var' can you use delete on it?
No - it will not give an error, but the variable will not be deleted either.
93
Can you declare a variable in a for loop with var?
Yes
94
Can you use var to declare the same variable more than once?
Yes - there is no issue with this (although limited use).
95
Functions can be declared within other functions, but can a function be declared within an if statement within the function?
No - it must be at the top level, not in an if, or while or other statement. NOTE: It can be nested within another function, it also wont throw an error unless in strict mode.
96
Whats the difference between a function declaration statement and a function definition expressions?
Function declaration statements include a function name.
97
Are function declaration statements hoisted?
Yes, like var variables, they are hoisted to the top of the script or function.
98
Can switch statements be used with strings?
Yes - you can do something like: switch(typeof x) { case 'number'; break; }
99
What is the format for the JavaScript for / in loop?
for (variable in object) | statement;
100
How do you label a statement?
mylabel: while() { }
101
What is the purpose of labelling a statement?
It allows you to jump to that label using a jump statement. i.e. mylabel: while() { continue mylabel; }
102
Can the 'break' statement use labels?
yes. break mylabel;
103
Can the break statement pass control over function boundaries?
No.
104
What is wrong with the following statement? function foobar() { ``` return result_from_this_function(); } ```
JavaScript automatic semicolon insertion will insert one immediately after the return statement as there is a new line. This will not give intended results.
105
In a try/catch/finally block, when is the finally block executed?
When the try block reaches the end - either through a return/break/ or just exiting the try block. It is always executed regardless of what happens in the try block.
106
If there is an exception in the try block, but no local catch block, when is the finally block executed?
If there is no local catch, the code jumps from the try to the local finally block, which will be executed, then the control is passed to the nearest catch block.
107
What happens if, in the act of processing an exception, there is no local catch block, and the code jumps to the finally block (before jumping to the nearest containing catch block) - but an exception is thrown in that finally clause?
The compiler will abandon that current jump, and start the exception handling process again from that location.
108
What does the 'with' statement do? width(object) statement;
It adds 'object' to the front of the scope chain, and executes statement with that scope. It then resets the scope chain to how it was prior to the call. With essentially temporarily extends the scope chain.
109
What is the main problem with the 'with' statement?
It is forbidden in the 'use strict' mode, and it should be considered deprecated otherwise. It is difficult to optimise, and may run slower than code that doesn't use it.
110
The 'with' statement is often used to reduce the amount of typing required when dealing with deeply nested objects, what would be another way of doing this without with? ``` with(myobjects.list[0]) { // Do things in the scope of myobjects.list[0] console.log(getName()); } ```
You could simply assign the longer version of the variable to a new variable. ``` var obj = myobjects.list[0]; console.log(obj.getName()); ```
111
What does the debugger statement do?
It essentially works as a break point - it is specified in ECMA Script 5, but not all vendors implement it equally. You must have a debugger open in order for it to trigger.
112
Is "use strict" a statement?
No, it is a directive.
113
Where must the "use strict" statement appear?
At beginning of a file, or a function block.
114
In strict mode, the with statement is...
not allowed.
115
In strict mode, all variables must be...
declared
116
In strict mode, functions invoked as functions (instead of methods) have a this value set to...
undefined
117
In strict mode, the this value (when used with call, or apply) is...
strictly the value passed as the first parameter to call or apply.
118
In strict mode, assignments to non-writable properties result in....
TypeError
119
In strict mode, attempts to create new properties on non-extensible objects throw...
TypeError
120
In strict mode, code passed to eval cannot declare or define functions in...
the callers scope
121
In strict mode, declaring two or more parameters with the same name is...
a syntax error.
122
In strict mode, declaring two more properties on an object literal is...
a syntax error.
123
In strict mode, octal literals (an integer that begins with 0 and is not followed by an x) are...
not allowed
124
In strict mode, eval() and arguments() are treated as...
keywords, and you are not allowed to change their values
125
Any value in JavaScript that is not a number, string, true, false, null or undefined is...
an object
126
Even though strings, numbers and booleans are not objects, they behave like...
immutable objects
127
The enumerable attribute specifies whether...
It's name is returned in a for loop
128
The writable attribute specifies whether...
the value of the property can be set
129
The configurable attribute specifies whether...
The property can be deleted and whether it's attributes can be altered.
130
Every object has three associated object properties, what are they?
``` Prototype - the objects prototype Class - a string defining the objects class extensible - whether new properties can be added to the object ```
131
What is a host-object?
An object provided by the client (web browser) environment.
132
Can you create a new object from an object literal?
No - an object literal is it's own variable, calling new on it will result in an error. The error will be something like 'object is not a function'.
133
The new operator must be followed by a...
function invocation
134
Are these equivalent? object.foobar object["foobar"]
Yes
135
Is it an error to try and query a property that does not exist on an object?
No - but it will return undefined
136
Is it an error to try and query a property on an object that does not exist?
Yes - this is an error, it should raise a TypeError
137
If you are unsure if a property of an object is an object itself, you may cause an error trying to access it - how would you write a test for this that is failsafe? Object book with subobject stats. (Take advantage of JS's short circuiting behavior).
var length = book && book.stats && book.stats.length; If book is an object, and book.stats is an object, then assign the property length from book.stats.length to the variable length.
138
Can delete remove inherited properties?
No - if you want to do this, you must try to remove it from the prototype.
139
If a property has an attribute of configurable set to false, can it be removed using delete?
No.
140
Can delete be used to remove a configurable property on a non-extensible object?
Yes
141
In strict mode, the following may fail: delete x; What should it be?
delete this.x;
142
What function can be used to determine if a property belongs to the object?
object.hasOwnProperty(nameofproperty);
143
What is the difference between: myObject.hasOwnProperty('x'); and 'x' in myObject
hasOwnProperty checks to see if THAT object has that property. In will check both the object and the prototype chain.
144
isPropertyEnumerable returns true if...
the property is enumerable AND is an own property. It is a refinement on hasOwnProperty.
145
You can usually get away with testing a property against !== undefined. However, there is one thing the !== can't do, that the 'in' operator can do - what is that?
It can differentiate between a property that doesn't exist and one that exists but has been set to undefined.
146
what is one way you could retrieve all of the property names on an object?
Object.getOwnPropertyNames(myObject);
147
Given an array of var a = [1, 2, 3, 4, 5], how could you turn this into a string "1 2 3 4 5".
var newstring = a.join(" ");
148
How would you create a string of 24 hyphens using Array.join?
``` myArray = new Array(24); myArray.join("-"); ```
149
How would you go about reversing an array?
``` var myArray = [1, 3, 4, 5, 6, 7]; myArray.reverse(); ``` // NOTE: reverse does it in place, does not create a new array
150
What function can be used to sort an array?
Array.sort()
151
How is an array sort performed?
Alphabetical order, will convert values to strings if necessary.
152
How would you sort an array numerically?
``` var myarray = [1111, 22, 333, 55555]; myarray.sort(function(a, b) { return a - b; }); ```
153
What Array function can be used to concatenate an array?
Array.concat // NOTE: Does not do concatenation in place
154
What is the gotcha with Array.concat and nested arrays?
It does not recursively concatenate arrays
155
What would be the result of: var a = [1, 2, 3]; a.concat(4, [5, [6, 7]]);
[1, 2, 3, 4, 5, [6, 7]]
156
How could you return the first three elements of an array 'a'?
a.slice(0, 3);
157
For array a[1, 2, 3, 4, 5] what would a.slice(3) return?
[4, 5]
158
For array a[1, 2, 3, 4, 5] what would a.slice(1, -1) return?
[2, 3, 4] -1 in the last parameter specifies the last element of the array (i.e. 1 from the end)
159
Which out of slice, splice and concat modifies the original array?
only splice
160
given an array a[1, 2, 3, 4, 5], what would a.splice(2) do?
returns an array [3, 4, 5], and leaves the array 'a' looking like [1, 2]
161
What function can be used to insert arrays into another array?
splice
162
push and pop are array functions that implement a stack like system. What two functions perform the same functionality, but from the opposite end of the array?
shift / unshift
163
What array method can be used to apply a function to each element in an array?
Array.forEach()
164
What is the one caveat with the forEach method?
There is no equivalent of the 'break' statement, so it will visit all elements of the array.
165
What is an alternate function to forEach that can be used to apply a function to each element of an array?
Array.map();
166
What array method can be used to remove elements from an array based on a predicate function?
Array.filter(); The function you pass to filter should be predicate - i.e. return true or false.
167
What does the 'Array.every' method do?
You can pass it a predicate function (that returns true/false) - if all elements of the array pass (i.e. are true), then Array.every will return true. Useful for determining if all elements in an array satisfy a condition.
168
What does the 'Array.some' method do?
You can pass it a predicate function (that returns true/false). If any (i.e. some) of the elements of the array pass the test, it will return true.
169
How would you find the index of a specific array element?
a = [0, 2, 3, 1, 4]; a.indexOf(1); // Returns 3
170
What is the difference between the indexOf and lastIndexOf methods?
lastIndexOf starts at the end of the array.
171
Arrays are not the only place that indexOf and lastIndexOf appear - where else can they be used?
Strings
172
What function can you use to determine if an array is an array?
Array.isArray();
173
If an object is not extensible, you can edit its existing properties, but...
You cannot add new properties to it.
174
If a property is not configurable, you cannot change its...
Configurable or enumerable attributes..
175
If an accessor property is not configurable, you cannot change its...
Getter and setter method, and you cannot change it to a data property.
176
If a data property is not configurable, you cannot change it to...
An accessor property
177
If a data property isnot configurable, you cannot change its writable attribute from false to true, but you can change it to...
True to false
178
If a data property is not configurable and not writable, you cannot change...
It's value
179
How do you get a list of property names from an object?
Object.getOwnPropertyNames(myObject);
180
How would you define a new property on an existing object?
Object.defineProperty(myObject, propertyName, propertyDesc);
181
What attributes do objects have?
Prototype Class Extensible
182
Objects created with new use the value of their prototype property of their...
Constructor function
183
How can you get the prototype of an object in ECMA Script 5?
Object.getPrototypeOf(object);
184
What function can you use to determine if an object is a prototype of another object?
myObject.isPrototypeOf(o);
185
Is the class property of an object configurable?
No - there is no way to get to it, however, toString should print the value of it [Object class]
186
The 'extensible' property on an object defines whether...
A new property can be added to it.
187
How do make an object 'extensible'?
Pass it to Object.isExtensible();
188
How do you make an object not 'extensible'?
Pass it to Object.preventExtensions()
189
Once an object is marked as non extensible, how do you mark it 'extensible' again?
You can't - it's a one way street bro.
190
What is odd about a non-extensible object?
You can still add properties to it's prototype no worries - extensible only applies to the actual object
191
The purpose of the 'extensible' object attribute is to prevent the object from being tampered with. What other function is useful for making an object non-extensible as well as preventing it's properties from being modified?
Object.seal()
192
What does Object.seal() do?
Makes the object non-extensible, but also sets all it's properties to non-configurable.
193
How do you determine if an object is sealed?
Object.isSealed();
194
Can you write to writable properties on a sealed object?
Yes
195
What does Object.freeze() do?
Like Object.seal(), it makes an object non-configurable, but makes all 'own' properties read-only (note - does not affect accessor methods).
196
What can you use to determine if an object is frozen?
Object.isFrozen()
197
What JavaScript functions can be used to serialize JavaScript objects?
JSON.parse() | JSON.stringify()
198
In JSON, what elements cannot be serialized or restored?
Function RegExp Error Objects
199
Does the toJSON function exist in the Object prototype?
No - but the JSON.stringify method will look for it - it's up to the developer to create their own to handle serialization if they need something specific.
200
Can JavaScript arrays have mixed types?
Yes, you can have [1.1, true, 'a'] for instance
201
If you omit an element in an array, what is it's value? (i.e. var a = [,,])
each ommited element is undefined
202
``` How many undefined elements would the following declaration have? var a = [, ,]; ```
Two - JavaScript arrays can have a trailing comma, so it would be interpreted as two elements
203
var a = new Array() is equivalent to...
var a = [];
204
How do you specify an array length at creation time?
var a = new Array(10);
205
If you try to access an array element that is out of bounds what error do you get?
You don't get an error, but undefined is returned.
206
If you create a sparse array with one element, but that element is at position 1000, what will array.length return?
1001
207
If you set length property of an array to a positive value less than the length of the current array length, what happens?
The array is shortened to the new length, the other elements are discarded.
208
If you have an array of length 10, and you make it array.length = 15; have you added new elements?
No - there are no new elements added to the array, but a sparse area at the end of the array has been added (i.e. you can't index those areas)
209
Can you make the length property of an array read-only?
Yes, using Object.defineProperty | Object.defineProperty(a, "length", {writable: false});
210
What is the equivalent of adding an element to an array with a[a.length]?
a.push();
211
What JavaScript statement can be used to delete an array element?
delete a[1];
212
If you delete elements from an array using delete, the array becomes...
sparse
213
Does deleting elements from an array shift the array elements up?
no
214
What is one problem with using array.length in a for loop?
It is looked up each iteration.
215
How can you optimise the a.length statement in a for loop?
for (i = 0, len = array.length; i
216
If your array is potentially sparse, and you want to skip undefined, null or non-existant elements, how would you do this?
In the for loop, use a conditional statement: | if (!a[i]) continue;
217
If you only want to skip undefined and non-existant array elements what conditional would you use?
if (a[i] === undefined) continue;
218
if you only want to skip indexes for which no array element exists what conditional would you use?
if (!(i in a)) continue;
219
Can you use the for / in loop with sparse arrays?
Yes, but non-existant elements will not be iterated.
220
What is the gotcha with using for/in loops on arrays?
``` The loop can return inherited properties, so you need to test that you are not about to process something you shouldn't for (var i in a) { if (!a.hasOwnProperty(i)) continue; // Loop body here } ```
221
Does javascript support multidimensional arrays?
No - but you can approximate them with arrays of arrays
222
How would you create a multidimensional array in JavaScript?
``` var table = new Array(10); for (var i = 0; i ```
223
Can JavaScript arrays be indexed like C arrays?
Yes - you can iterate through an array using the array index method
224
What is another way to index the second element of a string array, other than a[1]?
a.charAt(1);
225
What is the major difference between treating a string like an array in JavaScript compared with C?
In JavaScript, strings are immutable, so you can't modify the content of the array - it is readonly.
226
Do the functions push, sort, reverse and splice work on strings?
No.
227
When a function is invoked on or through an object, that object is known as the...
invocation context (or this value)
228
JavaScript functions can be defined within other functions, and have access to the variables in the scope they are defined - this means they can also be referred to as...
closures
229
Can a function expression define a function name?
Yes - var myfunc = function test() { }; This useful if the function needs to do recursion - internally, it can call itself by the name (test) - but a user will call it using myfunc();
230
Function definition expressions are particularly useful for functions that are only used...
once
231
Knowing that variables defined with var are hoisted, can you all this function in code before it is declared? var myfunc = function() { // Do stuff here };
No - while the variable is hoisted, the assignment itself is not, so it can only be called once the assignment has occurred in code.
232
Will the following produce an error? ``` function chicken() { myTest() }; var myTest = function() { console.log('Yo...'); }; chicken(); ```
No - despite the fact myTest is defined AFTER the call in chicken (and function statements aren't hoisted) - the actual call to chicken() happens after the assignment of the function statement to the variable myTest. myTest is hoisted already - and everything works fine. NOTE: The issue is not where the declaration occurs, rather, when it is called.
233
Will the following produce an error? ``` function chicken() { myTest() }; chicken(); var myTest = function() { console.log('Yo...'); }; ```
Yes. Despite myTest being hoisted, the assignment of the function statement occurs AFTER the call to chicken, which tries to access myTest (which is accessible due to hoisting) - but unfortunately the assignment of the function statement has not occurred yet.
234
A nest function can access the variables and parameters of the function that encloses it, true or false?
true - if you think about it, this is how JavaScript emulates objects (i.e. methods).
235
There are four ways a JavaScript function can be invoked, what are they?
As functions Methods Constructors Through their call() and apply() methods
236
What function could be written that could be used to determine if the code is running in strict mode?
var strict = (function() { return !this; })(); NOTE: We are using an IIFE, and the ! will make sure the value is boolean.
237
How would you implement method chaining in an API?
Make sure that functions that don't have their own return values, return the this object. That way you can invoke further methods on the object with the resulting object.
238
Can an inner function access the 'this' variable from it's context?
No - inner functions do not have access to a this variable. The best way to deal with this is to save a copy of the this variable at the outer level that it can access if required.
239
What is the likely object contained within this if it is invoked inside an inner function?
Depends on the mode of the script. If it is normal mode, then it will be the this for the global context. However, if it is in strict mode, then 'this' will be undefined for the inner function.
240
What is the difference between declaring a variable with var and without at global scope?
When you declare a variable using var, it gives the variable attributes. One of these attributes is the DontDelete flag - so a variable declared with var can't be deleted, the one without var (and hence no properties) can be deleted.
241
What is the difference between declaring a variable with var and without at function scope?
At function scope a variable declared without var with search the scope chain until it can find a variable with teh same name. If it can, it will assign the value to that variable. If it can't it will create a new variable. Therefore it's possible to create global variables at the function scope.
242
What is function currying?
It is where a function that uses one or more arguments is returned with some of the arguments pre-set.
243
Function currying is also known as....
partial function application
244
What JavaScript function is usually used to implement currying.
bind()
245
Javascript functions can be declared as a function statement, or a function literal - how else can they be declared?
Function constructor - i.e. var myfunc = new Function(x, y, "return x * y;" );
246
What are some differences in the way functions operate when created using the Function constructor?
The body of the function is parsed each time, and creates a new function object each time it's called. It allows functions to be dynamically created at runtime. Functions created using function constructors do not use lexical scoping, instead they are compiled as if they are always top level functions.
247
Why should you not write code based on the callability of RegExp objects?
Because it is a non-standard feature and will likely be deprecated.
248
What is a higher order function?
A function that operates on functions.
249
Duck typing de-emphasises object ..... over object .....
object type, over object capability
250
In JavaScript the definitive guide, an example requires that we pass a pointer to the log object: r.foreach(console.log); But this gives an error "Uncaught TypeError: Illegal Invocation". What is the problem here?
The .log method is effectively detached from the console object when it is executed within the 'foreach' method found in r. You need to bind the console object to it - so it has the right 'this' parameter. r.foreach(console.log.bind(console));
251
Functions written as constructors usually wont work as normal functions - true or false?
True - mainly because most of the variables are declared using the this keyword - which is only set when new is called on the constructor.
252
If we have a test for object type like such: r instanceof Range What is it testing?
It's not testing whether the r object is instantiated by the Range constructor - rather it is testing whether r.prototype is equal to prototype of Range.
253
All ECMA script 5 functions have a prototype property except on type - what is that?
Functions returned by bind()
254
Does the constructor property belong to the constructor Function, or as a property of the prototype?
As a property of the prototype
255
What happens to the prototype.constructor property if you define your own prototype for an object?
It is lost, and you must add it yourself.
256
Is there any difference between creating an prototype object with methods, and assigning it to the prototype field of an object - or directly assigning functions to the constructors prototype? (i.e. Range.prototype.foobar = function() {};
No - they are equivalent. However, when doing this you do not explicitly need to point the prototype objects constructor property at the constructor. This is because by adding the functions individually, instead of replacing the whole object, you are leaving the constructor property intact.
257
What are the three different objects involved in JavaScript class definitions?
Prototype Object Constructor Object Instance Object