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
Q

Objects are coerced to number via…

A

valueOf

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

Objects are coerced to strings via…

A

toString

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

Objects with a valueOf method should provide a toString method that does what?

A

Returns a string representation of the number generated by valueOf

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

Rather than using ‘truthiness’ for testing undefined values, what should you use?

A

typeof or comparison to ‘undefined’.

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

What is different between the ECMA script standard and Javascript in regards to how ‘null’ is reported by the operator ‘typeof’?

A

According to the standard null should be it’s own type, however Javascript reports null as an object.

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

What are the five primitive types in Javascript?

A
booleans,
numbers,
strings,
null,
undefined
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Strings are primitive types in Javascript, and yet you can create a string using new. Why?

var string = new String(‘superstring’);

A

This is a ‘boxed’ type - it’s a string wrapped in an object.

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

A

true
true

The object is coerced to a string.

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

A

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

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

What is the result of the following?

“hello”.newProperty = 10;
console.log(“hello”.newProperty);

And why?

A

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.

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

Getting and setting properties on primitives does what?

A

Implicitly creates an object wrapper.

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

Object wrappers have the same behavior as their primitive types when testing for equality - true or false?

A

False - they do not behave in the same way - making it difficult to compare values when using the object wrappers.

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

Is using the == operator okay with mixed types?

A

You should avoid using it with mixed types.

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

When reading data from a form, should you just use coercion to test for equality?

A

No - use Number or the unary + operator to convert to a true number before testing.

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

When values are of the same type - is there any difference between the == and === operators?

A

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.

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

What coercion takes place when you have:

null == undefined

A

None; always true

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

What coercion takes place when you have

null or undefined == anything other than null or undefined

A

None: always false

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

What coercion takes place when you have

Primitive String, Number, Boolean == Date Object

A

Primitive => number

Date Object => Primitive (first try toString, then valueOf)

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

What coercion takes place when you have

Primitive String, Number, Boolean == Non Date Object

A

Primitive => number

Non Date Object => Primitive (first try valueOf, then toString)

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

What coercion takes place when you have

Primitive String, Number, Boolean == Primitive String, Number, Boolean

A

Primitive => number

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

What is a good rule of thumb with regards to using the == operator for things like dates?

A

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.

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

Semi colons are only ever inserted…

A

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.

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

Is the following legal code?

function area(r) { r = +r return Math.PI * r * r }

A

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.

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

Is a semicolon added in this context?

a = b
f();

A

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().

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

Is a semicolon added in this context?

a = b
(f());

A

No - because:

a = b(f());

is valid code - a semicolon would not be required.

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

Even if you are not deliberately using semi-colon completion functionality - it can hide or cause some weird errors - why is that?

A

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.

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

Is the following code 1 or 2 statements?

a = b
[“r”, “g”, “b”].forEach(function (key) {
background[key] = foreground[key] / 2;
}

A

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.

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

Why might you a semicolon preceding a statement as in the following code?

a = b
var x
;(f());

A

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.

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

When is the ‘global object’ created?

A

Whenever a JavaScript interpreter is started, for instance when a new page is loaded in a browser.

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

What is created as part of the ‘global object’?

A

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

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

In client side JavaScript, what serves as the global object?

A

The window object

Instead of using this - it has it’s own self referential name, window.

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

A ‘truthy’ value converts to…

A

true

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

A ‘falsy’ value converts to…

A

false

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

In nested functions, what happens to variable scope?

A

Each function has it’s own scope

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

In a function, if a variable is declared without the var keyword, what happens to it’s scope?

A

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

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

A variable defined with var is…

A

non-configurable (i.e. can’t be deleted with ‘delete’ keyword.)

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

JavaScript is a …………. scoped language?

A

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)

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

In a top level non-nested function, what does the scope chain consist of?

A

Two objects, the function itself, with it’s declared variables and parameters. And the global object and it’s variables.

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

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?

A

You can also use the [] (square bracket) access notation - with the name in quotes.

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

