JavaScript 4 Flashcards
What is the simplest way to modularize your code?
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 do you make namespaces in JS?
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
What does AMD stand for?
Asynchronous Module Definition
What is the downsides to using the Namespace pattern?
Declaring modules as global variables
Can’t specify the dependencies of a module
Have to list script files in order in the index.html
What library is used to help implement AMD?
Require.js
When using React, how do you specify dependencies?
define([‘player/controller’], function(Player, Controller) {
});
If you don’t have dependencies, what do you declare in ReactJS?
You specify an empty array.
define([], function() {});
When using ReactJS, what is one of the risks we have to look out for when setting up dependencies?
Circular dependencies
What pattern can be used to allow communication between modules that have been setup using the AMD pattern?
PubSub
What is another name for the Pub Sub pattern?
Observer
Why might you use the tilde ~ character in an if expression?
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’)) {
}
What is the following code doing?
Array.prototype.slice.call(arguments, 1)
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.
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?
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).
Why should you use a package.json file when using NPM?
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 do you export a variable using ES6 from a file?
export var foobar = ‘myvalue’;
What does CommonJS do?
It’s a module system, that works mainly on the server side.
In MVC, the controller is the entry point to…
a component.
In MVC, the controller instantiates…
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).
The model is reponsible for…
storing, persisting or retrieving data from a database or other kind of store.
Why do we sometimes need to write a clone function?
Because objects in JS are passed by reference, so we often need to create clones, so that a change doesn’t affect ALL objects.
What is the main difference between MVP and MVC?
In MVP, the view does not have direct access to the model.
What function could you use to make sure that when you perform a mathematical calculation, that it never goes below a certain level?
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.
Using an object literal, how would you create a namespace for your project?
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 }
What’s the biggest flaw of the basic Module design pattern?
The private members can’t interact with the public members.
What is the main difference between the Module and the Module Reveal patterns?
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.
What is the main disadvantage of the Module Reveal pattern?
You can’t add members to the object easily as it’s entirely locked off in a private space.
How do you get ALL of your code out of the global scope?
Use an IIFE to wrap everything.
If you encapsulate your application in an IIFE, how could you make a public API / entry point into your app?
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;
}
What is one benefit of the JavaScript singleton design pattern?
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).
If you are using the jQuery keypress method and you are checking ‘key’ - what is the potential pitfall?
Chrome doesn’t seem to generate a value for key - which leads to no result. You probably need to use keycodes.
When would you use the Abstract Factory over a Factory?
When you realise your factory is no longer flexible enough. Generally the Factory pattern is sufficient.
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?
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.
What are the four elements of a design pattern?
- A pattern name – each pattern should have a descriptive name
- A problem – a design challenge or context in which to apply the pattern
- A solution – describes the pattern elements and their arrangements
- Consequences – tradeoffs and side-effects of applying the pattern
How does the GoF describe design patterns?
“descriptions of communicating objects and classes that are customized to solve a general design problem in a particular context”
Getter and Setter methods are more accurately called…
accessor and mutator methods
“has a” and “is a” relationships are more formally known as…
Composition and Inheritence relationships
What is the simplest way to implement inheritance in JS?
Set the prototype variable of an object to the ancestor object.
Tight coupling is a form of..
technical debt
If coupling exists between objects, cohesion exists…
within objects and modules
What is the rule of three?
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.
What are considered the three layers of web design?
Behaviour - JS
Style - CSS
Content - HTML
The browser loop (which is single threaded) is also known as the…
User Interface loop
What is a potential problem that could arise from adding an onload event where the handler takes 5 more seconds to execute?
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.
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?
Asynchronous callbacks.
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”
It will prevent the function from doing it’s default action, which would be to follow the href (link).
When you use addEventHandler to get a reference to a DOM element, what is the ‘this’ variable of the handler set to?
The actual HTML element
What is the zero timeout pattern?
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.
What is a common place that the zero timeout pattern is used?
Text highlighters - the act of searching the page for the required text can take a long time.
If you’ve set a variable with the method setTimeout - how do you clear that timeout and hence stop the timer?
Call “clearInterval” on it.
clearInterval(timeout);
When we get a value from an object, JS follows the prototype chain - what about when we set a value?
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.
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?
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
What are the only things in JS that have prototype properties?
Constructor functions or Function objects
var Truck = function() {}; Truck.prototype = { load: 100 } var myTruck = new Truck();
Does myTruck have a .prototype member?
No - only the FUNCTION CONSTRUCTOR has one. It will assign the prototype to the internal [[Prototype]] member
What is Function.prototype?
The default prototype object for all functions
What is Function.prototype’s prototype?
Object.prototype
What is Object.prototype’s prototype?
undefined
If you change the value on a member variable from a prototype - does this change the value for all prototypes?
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.
Why can’t name be printed out in the following code?
function Car() { name = "a big car"; } console.log(name);
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.
Why is the following undefined?
function Car() { name = "a big car"; } Car.prototype = { chicken: 'A String' } var car = new Car(); console.log(car.prototype);
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.
What will the following two return:
alert(Emp.prototype == Emp.__proto__);
alert(Emp.__proto__ == Function.prototype);
False
True
Why does Function.prototype == Emp.__proto__, because it’s the base object that all functions derive / inherit from
What is the prototype chain for a function object?
function object -> Function.prototype -> Object.protoype
What is the difference between a function and a function constructor?
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).
The prototype property ONLY exists on what?
Functions and Constructor Functions
The constructor property exists on WHAT, and were created by WHAT?
They exist on prototype objects (not the main object), and were created by constructor functions - it points back to the original function constructor.
What is one disadvantage of using an anonymous constructor function?
The debugger reports the constructor value as being function().
What is the purpose of the ! in this code?
!function() {
console.log(“Testing”);
}();
It’s an alternative syntax for an IIFE.
Does the __proto__ object have a copy of the function constructor too?
Yes - remember the __proto__ variable is basically a reference to the original prototype object on the function / function constructor.
What do the following two statements evaluate to?
alert(Function.prototype.constructor === Function);
alert(Function.constructor === Function);
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.
if (true || (a + b))
will a + b execute?
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.
What will the following expression return?
false || “8”
“8”
It wont return true or false - but the last part of the expression that evaluated to true.
What will the following expression return?
true && “10”
“10” - because it’s the last value that was evaluated to true
Why does the following work?
var param = param || ‘ ‘;
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).
Falsy expressions are those that evaluate to… (and what are they)?
false - they are false, null, undefined, NaN, 0, the number 0, and empty string.
Truthy expressions are those that evaluate to… (and what are they)?
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.