JavaScript 4 Flashcards

1
Q

What is the simplest way to modularize your code?

A

Use the namespace pattern - to contain all of your modules. This works by creating a root object (the root namespace) and adding modules (new objects) corresponding to the nesting namespace.

PlayerJS.player.controller
singleton/module name/object
Object / Object / IIFE

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

How do you make namespaces in JS?

A

The easiest way is to create a global object (at the document root) that is a singleton.

Then you can use a directory structure to store the files (naming the directories after the modules). The directory names are the same as the module (object) names within the root / singleton. Modules are created by calling an IIFE. The resulting modules have methods which can be called.

EG:

PlayerJS.player.controller.play();
singleton/module name/object/method
Object / Object / IIFE / Method

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

What does AMD stand for?

A

Asynchronous Module Definition

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

What is the downsides to using the Namespace pattern?

A

Declaring modules as global variables
Can’t specify the dependencies of a module
Have to list script files in order in the index.html

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

What library is used to help implement AMD?

A

Require.js

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

When using React, how do you specify dependencies?

A

define([‘player/controller’], function(Player, Controller) {

});

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

If you don’t have dependencies, what do you declare in ReactJS?

A

You specify an empty array.

define([], function() {});

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

When using ReactJS, what is one of the risks we have to look out for when setting up dependencies?

A

Circular dependencies

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

What pattern can be used to allow communication between modules that have been setup using the AMD pattern?

A

PubSub

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

What is another name for the Pub Sub pattern?

A

Observer

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

Why might you use the tilde ~ character in an if expression?

A

The tilde character will convert the value to a truthy value. For instance

~1 == true
~2 == true
~-2 == true
~-1 == false

This works because the tilde operator inverts the bits representing -1 to 0. So for example, if you are using indexOf (which will return an index, or -1 if there is not match) - then you can use this expression to make the test more reliable.

if (~mystring.indexOf(‘f’)) {
}

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

What is the following code doing?

Array.prototype.slice.call(arguments, 1)

A

In JavaScript, arguments (one of the default values in a function) is not an array, but an array like object. In order to call slice on it - you can pass ‘arguments’ to the slice function on the Array.prototype - can use call to call slice, and set it’s ‘this’ variable to ‘arguments’. I guess it would be like calling arguments.slice() - if arguments was an actual array.

It works because the key / value pairs are numbered, and the object has a length value.

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

When using React.js you may see the pattern where a file is ‘defined’ and the variable is declared as a parameter to a function, but it’s not actually used in the function. What is happening here?

A

The object/function being referenced is going to get called (because it’s defined as a dependency) - which will execute any code in that function. So it can be useful for setting up data / states - and having it run without actually calling a function explicitly (since React takes care of that for you under the hood).

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

Why should you use a package.json file when using NPM?

A

If you use –save switch, it will write the dependencies into the file. This will make it a lot easier when moving to another machine, or distributing your application.

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

How do you export a variable using ES6 from a file?

A

export var foobar = ‘myvalue’;

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

What does CommonJS do?

A

It’s a module system, that works mainly on the server side.

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

In MVC, the controller is the entry point to…

A

a component.

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

In MVC, the controller instantiates…

A

The view and the model

(Of course, there is a case to be made for these to be instantiated and injected into the controller via a DI container).

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

The model is reponsible for…

A

storing, persisting or retrieving data from a database or other kind of store.

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

Why do we sometimes need to write a clone function?

A

Because objects in JS are passed by reference, so we often need to create clones, so that a change doesn’t affect ALL objects.

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

What is the main difference between MVP and MVC?

A

In MVP, the view does not have direct access to the model.

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

What function could you use to make sure that when you perform a mathematical calculation, that it never goes below a certain level?

A

Math.max(myarray.length - 6, 0);

This will take the array length and give you the result minus six, unless it goes below 0, when it will give you 0.

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

Using an object literal, how would you create a namespace for your project?

A

Firstly - give it a long name so it’s unique (i.e. reverse URL).