What is an ‘invocation expression’?

A

The typical format for calling (or invoking) a function. i.e. supermanfunction();

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

What is the order of evaluation when using ‘invocation expressions’?

A

The function itself is evaluated first, then any argument expressions are evaluated, which allows a list of parameters to be build up.

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

If an invocation expression before the parenthesis contains an access operator, what does this mean?

A

It is a method invocation (i.e. a method on an object)

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

The object that method invocation is called on becomes…

A

the value of the ‘this’ operator within the method itself while the body of the function is being executed.

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

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?

A

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.

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

Most operators in JavaScript have left to right associativity. Which ones have Right to Left associativity?

A

unary, assignment and ternary conditional operators.

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

What does the unary (+/-) operators do?

A

Converts the value to a number (or NaN) and returns the value.

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

What is the difference between the bitwise operators&raquo_space; and&raquo_space;>

A

> > shifts right and preserves the sign, whereas&raquo_space;> shifts right and zero fills from the left.

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

JavaScript objects are compare by…

A

reference, not value. (i.e. a JavaScript object is equal to itself, but not to any other object - even if they have identical properties).

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

When using the === (strict equality operator) are the following equal?
null === null
undefined === undefined

A

yes, they are both equal

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

If var1 is a string of “1” and var2 is a number of 1, are they equal when using the === operator?

A

No - the first step in the equality test when using the === operator is to determine if they are of the same type.

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

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?

A

An object.

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

When does the “in” operator evaluate to true?

A

When the string named in the left hand side is found as a property name on the object on the right hand side.

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

Given an object (MyObject) that is defined as { “1”: “superman” }, would the following evaluate to true?

1 in MyObject

A

Yes - 1 would be converted to a string, which is in that object.

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

The “instanceof” operator expects the left hand side to be an object, the right hand side should be a….

A

class of objects

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

When evaluating an “instanceof” expression, what is checked on the object?

A

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.

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

With logical operators you should avoid right hand side operators that…?

A

Have a side effect, as they may not always be called if the left hand operator is not truthy.

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

What is the following code doing?

function copy(o, p) {
   p = p || { };
}
A

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.

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

Why is it a good idea to use the = within brackets when using it in large expressions?

A

= has very low precedence, you could get unexpected results if you don’t use parenthesis.

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

If you pass a string to eval(), what does it do?

A

It tries to parse it as JavaScript.

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

If you pass anything other than a string to eval(), what does it do?

A

Returns that value.

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

What does typeof null return?

A

object

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

In general, typeof may return object for a number of different types, so what is a more pragmatic approach to determining an objects type?

A

Use instanceof

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

Does delete remove a property, or set it to undefined?

A

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.

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

What is the ‘void’ operator?

A

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.

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

What is the comma operator?

A

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

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

What is a statement block?

A
A series of statements that are enclosed within braces.
{
  // statements;
} // NOTE: Doesn't end with a semi colon
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
91
Q

Write a statement that initialises an array a[] to all 0’s in one line.

A

for (i = 0; i

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

If a variable is defined with the declaration operator ‘var’ can you use delete on it?

A

No - it will not give an error, but the variable will not be deleted either.

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

Can you declare a variable in a for loop with var?

A

Yes

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

Can you use var to declare the same variable more than once?

A

Yes - there is no issue with this (although limited use).

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

Functions can be declared within other functions, but can a function be declared within an if statement within the function?

A

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.

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

Whats the difference between a function declaration statement and a function definition expressions?

A

Function declaration statements include a function name.

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

Are function declaration statements hoisted?

A

Yes, like var variables, they are hoisted to the top of the script or function.

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

Can switch statements be used with strings?

A

Yes - you can do something like:

switch(typeof x) {
case ‘number’;
break;
}

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

What is the format for the JavaScript for / in loop?

A

for (variable in object)

statement;

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

How do you label a statement?

A

mylabel: while() {

}

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

What is the purpose of labelling a statement?

A

It allows you to jump to that label using a jump statement. i.e.

mylabel: while() {
continue mylabel;
}

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

Can the ‘break’ statement use labels?

A

yes.

break mylabel;

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

Can the break statement pass control over function boundaries?

A

No.

104
Q

What is wrong with the following statement?

function foobar() {

   return 
   result_from_this_function();
}
A

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
Q

In a try/catch/finally block, when is the finally block executed?

A

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
Q

If there is an exception in the try block, but no local catch block, when is the finally block executed?

A

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
Q

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?

A

The compiler will abandon that current jump, and start the exception handling process again from that location.

108
Q

What does the ‘with’ statement do?

width(object)
statement;

A

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
Q

What is the main problem with the ‘with’ statement?

A

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
Q

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());
}
A

You could simply assign the longer version of the variable to a new variable.

var obj = myobjects.list[0];
console.log(obj.getName());
111
Q

What does the debugger statement do?

A

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
Q

Is “use strict” a statement?

A

No, it is a directive.

113
Q

Where must the “use strict” statement appear?

A

At beginning of a file, or a function block.

114
Q

In strict mode, the with statement is…

A

not allowed.

115
Q

In strict mode, all variables must be…

A

declared

116
Q

In strict mode, functions invoked as functions (instead of methods) have a this value set to…

A

undefined

117
Q

In strict mode, the this value (when used with call, or apply) is…

A

strictly the value passed as the first parameter to call or apply.

118
Q

In strict mode, assignments to non-writable properties result in….

A

TypeError

119
Q

In strict mode, attempts to create new properties on non-extensible objects throw…

A

TypeError

120
Q

In strict mode, code passed to eval cannot declare or define functions in…

A

the callers scope

121
Q

In strict mode, declaring two or more parameters with the same name is…

A

a syntax error.

122
Q

In strict mode, declaring two more properties on an object literal is…

A

a syntax error.

123
Q

In strict mode, octal literals (an integer that begins with 0 and is not followed by an x) are…

A

not allowed

124
Q

In strict mode, eval() and arguments() are treated as…

A

keywords, and you are not allowed to change their values

125
Q

Any value in JavaScript that is not a number, string, true, false, null or undefined is…

A

an object

126
Q

Even though strings, numbers and booleans are not objects, they behave like…

A

immutable objects

127
Q

The enumerable attribute specifies whether…

A

It’s name is returned in a for loop

128
Q

The writable attribute specifies whether…

A

the value of the property can be set

129
Q

The configurable attribute specifies whether…

A

The property can be deleted and whether it’s attributes can be altered.

130
Q

Every object has three associated object properties, what are they?

A
Prototype - the objects prototype
Class - a string defining the objects class
extensible - whether new properties can be added to the object
131
Q

What is a host-object?

A

An object provided by the client (web browser) environment.

132
Q

Can you create a new object from an object literal?

A

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
Q

The new operator must be followed by a…

A

function invocation

134
Q

Are these equivalent?

object.foobar
object[“foobar”]

A

Yes

135
Q

Is it an error to try and query a property that does not exist on an object?

A

No - but it will return undefined

136
Q

Is it an error to try and query a property on an object that does not exist?

A

Yes - this is an error, it should raise a TypeError

137
Q

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

A

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
Q

Can delete remove inherited properties?

A

No - if you want to do this, you must try to remove it from the prototype.

139
Q

If a property has an attribute of configurable set to false, can it be removed using delete?

A

No.

140
Q

Can delete be used to remove a configurable property on a non-extensible object?

A

Yes

141
Q

In strict mode, the following may fail:

delete x;

What should it be?

A

delete this.x;

142
Q

What function can be used to determine if a property belongs to the object?

A

object.hasOwnProperty(nameofproperty);

143
Q

What is the difference between:

myObject.hasOwnProperty(‘x’);
and
‘x’ in myObject

A

hasOwnProperty checks to see if THAT object has that property. In will check both the object and the prototype chain.