// NOTE: This is check to see if each part of the variable 
// exists. It doesn't matter if it does - as if one part exists,
// the next part will be attached to the existing var.
var com = com || {};
com.cm = com.cm || {}; // NOTE - no var
// Obviously, don't use a name like cm, use something
// longer - just using short names for space. 
com.cainmartin.project = {
    // The actual project code goes here
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What’s the biggest flaw of the basic Module design pattern?

A

The private members can’t interact with the public members.

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

What is the main difference between the Module and the Module Reveal patterns?

A

The Module pattern uses an object literal to encapsulate the public methods - whereas the Module Reveal pattern encapsulates ALL methods within it’s main body, and “reveals” them by creating a reference to the public methods in an object literal that is returned to the outer scope.

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

What is the main disadvantage of the Module Reveal pattern?

A

You can’t add members to the object easily as it’s entirely locked off in a private space.

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

How do you get ALL of your code out of the global scope?

A

Use an IIFE to wrap everything.

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

If you encapsulate your application in an IIFE, how could you make a public API / entry point into your app?

A

You can pass in a pointer to the window / document etc. Then assign a variable to the window (global namespace).

if (!window.chatModule) {
window.chatModule = chatModule;
}

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

What is one benefit of the JavaScript singleton design pattern?

A

You can delay instantiation of the object until required. This is done by using a IIFE which contains an init function, and a revealed “getInstance()” method. That method then calls init, which in turns creates the actual object you want (the singleton).

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

If you are using the jQuery keypress method and you are checking ‘key’ - what is the potential pitfall?

A

Chrome doesn’t seem to generate a value for key - which leads to no result. You probably need to use keycodes.

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

When would you use the Abstract Factory over a Factory?

A

When you realise your factory is no longer flexible enough. Generally the Factory pattern is sufficient.

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

Given that JavaScript doesn’t have a notion of interfaces, how do you deal with (say in an abstract factory) ensuring that the object that is requested, is the right one?

A

One method is to test for the function you need on the prototype.

if (myobject.prototype.myfunc) {
return new // the object you want.
}

Effectively you are testing for an interface here.

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

What are the four elements of a design pattern?

A
  1. A pattern name – each pattern should have a descriptive name
  2. A problem – a design challenge or context in which to apply the pattern
  3. A solution – describes the pattern elements and their arrangements
  4. Consequences – tradeoffs and side-effects of applying the pattern
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

How does the GoF describe design patterns?

A

“descriptions of communicating objects and classes that are customized to solve a general design problem in a particular context”

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

Getter and Setter methods are more accurately called…

A

accessor and mutator methods

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

“has a” and “is a” relationships are more formally known as…

A

Composition and Inheritence relationships

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

What is the simplest way to implement inheritance in JS?

A

Set the prototype variable of an object to the ancestor object.

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

Tight coupling is a form of..

A

technical debt

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

If coupling exists between objects, cohesion exists…

A

within objects and modules

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

What is the rule of three?

A

Under some circumstances, copying code twice is okay (at first appears to violate dry). But when you’ve copied it three times you may need to start refactoring. You wait three times because only at that point do the necessary abstractions become clear.

The reason for this is that two observations may not be sufficient to see the pattern.

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

What are considered the three layers of web design?

A

Behaviour - JS
Style - CSS
Content - HTML

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

The browser loop (which is single threaded) is also known as the…

A

User Interface loop

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

What is a potential problem that could arise from adding an onload event where the handler takes 5 more seconds to execute?

A

Because the loop is single threaded, it will block events until it’s finished executing. The problem being that keyboard input events are also executed in that loop. So if a page fully loads, and this function kicks off, the user may try to input something in the page - and it wont work.

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

If you are going to need to do something that will definitely take time (i.e. getting data from a sever) - what technique can you use that will reduce the impact on the user experience?

A

Asynchronous callbacks.

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

If you have an onclick event - (in the HTML) - and you give it this code, what does the return false do?

onclick=”alert(‘chicken’); return false”

A

It will prevent the function from doing it’s default action, which would be to follow the href (link).

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

When you use addEventHandler to get a reference to a DOM element, what is the ‘this’ variable of the handler set to?

A

The actual HTML element

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

What is the zero timeout pattern?

A

You can call a function using SetTimeout - with a value of 0. This can potentially get around scripts that are taking too long to run.

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

What is a common place that the zero timeout pattern is used?

A

Text highlighters - the act of searching the page for the required text can take a long time.

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

If you’ve set a variable with the method setTimeout - how do you clear that timeout and hence stop the timer?

A

Call “clearInterval” on it.

clearInterval(timeout);

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

When we get a value from an object, JS follows the prototype chain - what about when we set a value?

A

No - when we set a value, it doesn’t write the to prototype. In fact, if the variable doesn’t exist on the object, it actually creates it - which subsequently masks the value on the prototype.

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

If we have the following code:

var Car = function() {};
Car.prototype = { make: 'Lexus' };
var myToyota = new Car();
console.log(myToyota.prototype);

Why does the last line fail?

A

Because you can’t actually directly access the prototype directly from an instance.

The internal reference is actually [[Prototype]]. You CAN access through the non-standard __proto__ and also the ES5 function - Object.getPrototypeOf

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

What are the only things in JS that have prototype properties?

A

Constructor functions or Function objects

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q
var Truck = function() {};
Truck.prototype = { load: 100 }
var myTruck = new Truck();

Does myTruck have a .prototype member?

A

No - only the FUNCTION CONSTRUCTOR has one. It will assign the prototype to the internal [[Prototype]] member

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

What is Function.prototype?

A

The default prototype object for all functions

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

What is Function.prototype’s prototype?

A

Object.prototype

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

What is Object.prototype’s prototype?

A

undefined

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

If you change the value on a member variable from a prototype - does this change the value for all prototypes?

A

It depends on how you do it. If you do it properly - then no. Normally, you would have a function that would make a change like this:

this.mynumber = 10;

EVEN if this is called from within a function placed directly on the prototype, this wont change the prototypes value. It will create a new variable on the enclosing object, below the prototype level. Subsequent lookups will find this variable first, and return it’s value.

this. prototype.mynumber - from within a fucntion on the prototype, will fail - so you can’t do this.
this. __proto__.mynumber = 10 - will work - and change all values for all objects. Keep in mind - you SHOULD NEVER DO THIS.

So for all intents and purposes - if you do this correctly, changing a value of a variable on an object, even one that lives on the prototype - will only change it for that instance. Just like classical object oriented programming.

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

Why can’t name be printed out in the following code?

function Car() {
    name = "a big car";   
}
console.log(name);
A

Because a straight function isn’t automatically called. Therefore you have to call it first, then “name” will be assigned to the global space and this code will work.

Remember - variables without the var keyword (i.e. an undeclared variable) is added to the global memory space, not the local function execution context.

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

Why is the following undefined?

function Car() { name = "a big car";   }
Car.prototype = { chicken: 'A String' }
var car = new Car();
console.log(car.prototype);
A

Because the .prototype reference only exists on the function constructors, not the actual object. At the point the object is created, the .prototype reference is assigned to the __proto__ or [[Prototype]] members on the object.

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

What will the following two return:

alert(Emp.prototype == Emp.__proto__);
alert(Emp.__proto__ == Function.prototype);

A

False
True

Why does Function.prototype == Emp.__proto__, because it’s the base object that all functions derive / inherit from

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

What is the prototype chain for a function object?

A

function object -> Function.prototype -> Object.protoype

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

What is the difference between a function and a function constructor?

A

The difference is simply in the use of “new”. New sets the context (the this variable) and if it’s not used on a function (i.e. it’s just a normal function) - then the context is that of the external object (window, assuming you are working in global context).

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

The prototype property ONLY exists on what?

A

Functions and Constructor Functions

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

The constructor property exists on WHAT, and were created by WHAT?

A

They exist on prototype objects (not the main object), and were created by constructor functions - it points back to the original function constructor.

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

What is one disadvantage of using an anonymous constructor function?

A

The debugger reports the constructor value as being function().

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

What is the purpose of the ! in this code?

!function() {
console.log(“Testing”);
}();

A

It’s an alternative syntax for an IIFE.

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

Does the __proto__ object have a copy of the function constructor too?

A

Yes - remember the __proto__ variable is basically a reference to the original prototype object on the function / function constructor.

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

What do the following two statements evaluate to?
alert(Function.prototype.constructor === Function);
alert(Function.constructor === Function);

A

true
true

NOTE: Function is it’s own constructor. Also - these two statements are essentially doing the same thing. Only in the second one, the JS engine has to do a little more work by moving through the prototype chain to find it.

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

if (true || (a + b))

will a + b execute?

A

No - because the first part of the expression evaluated to true, there was no need to continue to evaluate the expression as an or expression only requires one side to be true.

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

What will the following expression return?

false || “8”

A

“8”

It wont return true or false - but the last part of the expression that evaluated to true.

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

What will the following expression return?

true && “10”

A

“10” - because it’s the last value that was evaluated to true

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

Why does the following work?

var param = param || ‘ ‘;

A

Because the logical operators return the first value that evaluates to true. So if param exists, it will return the value stored in param - if it doesn’t exist, it will return the empty string (or whatever other value is on the right).

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

Falsy expressions are those that evaluate to… (and what are they)?

A

false - they are false, null, undefined, NaN, 0, the number 0, and empty string.

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

Truthy expressions are those that evaluate to… (and what are they)?

A

true - they are true, non-empty strings, arrays (empty or not), objects, functions, numbers (not zero, but negative is true), infinity etc. Basically anything that is not falsy.

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

What does the !! character do?

A

Ensures the value returned is a true Boolean value.

76
Q

How could you use a !! character to determine if a value is odd?

A

var odd = !!(i % 2);

i.e. if 2 % 2 = 0, then !! will coerce this to a boolean value of false. I.e. 2 is NOT an odd number.

77
Q

Why might you see code like:

var oProto = Object.prototype;

A

Because it allows minifiers to reduce the code as much as possible. Minifiers cannot reduce the name of inbuilt identifiers - but it can reduce the size of custom variables.

78
Q

Why might you see the following code, and what is the downsides?

var slice = Array.slice;

A

It speeds up access to the slice method - however, it will require using the “call” function to specify the context.

slice.call(array, 0, n);

79
Q

What is the following code doing?

var slice = [].slice;
var toString = {}.toString;
A
Much like: 
var slice = Array.slice;

It’s attempting to reduce the execution time of the code. However - using the object literal / array literal syntax is a bit slower than using Array.slice or Object.toString because it has to create the object for each line.

80
Q

Why do local variables containing references to built in methods save processing time? i.e.

var math = Math,
       mRound = math.round;
A

Because it saves JavaScript having to continually search the prototype chain.

This is most useful for methods and properties that exist on the global object, because these are the last part of the prototype chain to be checked. i.e. Document, Math, alert.

81
Q

Why do programmers sometimes use the following construct in JS?

var _true_ = true;
var _false_ = false;
var _null_ = null;
A

It allows minifiers to shave off space when minifying the native variable names.

82
Q

The function parameter ‘arguments’ is not an array - but in some code the programmers will convert it to an array. How is this usually done?

A

Two main ways.

var args = [].slice.call(arguments, 0);
or
var args = Array.prototype.slice.call(arguments, 0);
83
Q

What is the common way (and why?) do you represent unused parameters?

A

Using an underscore (although this is just a convention, not a programming language rule). i.e.

function foobar(_, result) {
}

This is sometimes used in callbacks, or try / catch blocks and simply indicates that the parameter is not actually used (but the way the method is called, requires something).

try {
} catch(_) {
}

84
Q

How could you write a function to test if an object is a function?

A
var isFunction = function (item) {
    return Object.prototype.toString.call(item) == "[object Function]";
}
85
Q

How can you implement function overloading in JS?

A

You can test the type / number of parameters and execute different code paths accordingly.

86
Q

What is the options hash or configuration pattern?

A

It’s a pattern that’s useful when function argument lists have a combination of required and optional parameters. Basically you give all required parameters as individual paramters. Then bundle up the optional parameters in an object and pass that as the last parameter.

function myfunc(required1, required2, options) {
     // optionals is an object
}
87
Q

How do you deal with optional parameters in a function when using the options hash?

A

You first create a default object that contains all the possible default parameters - with sensible defaults

var defaults = {
    parameter: 21,
    name: 'superman'
}

Then you use a function to combine the objects - something like jQuery $.extend, or you can write your own. That will combine them.

this.settings = $.extend({}, defaults, options || {});

(options is the optional settings object passed in from the outside)

88
Q

What does the following code do?

+function () {
}();

A

It’s an IIFE - although the + syntax is not recommended. You could also use: void, 100%, and number of other things.

89
Q

Is this statement true, “Anything placed in front of an anonymous function that turns the function into an expression, and if it’s followed by parenthesis, will execute the function”?

A

yes. This is how IIFE’s work. The outer brackets simply turn the anonymous function into an expression. By adding the final () - it invokes the enclosed function. But it doesn’t have to be outer brackets - using a !, or ~, or a + will turn that anonymous function into an expression, and as long as there is a set of closing () - it will invoke the anonymous function.

90
Q

Is the following construct valid JavaScript?

var func = new function() {
  // 
}
A

Yes - but it’s not ideal. You can’t reuse the function constructor, and JSLint will tell you that you should probably remove new.

91
Q

What is the purpose of the preceding ‘;’

;(function func() {
  // Other code here
}());
A

It’s often used in the module pattern - when your code is likely to be used with other libraries. It protects your code against forgotten or unclosed ;

This idiom is referred to as the preceding semicolon.

92
Q

What is wrong with this code?

function foo() {
    return 
    {
        name: 'steveo'
    }
}
A

The JS engine will put a semi colon after the ‘return’ keyword, therefore blocking out the returned object from the code.

93
Q

Why is the convention of using uppercase letters for function constructors important?

A

It helps the dev remember to use new when calling the constructor. No errors are given if you forget.

94
Q

What is the output of the following code:

var index = 9;

function doSomething() {
    alert(index); 
    var index = 10;
    alert(index); 
}

doSomething();

A

undefined
10

The reason being the var index inside the function is hoisted to the top of the function, and masks the global var index (even though it’s undefined).

95
Q

What is the single var pattern?

A

It’s where all variables are declared at the beginning of a function block - and only one var is used:

var foobar = 10,
      chicken = 21,
      bestcurealbum = "Disintegration"

NOTE: Some code houses will demand initialised variables come first, and only one variable dec per line.

96
Q

While the single var pattern is quite common - it has one big pitfall, what is it?

A

When making the declarations, if you accidentally put a semi-colon instead of a comma, the following variables will be made global.

97
Q

Functions should be declared before…

A

they are used. It’s obviously not a requirement in JavaScript - but it makes your code easier to read and understand. this is particularly true inside functions.

98
Q

If you create two Person objects, and set the name of the first one, then give a different name to the second one - but both are reporting that they have the same name - what could have gone wrong?

A

If you create the objects without the new operator by accident, the context is not set, and the this operator is set to the global scope. Therefore both objects will be referring to the exact same variables.

HOWEVER - in actually testing this - if you try to assign a function object to a variable, it appears to be undefined. So while

99
Q

What is one way to code defensively against forgotten “new” calls on function constructors?

A
var Person = function (name) {
    if (!(this instanceof Person)) {
        return new Person(name);
    }
    // Other code here.
}

This has little overhead and is worthwhile as it can prevent some insidious bugs.

100
Q

When using the module pattern, do you use the “new” keyword to create a new object?

A

No. Just assign it to a variable - since the function returns a closure containing the inner data, it’s going to be giving you a different object than the one you requested anyway. (i.e. the internal anonymous closure).

101
Q

How can function prototypes save memory?

A

By putting shared functions on the prototype, all objects that are created using that object will share the same prototype, thereby saving memory.

102
Q

What is the simplest way to define a namespace and variables to it in JS?

A
var myNamespace = {}
var myNamespace.i, myNamespace.j, myNamespace.k;
function myNamespace.superman () {}
103
Q

What is a bookmarklet?

A

A small bit of code that is used on a page that is not intended to interact with any other code outside of it. It can therefore be created within an IIFE and not take up any space in the global namespace.

104
Q

Where does the name bookmarklet come from?

A

It’s a combination of the words bookmark and applet.

105
Q

Why would you include a variable named “undefined” in a module like this:

var module = (function (win, $, undefined) {

    var doc = win.document;
    var nav = win.navigation;    
return {
}; })(window, jQuery);
A

A hacker could redefine the value undefined to ‘true’ for instance which would have unknown consequences for you r code. By creating a variable that is never set - and calling it ‘undefined’ - then you can be sure that undefined will in fact be equal to undefined.

106
Q

If you have a long string (such as a user agent string), and you want to know whether a word (such as a browser name) exists within the string - what’s a simple way tot test without resorting to regex?

A

useragentString.indexOf(‘chrome’) > -1

By testing for > -1 you don’t care where it is in the string, just that it’s there.

107
Q

Rather than access the global scope directly from a module, what is considered best practice?

A

To pass the value in through the module.

(function(win) {
   var doc = win.document;

}(window));

108
Q

In large projects spanning multiple files - there is a risk that you can overwrite your modules due to files being included in an incorrect order - how can you modify the module pattern to solve this??

A

Using the “partial module” pattern.

var module = (function (self) {

var top = 10;

self. multiply = function (x,y) { return x * y; };
self. divide = function (x,y) { return x / y; };
self. getTop = function () { return top; };

return self;

})(module || {});

NOTE: that you pass the module back to itself - and then add the members to that. If the module doesn’t exist in the first place, it’s created anew. If it did exist, then you are adding to the original variable.

109
Q

What is the most common way to mix the namespace pattern and the module pattern?

A
MyApp.namespace("Util.Events").module = (function () {
    // private area ...
    return {
        // public area ...
    };
})();
110
Q

The module pattern is Javascripts version of the…

A

Singleton

111
Q

How do you make a method chainable?

A

You return the this value from the method.

112
Q

What is the biggest disadvantage of chaining methods?

A

If the debugger detects an error - it will give the you the line - but not necessarily the method.

113
Q

What’s another name for the chaining pattern?

A

Fluent interface

114
Q

What is the constructor invocation pattern?

A

simply refers to calling a method declared on a constructor function that was created via new. This ‘this’ variable is bound to the object.

function Something() {
    this.doSomething = function() {
    }
}
var mySomething = new Something();

mySomething.doSomething();

115
Q

What is the method invocation pattern?

A

Calling a method directly from an object. The ‘this’ variable is bound to the object instance.

var obj = {
  doSomething: function() {
  }
}

obj.doSomething();

116
Q

What is the function invocation pattern?

A

Simply creating a function in the global scope and calling it. The this variable is set to the global object (in a browser this is the window object).

function foobar() {
}

foobar();

117
Q

Calling a constructor function without new changes the invocation pattern being used from a Constructor Invocation to a Function Invocation - what is the problem with this?

A

The ‘this’ variable will be bound to the global object, and this will cause problems with the code.

118
Q

The value of this is bound just before the function starts executing. This is called…

A

late binding.

119
Q

What is the difference between an extend pattern and a mixin?

A

A mixin will copy properties from one or more objects, whereas an extend will only copy from one.

120
Q

Why might you see a line of code like this?

Employees.prototype = [];

A

If you wanted to make a set of objects that are sortable - it may make sense to derive from an array.

121
Q

What is a very easy way to create a container object that has all the features of an array?

A

You can inherit from the array object.

var MyContainer = function() {};
MyContainer.prototype = [];
var myContainer = new MyContainer();
myContainer.push('Chickens');
122
Q

What is the functional mixin pattern?

A

Rather than having a mixin function, we can create functions that contain the functions we wish to attach to another object. Then we can use the ‘call’ method, to attach them. The idea is to group related functionality into methods that can be attached as required. Then we can apply these functions to the receivers prototype.

var sortable = function() {
    this.sortAge = function() {
    }
}

sortable.call(MyObject.prototype);

Because this in sortable will be set to the prototype of MyObject, the function will be created on the prototype.

123
Q

What is the purpose of the Monkey Patch in JS?

A

To modify code at runtime without modifying the source. This is useful when patching functionality into an existing library. (also known as duck punching)

NOTE: This isn’t really a recommended pattern - although it can be useful.

124
Q

How is a monkey patch implemented?

A

You simply mask the variable / method that is being patched. i.e.

var monkey = {
   say: function() { alert('yo'); }
}

monkey.say = function() { console.log(‘yo’); }

125
Q

When you are creating a monkey patch, it’s often desirable to capture the old function, so you can make modifications around the function - what should you do to make sure you aren’t poluting the global namespace?

A
Wrap the saved function: var myFunc = old.myFunc; 
and the monkey patch, into an IIFE.
126
Q

If you apply a monkey patch like so:

person.myMonkeyPatch = function() {}

But the function myMonkeyPatch exists on the prototype - will this work?

A

Yes - but we are just masking the function. Therefore it will only apply to that particular object. This isn’t a problem, but it’s worth noting that it will not propagate to other objects using this method.

127
Q

Why is it not a good idea to have this code at the global scope?

var history = {};

A

It’s a variable that is already in use on the global object - it’s part of the interface that allows a programmer to manipulate the browsers history.

128
Q

What is lazy initialisation?

A

In JavaScript it’s not always desirable to create all objects at the start (for reasons of performance, memory, prevent flickering of the page) . To do this, you may have an object with an “getIniatilized” method - which actually populates and returns the required data when queried. What makes this a pattern is that it will only do this the first time it’s queried - and store the results for subsequent calls. (a little like a singleton)

129
Q

What is the “Ghost Pattern”?

A

When an object is created it’s only partially loaded. The loading is completed when it’s called upon. The term Ghost comes from the fact the pattern might load only the “ID, NAME and PHOTO” of an employee. This is a ghost version of the full employee data - which is only loaded when requested.

The background load is likely accomplished using AJAX.

130
Q

When is the Ghost Pattern useful?

A

When you have a website where the front page is full of employees (and it’s a long list) - you can just load the initial information (say id, and name and photo thumbnail). Upon clicking on an employee, the rest of the data is loaded - only when required.

131
Q

What is the multiton pattern?

A

Similar to a singleton. But it typically stores multiple instances of the same kind of object. The difference between this and a simple hash is that the client is allowed to choose mappings.

Also the multiton should never return a null or empty reference. Instead, when it’s first called it creates the object with the associated key - then it always returns that same object for that key.

132
Q

Is it true that you should never use == true?

A

I think for the most part - this is true. The reason being:

“true” == true

This equals false. Even though a non-empty string in JS is equal to true. The reason being, when we bring the == into the picture, the values are converted to numbers. “true” becomes NaN and true becomes 1. Therefore they are not equal - and will result in a false.

The best way to deal with this is to simply let the operators deal with the truthiness. In the case of a non-empty string.

if (“true”) {
}

133
Q

In a typical JS MVC, the flow between the controller and the model is by…

A

method invocations

134
Q

In a typical JS MVC pattern, the flow between the view and the controller, and the model and the view is by…

A

events and event handlers.

135
Q

What is the typical flow in an MVC app?

A

View -> Controller -> Model -> View

136
Q

What is another name that the observer pattern is known by?

A

Pub / Sub (for publish / subscribe)

137
Q

What participants exist in the observer pattern?

A

The subject
Maintains a list of observers
Implements an interface that lets the observer subscribe / unsubscribe
Sends a notification to it’s list of observers when it’s state changes

The Observer
Has a function signature that can be invoked when the Subject changes

138
Q

When using the observer pattern in MVC? With regards to the view / model - who is the subject, and who is the observer?

A

The model is the subject, the view is the observer. The model notifies the view that there has been a change. The view then subsequently updates it.

139
Q

How do you print errors to the console?

A

console.error(“ERROR!”);

140
Q

If you find jQuery loading from a CDN is slowing down your web application - how can you improve the speed?

A

You could create a custom version of jQuery, including on the functions you use, and store it locally on the server.

141
Q

What will be the value of foo.count?

function foo(num) {
    this.count = 5;
}

foo.count = 0;
foo(10);
console.log(foo.count);

A

The value will be 0.

Remember - in a function the context (value of this) is set by default to the window.

142
Q

There are two ways to make the ‘this’ value within a function point to the function itself - what are they?

A

First is using a lexical identifier (variable) - i.e. if you have a function foo with a variable ‘data’ - you can refer to it by foo.data;

Otherwise you can use the more conventional (for JS) - method - use the call method to set the value of this.

foo.call(foo);

143
Q

This is not an author-time binding - but a…

A

runtime binding

144
Q

the this variable is a property of…

A

the execution context that is created when a function is invoked.

145
Q

The execution context may also be known as a…

A

activation record

146
Q

The this binding made for each invocation is based on…

A

the call-site

147
Q

The call-site is in…

A

the invocation BEFORE the currently executing function

148
Q

Given that in strict mode, the the global object is ineligible for binding - what would be the result of the following code?

function foo() { console.log(this.a); }
var a = 2;
(function() {
   "use strict";
    foo();
})();
A

2

  • because the actual code for foo is not contained within the “use strict” scope - the global object is eligible for binding with the this property in foo - and thus it is able to locate the value of a via ‘this’.

This is an example of default binding

149
Q

What is printed to screen here?

function foo() { console.log( this.a );}
var obj = {
    a: 2,
    foo: foo
};
obj.foo();
A

2

Because foo is added as a reference property foo inside the object, when you call that function via the object, the this (in foo) variable is bound to context of the enclosing object. This is called the object context.

This is an example of implicit binding.

150
Q

What does the implicit binding rule state?

A

When there is a context object for a function reference, it’s THAT object that should be used at runtime for the function calls binding.

function foo() { console.log( this.a );}
var obj = {
    a: 2,
    foo: foo
};
obj.foo();
151
Q

Which object is this call chain is used to set the this value?

obj1.obj2.foo();

A

obj2 - it’s the last object in the chain that matters to the call-site.

152
Q

What will be output with the following code?

function foo() { console.log(this.a); }

var obj = {
a: 42,
foo: foo
};

var bar = obj.foo;
var a = "Ooops! Global";
bar();
A

“Oops! Global”

This is a case of Implicitly lost binding.

Remember - the call-site is what matters. And despite bar being an implicitly bound function with (what appears to be) an object context - the call-site is at the global level. And thus, this will point to the global object.

NOTE: bar is really just a reference to foo here, not a reference to obj.foo.

153
Q

If an implicitly bound function loses that binding , what does ‘this’ point to?

A

Depending on whether strict mode is enabled, either the global object, or undefined.

154
Q

What is the output of the following code?

function foo() {console.log(this.a); }
function doFoo(fn) { fn(); }
var obj = { a: 2, foo: foo };
var a = "oops, global";

doFoo(obj.foo);

A

“Oops, global”

Because ‘obj.foo’ is passed as a reference to doFoo - it’s really just a direct reference to ‘foo’. Therefore we lose the implicit binding when fn() is called within doFoo.

This occurs regardless of whether the reference is from your own code, or internal to the language.

So function callbacks are a common place that implicit bindings are lost.

155
Q

What is hard-binding in the context of JS?

A

When passing a variable to a function of the form:

var bar = obj.foo;

The binding to the obj is lost. By using the following construct that isn’t the case:

var bar = function () {
   foo.call(obj);
}

the ‘this’ variable within foo can no longer be overriden, and the scope is defined as obj. No matter how you invoke bar - it will always manually invoke foo with bar as the context. Thi s binding is both explicit and strong - therefore hardbinding.

156
Q

The most common way to warp a function with hard-binding is to…

A

create a function with a pass through of any arguments passed and return value received.

var bar = function() {
    return foo.apply(obj, arguments);
};
157
Q

How would you write a simple “hard binding” helper?

A
function bind( fn, obj ) {
    return function() { 
        return fn.apply( obj, arguments );
    }
}

NOTE: This is essentially available through the bind function in ES5

158
Q

Are constructor functions special in anyway?

A

No - they are just regular functions. The only thing that makes them a constructor is the act of calling them with keyword new. By doing so, a regular function essentially becomes a constructor function.

159
Q

What is ‘new binding’?

A

When a function is called with the new keyword, it becomes a constructor function. The this value within the function is bound to the newly constructed object.

160
Q

What is the order of precendence of binding types?

A

New binding
Explicit binding
Implicit binding
Default binding

161
Q

How do you determine what the this value is set to?

A

First - find the direct call site, then:

Is the function called with new (new binding)? If so - the newly created object is ‘this’.

Is the function called with call/apply (explicity binding) (or even hidden inside a hard binding) - then this is the explicitly specified object

Is the function called with a context? (implicit binding) (otherwise known as an owning object) - if so - this is the owning object

Otherwise default this (default binding) is the global object, or ‘undefined’ if we are in strict mode.

(Remember though - there are some exceptions, such as assignment where bar = a.foo; default binding applies here)

162
Q

If you pass null to apply/call/bind - what binding rule applies?

A

The default binding rule.

function foo(a, b) { console.log("a: " + a + " b: " + b);}
foo.apply(null, [2, 3]);
// Currying with bind
var bar = foo.bind(null, 2);
bar( 3 );
163
Q

Using apply and bind on a function can be useful for reasons OTHER than to bind a function’s context - so you can pass it null instead of a context. However - there is a risk - what is it?

A

If the function that you are setting to ‘null’ actually makes use of the ‘this’ variable (i.e. in some external library) - then the default binding rule means it might reference (or worse mutate) the global object (window in the browser).

164
Q

Currently, you can use the apply function to ‘spread’ out a set of parameters from an array.
foo.apply(null, [1, 2, 3, 5]);

What is the ES6 way of doing this?

A

There is now the new ‘spread’ operator ‘…’

foo(…[1, 2, 3,5);

This gets around some of the risks that using the null operator with apply introduces.

165
Q

Rather than passing null to an apply/call invocation - what could you do so that you don’t run the risk of mutating the global object?

A

Pass it an empty, non-delegated object.

You can do this with:

Object.create(null);

NOTE: this is similar to just {} but - {} makes a delegation to Object.prototype. So the first version is “more empty”. You can use a symbol or name that helps signifiy that you want it to be empty. Such as ø

166
Q

Is null an object type?

A

No - it does appear to be one - i.e. when you do a test with typeof - it does report it as an object. But this is a bug.

167
Q

Currently in ES5, you have to specify an object literals’ properties using strings. But ES6 introduces computed property names - how does this work?

A

This allows you to build up a new objects property names using run time code.

var object = {
[prefix + ‘bar’]: “Hello”,
[prefix + ‘baz’]: “Yo…”,
};

(These are very likely going to be useful in the ES6 feature, symbols - however, I have no idea what they are yet).

168
Q

Does adding a named property to an array increase the value of the array property ‘length’?

A

No

However - if you were to use a name that “looks” like a number, it will indeed increase the value of “length”.

169
Q

What are the consequences of doing the following?

var array = new Array(10);
array["34"] = 10;
A

The length value SHOULD give you 11 - but instead it will report itself as 35 (due to the index starting at 0).

170
Q

If you copy an object, are the special characteristics of an object preserved on the new object (for instance, the writable flag)?

A

No.

171
Q

What method of Object can be used to get the property descriptor values of an object?

A

Object.getOwnPropertyDescriptor(myObject, ‘propertyname’);

172
Q

What method of Object can be used to define a property descriptor along with it’s value?

A
Object.defineProperty( myObject, 'a', {
   value: 2,
   writable: true,
   configurable: true,
   enumerable: true
});

console.log(myObject.a);

NOTE: This would not normally be used to create properties

173
Q

What attribute of a property defines whether the property can be written to, and what happens if you try to write to it when it’s read-only?

A

the writable property

Object.defineProperty( myObject, 'a', {
    value: 2,
    writable: false, // CAN'T WRITE TO IT!
    configurable: true,
    enumerable: true
});

If you try to write to it - it will fail silenty, unless strict mode is enabled, when it will throw a TypeError

174
Q

In the case that you are using straight functions within a module, the usage of ‘this’ in the function may throw a warning in JSHint, especially when using this inside a callback for an event handler. What is the solution?

A

Use the event object to get direct access to the target object.

evt.currentTarget.getAttribute(‘myattr’);

175
Q

What is KB927917 IE8 error?

A

It appears to be an issue with the way IE8 renders pages - but the usual fix is to make sure the DOM is loaded before doing any dom manipulation.

176
Q

Can you use delete on a function declared as such?

var foobar = function() {};

A

No - variables (even functions) that are declared using var cannot be deleted.

177
Q

Can you use delete on a function declared as such?

function x() {};

A

No - you cannot delete a function like this.

178
Q

Can you delete an object property like such?

object o = { x: 1 }
delete o.x;

A

Yes - this is about the only thing delete can be used for. You cannot delete var’s or functions, but you can delete object properties.

179
Q

What are the three types of executable code in ECMAScript?

A

Global Code - When source text is treated as a program, it is executed in global scope.

Function Code - Anything executed directly in a function, including inline code (event attributes) in HTML

Eval Code - text passed to the built in eval function.

180
Q

Why is it that you can delete the second, but not the first variable?

var foo = 10;
bar = 20;
A

Because when you create a variable using var - it’s internal ‘DontDelete’ property is set. Whereas, when you simply create a property like ‘bar’ - that property is not set.

181
Q

Why is it that when you use ‘delete’ on a ‘var variable’ - in firebug, it appears to actually delete the code?

A

It would appear that firebug uses eval to run the code within the environment - variables declared in eval mode do not set the ‘dontdelete’ flag. And therefore can be deleted. This is not the true behavior though (in a real program) so can be misleading.

182
Q

In an object/prototype scenario, how would you create private variables?

A

You can use var to declare a private variable. But the issue is that you can’t access them from the prototype. However, you can create public methods within the constructor that have direct access to the ‘private variables’.

var MyClass = function () {
   var _privateVar = 'foo';
   this.privlegedFunction = function () {
       alert(_privateVar);
   };
}

NOTE: In this scenario you don’t use this to access it.

183
Q

How would you use the reduce method to sum an array?

A
var total = [0, 1, 2, 3].reduce(function(a, b) {
  return a + b;
});
// total == 6
184
Q

What does ‘Array.prototype.concat()’ do?

A

Takes a number of arrays, returns a new array, with the arrays concatenated.

var num1 = [1, 2, 3],
num2 = [4, 5, 6],
num3 = [7, 8, 9];

var nums = num1.concat(num2, num3);

console.log(nums); // Result: [1, 2, 3, 4, 5, 6, 7, 8, 9]

185
Q

How would you flatten a series of arrays, using reduce and concat?

A
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
  return a.concat(b);
}, []);
// flattened is [0, 1, 2, 3, 4, 5]