144
Q

isPropertyEnumerable returns true if…

A

the property is enumerable AND is an own property. It is a refinement on hasOwnProperty.

145
Q

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?

A

It can differentiate between a property that doesn’t exist and one that exists but has been set to undefined.

146
Q

what is one way you could retrieve all of the property names on an object?

A

Object.getOwnPropertyNames(myObject);

147
Q

Given an array of var a = [1, 2, 3, 4, 5], how could you turn this into a string “1 2 3 4 5”.

A

var newstring = a.join(“ “);

148
Q

How would you create a string of 24 hyphens using Array.join?

A
myArray = new Array(24);
myArray.join("-");
149
Q

How would you go about reversing an array?

A
var myArray = [1, 3, 4, 5, 6, 7];
myArray.reverse();

// NOTE: reverse does it in place, does not create a new array

150
Q

What function can be used to sort an array?

A

Array.sort()

151
Q

How is an array sort performed?

A

Alphabetical order, will convert values to strings if necessary.

152
Q

How would you sort an array numerically?

A
var myarray = [1111, 22, 333, 55555];
myarray.sort(function(a, b) {
  return a - b;
});
153
Q

What Array function can be used to concatenate an array?

A

Array.concat

// NOTE: Does not do concatenation in place

154
Q

What is the gotcha with Array.concat and nested arrays?

A

It does not recursively concatenate arrays

155
Q

What would be the result of:
var a = [1, 2, 3];
a.concat(4, [5, [6, 7]]);

A

[1, 2, 3, 4, 5, [6, 7]]

156
Q

How could you return the first three elements of an array ‘a’?

A

a.slice(0, 3);

157
Q

For array a[1, 2, 3, 4, 5] what would a.slice(3) return?

A

[4, 5]

158
Q

For array a[1, 2, 3, 4, 5] what would a.slice(1, -1) return?

A

[2, 3, 4]

-1 in the last parameter specifies the last element of the array (i.e. 1 from the end)

159
Q

Which out of slice, splice and concat modifies the original array?

A

only splice

160
Q

given an array a[1, 2, 3, 4, 5], what would a.splice(2) do?

A

returns an array [3, 4, 5], and leaves the array ‘a’ looking like [1, 2]

161
Q

What function can be used to insert arrays into another array?

A

splice

162
Q

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?

A

shift / unshift

163
Q

What array method can be used to apply a function to each element in an array?

A

Array.forEach()

164
Q

What is the one caveat with the forEach method?

A

There is no equivalent of the ‘break’ statement, so it will visit all elements of the array.

165
Q

What is an alternate function to forEach that can be used to apply a function to each element of an array?

A

Array.map();

166
Q

What array method can be used to remove elements from an array based on a predicate function?

A

Array.filter();

The function you pass to filter should be predicate - i.e. return true or false.

167
Q

What does the ‘Array.every’ method do?

A

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
Q

What does the ‘Array.some’ method do?

A

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
Q

How would you find the index of a specific array element?

A

a = [0, 2, 3, 1, 4];
a.indexOf(1);
// Returns 3

170
Q

What is the difference between the indexOf and lastIndexOf methods?

A

lastIndexOf starts at the end of the array.

171
Q

Arrays are not the only place that indexOf and lastIndexOf appear - where else can they be used?

A

Strings

172
Q

What function can you use to determine if an array is an array?

A

Array.isArray();

173
Q

If an object is not extensible, you can edit its existing properties, but…

A

You cannot add new properties to it.

174
Q

If a property is not configurable, you cannot change its…

A

Configurable or enumerable attributes..

175
Q

If an accessor property is not configurable, you cannot change its…

A

Getter and setter method, and you cannot change it to a data property.

176
Q

If a data property is not configurable, you cannot change it to…

A

An accessor property

177
Q

If a data property isnot configurable, you cannot change its writable attribute from false to true, but you can change it to…

A

True to false

178
Q

If a data property is not configurable and not writable, you cannot change…

A

It’s value

179
Q

How do you get a list of property names from an object?

A

Object.getOwnPropertyNames(myObject);

180
Q

How would you define a new property on an existing object?

A

Object.defineProperty(myObject, propertyName, propertyDesc);

181
Q

What attributes do objects have?

A

Prototype
Class
Extensible

182
Q

Objects created with new use the value of their prototype property of their…

A

Constructor function

183
Q

How can you get the prototype of an object in ECMA Script 5?

A

Object.getPrototypeOf(object);

184
Q

What function can you use to determine if an object is a prototype of another object?

A

myObject.isPrototypeOf(o);

185
Q

Is the class property of an object configurable?

A

No - there is no way to get to it, however, toString should print the value of it [Object class]

186
Q

The ‘extensible’ property on an object defines whether…

A

A new property can be added to it.

187
Q

How do make an object ‘extensible’?

A

Pass it to Object.isExtensible();

188
Q

How do you make an object not ‘extensible’?

A

Pass it to Object.preventExtensions()

189
Q

Once an object is marked as non extensible, how do you mark it ‘extensible’ again?

A

You can’t - it’s a one way street bro.

190
Q

What is odd about a non-extensible object?

A

You can still add properties to it’s prototype no worries - extensible only applies to the actual object

191
Q

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?

A

Object.seal()

192
Q

What does Object.seal() do?

A

Makes the object non-extensible, but also sets all it’s properties to non-configurable.

193
Q

How do you determine if an object is sealed?

A

Object.isSealed();

194
Q

Can you write to writable properties on a sealed object?

A

Yes

195
Q

What does Object.freeze() do?

A

Like Object.seal(), it makes an object non-configurable, but makes all ‘own’ properties
read-only (note - does not affect accessor methods).

196
Q

What can you use to determine if an object is frozen?

A

Object.isFrozen()

197
Q

What JavaScript functions can be used to serialize JavaScript objects?

A

JSON.parse()

JSON.stringify()

198
Q

In JSON, what elements cannot be serialized or restored?

A

Function
RegExp
Error Objects

199
Q

Does the toJSON function exist in the Object prototype?

A

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
Q

Can JavaScript arrays have mixed types?

A

Yes, you can have [1.1, true, ‘a’] for instance

201
Q

If you omit an element in an array, what is it’s value? (i.e. var a = [,,])

A

each ommited element is undefined

202
Q
How many undefined elements would the following declaration have?
var a = [, ,];
A

Two - JavaScript arrays can have a trailing comma, so it would be interpreted as two elements

203
Q

var a = new Array() is equivalent to…

A

var a = [];

204
Q

How do you specify an array length at creation time?

A

var a = new Array(10);

205
Q

If you try to access an array element that is out of bounds what error do you get?

A

You don’t get an error, but undefined is returned.

206
Q

If you create a sparse array with one element, but that element is at position 1000, what will array.length return?

A

1001

207
Q

If you set length property of an array to a positive value less than the length of the current array length, what happens?

A

The array is shortened to the new length, the other elements are discarded.

208
Q

If you have an array of length 10, and you make it array.length = 15; have you added new elements?

A

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
Q

Can you make the length property of an array read-only?

A

Yes, using Object.defineProperty

Object.defineProperty(a, “length”, {writable: false});

210
Q

What is the equivalent of adding an element to an array with a[a.length]?

A

a.push();

211
Q

What JavaScript statement can be used to delete an array element?

A

delete a[1];

212
Q

If you delete elements from an array using delete, the array becomes…

A

sparse

213
Q

Does deleting elements from an array shift the array elements up?

A

no

214
Q

What is one problem with using array.length in a for loop?

A

It is looked up each iteration.

215
Q

How can you optimise the a.length statement in a for loop?

A

for (i = 0, len = array.length; i

216
Q

If your array is potentially sparse, and you want to skip undefined, null or non-existant elements, how would you do this?

A

In the for loop, use a conditional statement:

if (!a[i]) continue;

217
Q

If you only want to skip undefined and non-existant array elements what conditional would you use?

A

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

218
Q

if you only want to skip indexes for which no array element exists what conditional would you use?

A

if (!(i in a)) continue;

219
Q

Can you use the for / in loop with sparse arrays?

A

Yes, but non-existant elements will not be iterated.

220
Q

What is the gotcha with using for/in loops on arrays?

A
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
Q

Does javascript support multidimensional arrays?

A

No - but you can approximate them with arrays of arrays

222
Q

How would you create a multidimensional array in JavaScript?

A
var table = new Array(10);
for (var i = 0; i
223
Q

Can JavaScript arrays be indexed like C arrays?

A

Yes - you can iterate through an array using the array index method

224
Q

What is another way to index the second element of a string array, other than a[1]?

A

a.charAt(1);

225
Q

What is the major difference between treating a string like an array in JavaScript compared with C?

A

In JavaScript, strings are immutable, so you can’t modify the content of the array - it is readonly.

226
Q

Do the functions push, sort, reverse and splice work on strings?

A

No.

227
Q

When a function is invoked on or through an object, that object is known as the…

A

invocation context (or this value)

228
Q

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…

A

closures

229
Q

Can a function expression define a function name?

A

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
Q

Function definition expressions are particularly useful for functions that are only used…

A

once

231
Q

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 };

A

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
Q

Will the following produce an error?

function chicken() { myTest() };
var myTest = function() { console.log('Yo...'); };
chicken();
A

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
Q

Will the following produce an error?

function chicken() { myTest() };
chicken();
var myTest = function() { console.log('Yo...'); };
A

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
Q

A nest function can access the variables and parameters of the function that encloses it, true or false?

A

true - if you think about it, this is how JavaScript emulates objects (i.e. methods).

235
Q

There are four ways a JavaScript function can be invoked, what are they?

A

As functions
Methods
Constructors
Through their call() and apply() methods

236
Q

What function could be written that could be used to determine if the code is running in strict mode?

A

var strict = (function() { return !this; })();

NOTE: We are using an IIFE, and the ! will make sure the value is boolean.

237
Q

How would you implement method chaining in an API?

A

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
Q

Can an inner function access the ‘this’ variable from it’s context?

A

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
Q

What is the likely object contained within this if it is invoked inside an inner function?

A

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
Q

What is the difference between declaring a variable with var and without at global scope?

A

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
Q

What is the difference between declaring a variable with var and without at function scope?

A

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
Q

What is function currying?

A

It is where a function that uses one or more arguments is returned with some of the arguments pre-set.

243
Q

Function currying is also known as….

A

partial function application

244
Q

What JavaScript function is usually used to implement currying.

A

bind()

245
Q

Javascript functions can be declared as a function statement, or a function literal - how else can they be declared?

A

Function constructor - i.e.

var myfunc = new Function(x, y, “return x * y;” );

246
Q

What are some differences in the way functions operate when created using the Function constructor?

A

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
Q

Why should you not write code based on the callability of RegExp objects?

A

Because it is a non-standard feature and will likely be deprecated.

248
Q

What is a higher order function?

A

A function that operates on functions.

249
Q

Duck typing de-emphasises object ….. over object …..

A

object type, over object capability

250
Q

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?

A

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
Q

Functions written as constructors usually wont work as normal functions - true or false?

A

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
Q

If we have a test for object type like such:

r instanceof Range

What is it testing?

A

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
Q

All ECMA script 5 functions have a prototype property except on type - what is that?

A

Functions returned by bind()

254
Q

Does the constructor property belong to the constructor Function, or as a property of the prototype?

A

As a property of the prototype

255
Q

What happens to the prototype.constructor property if you define your own prototype for an object?

A

It is lost, and you must add it yourself.

256
Q

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() {};

A

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
Q

What are the three different objects involved in JavaScript class definitions?

A

Prototype Object
Constructor Object
Instance Object