General Game Programming Flashcards

1
Q

How would you go about resizeing a game to fit all devices?

A

There are lots of approaches and it would depend on the game, and target devices.

One simple - approach is to react to an resize event, and scale the game canvas based on the devices dimensions. You can use .innerWidth and .innerHeight to change the canvas. The game can keep it’s original game dimenions - but you apply a scaling factor based on the new dimensions / ratio to all positioning. This works pretty well, but has some drawbacks - images are stretched, It’s more complex to do the positioning (plus more calculations required in the main game loop )

Another alternative is to determine the ratio of your game, then determine the ratio of the device. With these ratios you can determine whether the device is wider or taller - then you can decide how to position the canvas in the div.

If the device is wider than the canvas - you might have bars on the left side. If the device is taller, you might have bars top and bottom.

This allows you to preserve the screen ratio.

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

How would you go about importing JSON data into a game?

A

There are no really good ways to read data from a file in JavaScript (mainly for security reasons) - but we can use AJAX style calls to achieve the same thing.

You create a XMLHttpRequest object, specify the mime type and file location - and you should be able to get the JSON and parse it.

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

Is Javascript asynchronous?

A

It appears to be, however it isn’t. While it seems like it can deal with things in an asynchronous manner, (events can fire at anytime, files can be fetched in a non-blocking manner) - in actual fact it runs in a single thread. The reason it appears to be asycnhronous is because of it’s callback system and the event loop.

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

Explain the event loop?

A

The javascript runtime contains a message queue - which is processed by the event loop. When events occur, they are placed in the queue. The queue is polled (each poll is called a tick) and if there is a message, it’s processed.

Now, because Javascript is actually single threaded, once a callback is taken out of the queue, it’s put on the call stack - and all polling of the queue is stopped until the call stack is cleared.

When you setup, say a timing event, with 0 millisecond delay, even though it’s 0 milliseconds it wont fire straight away - it’s placed in the queue ready for the next tick. The currently executing function will finish - then the queue is polled and the timer is executed.

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

Why are texture atlases important?

A

Most browsers will have a maximum number of requests that they can simultaneously allow to a server. This will be fairly low - around 6ish. If the request can’t be serviced, then it has to wait.

So the most optimal path is to create your assets to reduce the number of requests being made. One way to do this with images, is to create a texture atlas, a single png / jpg with all the assets on it.

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

Why does JSLint not like the new Array syntax?

A

The constructor is ambiguous, if you pass a number to it, it will create an empty array of that length. But if you pass the same value, as a string (i.e. ‘4’), then it will create a single element array with the value 4 in it.

It can also create some odd behavior - because .length will report that an empty array has x number of elements - and so much javascript code makes the assumption that .length is the size of the actual array (filled).

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

How can you reduce asset load times?

A

Use texture atlases can reduce the number of calls you make to the server reducing times.

If you use an asset manager, you can make sure you aren’t calling the same asset multiple times, you cache the asset and return that asset on request if it already exists.

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

What features should an asset manager have?

A

Cache

Async callbacks on load - that way we can do other processing while the File IO is underway, and react once we have the asset returned.

Batched asset loading - load lots of assets at once, and only give one callback.

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

How would you deal with users on a slow connection, if they are trying to load lots of data?

A

Using a preloader can help - it’s more about perception of speed. By making it feel responsive, it will help the user understand that something is actually happening as opposed to the game stalling.

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

How would you go about making sure code is reusable?

A

Writing clean, OO code (DRY, SOLID).

Making sure to maintain separation of concerns.

Avoid mixing presentation with logic.

Keep the scripting of the game (the actual gameplay code) separate from the entities within the game.

Plan ahead before coding.

If the UI is HTML - then you can keep that in it’s own layer.. It should be separate from the entities etc.

Reduce dependencies on external code.

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

Explain why you would prefer browser sniffing, over browser detection?

A

THe problem with browser detection is that it relys on fixed points in time of a browsers devvelopment. For instance, you may check for IE - but then, IE starts supporting the feature, so now you are check for a specific version, maybe there’s a patch. etc etc. It’s a liability that could lead to visitors with perfectly valid browsers missing out on features.

With sniffing, you can simply detect whether the specific feature is supported by the browser, and if so use, if not fall back to some other code path / way of doing it.

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

When would you choose to use CSS Animations?

A

If the animations are relatively simple, state based (only 1 or two states, or forwards and backwards are the same)

Also - it does depend to an extent on when you want them to trigger - if you need the animation to occur on :hover, :checked: or :active - then CSS might be the go.

Use javascript when the animation you are doing requires many different states, or different states depending on different inputs. Javascript is also the best option if you need to emulate physics.

You also need to consider browser support - while widely supported, it’s not 100%, so you have to consider whether the information being conveyed is critical or simply dressing. The good thing about CSS animations is that used properly, they are an excellent example of progressive enhancement, in that if the animation support isn’t there, it works fine without it - but if it is there, you get the additional benefit of the animation.

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

What are the most performant types of transitions in CSS?

A

opacity, scale, rotation and movement (when done with transforms)

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

What are the steps that a browser goes through to draw everything to the screen when animating?

A

Style, layout, paint, composite

Style, it calculates all the styles required for the element.
Then it works out it’s layout (that’s the geometry, position of each element). Then it fills in the pixels for the element, then it composites it on screen with everything else.

Some changes require going through all of these steps, and others do not, which is partly why some operations are more efficient than others.

Changes to transform and opacity properties - are done on the last step only.

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

What is the CSS translate3d hack?

A

Setting the transform: translate3d(0, 0, 0) forces the browser to use hardware acceleration, and forces the element onto a new layer - which also boosts performance.

You may be able to use the ‘will-change’ property.

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

Talk about how you deal with CSS files?

A

I tend to separate them based on page.

I may use a CSS reset if I am doing something large like a wordpress theme.

I tend to use a an autoprefixer to deal with vendor prefixes - you can use this with grunt. There is one called Autoprefixer.

I use a CSS linter.

I haven’t used SASS / LESS before, but I’m going to start, because the complexity of animation files I’m playing with is increasing, and the ability to preform loops would be excellent. That should fit nicely into the grunt workflow.

I use a minifier with grunt.

If I am doing a lot of CSS animations, I might put those into separate files for organisation purposes - again, I’ll use grunt to concatenate those files / minify it for production. etc.

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

Any considereations when using CSS animations?

A

Yes - design them such that they don’t look browken if the animation can’t trigger (lack of browser support etc). Try to use the most performant methods of animation, look at a site like csstriggers.com will give you a list of what browser render states are triggered during that type of animation / transition.

Make sure you animations don’t make it harder for the user to use them. (i.e. animations that move under the mouse and cancel :hover states etc).

And like any design - evaluate what it brings to the table. Does it serve a purpose, am I over doing this (i.e. does it make things more confusing).

If your target browsers don’t support everything you need - consider using JavaScript instead.

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

What are the downsides to using the revealing module pattern?

A

It becomes more difficult to use the prototypal inheritance pattern, you’ll need to return the exposed public interface from an IIFE.

When you create the object, all of the objects are created again - it can be bad for memory, as we are not getting one of the benefits of the prototypal inheritance (i.e. shared prototypes).

Its hard to extend.

Object types are unclear, as you can’t use instanceof.

Patching a module is very difficult (if not impossible) as the module will continue to refer to the internal implementation (due to the way the closure works)

NOTES: __proto__ is not standard (or at least may be deprecated)

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

Why would you use a module pattern?

A

Unlike many other OO languages, there is no syntax to declare member variables / methods as private, so a JavaScript object is technically always open for modification. This in fact has become part of the way people program in JavaScript - but it can lead to some issues.

For instance, if we have a member variable that needs to be modified by a method, say we have to perform some kind of transformation to it before use - a user of the interface could by pass that causing major problems.

Using _’s to indicate that it’s private is okay - but it doesn’t prevent access.

So using a module pattern such as revealing module will protect against that.

It’s easy to make members private without changing the internal implementation - just change the interface (the return object)

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

What is the difference between a primitive and an obect?

A

A primitive is a data type that is composed of no other data types and can not be broken down any further. They are the building blocks for Objects.

In JavaScript there are 5 primitive types are
Number
String
Boolean
Null
Undefined

There is a new type in ECMA 6 called “Symbol”

NaN - is not a primitive, it’s not a Number - even though it returns Number when you do typeof NaN.

An object is usually made up of primitives, and other objects.

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

What is a “falsy” value?

A

There are six falsey values:

0, null, undefined, false, “”, NaN

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

Why should you use the === operator as a matter of practice?

A

If JavaScript needs to test equivalency, it first tries to get both sides of the expression to a similar type. In the case of the equality operator, it will convert the left and right operands

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

What does JS try to coerce values too in this type of expression?

A

foobar = foobar || {}

Boolean - if the left hand side is false, then the left hand side will be assigned to the variable. Because Objects are always true.

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

What is meant by Dependency Inversion?

A

It’s a method of decoupling dependencies in Object oriented programming.

The principle states that high level modules should not depend on low level modules, and abstractions should depend on details, details should depend on abstractions.

On technique is Dependency Injection - you often see modules that contain ‘new OtherModule’, which immediately creates a dependency and makes testing harder.

So DI (which is NOT dependency inversion by itself, instead it’s a component) - can be used to decouple the objects. Rather than instantiating directly within the object, you can pass a reference to the object, preferably via an interface - or abstract bass class.

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

Is there ever a reason to use eval?

A

Yes - when there is no other way to accomplish the given task with a reasonable level of clarity and within a reasonable number of lines of code.

This eliminates 99% of cases where eval is used, across the board in all languages and contexts.

The only reason I can think of that is valid - is when dynamically generating code.

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

What are AMD modules?

A

AMD stands for Asynchronous Module Definition.

AMD supposedly makes website performance better, by allowing the website to load the files asynchronously, only when required. You don’t need to load the entire code base at once.

The cool thing about it is that you can define dependencies, which means you don’t get into that problem of which file needs to load first - you can specify the dependencies up front.

One of the better known implementations would be Require.js

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

What is CommonJS?

A

Like AMD modules it was designed to modularise JavaScript code - but it was more server centric.

I’m not sure of the exact details - but it seemed to occupy a space that Node is now replacing with it’s own module system.

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

What is currying?

A

When a function doesn’t take all it’s required parameters up front - instead returning a new function. This continues until you have fulfilled all the parameter requirements at which point it returns the result.

This is particularly useful if you need a function that pass through the application and gradually receive the arguments it needs.

It is also useful in cases where you want a function to behave in different ways based on certain input. You can say prime the function with an initial value, saving that in a variable - then use that “primed” function with different parameters

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

What is lazy loading / initialisation?

A

It’s a creational pattern that helps defer the creation of expensive objects unless really need. It helps you avoid the repetition of expensive processes.

In Javascript an example might be a Lazy Factory to load the XMLHttpRequest object.

When you call the factory, it determines which XMLHttpRequst object you will use - then, it redefines itself, based on the check for which one is available. The function then calls itself, returning the result.

Subsequent calls will simply return the already retrieved result.

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

What are some performance tips for JavaScript?

A

Use local variables - this will reduce the amount of searching that must be done via the scope chain.

Use lazy initialisation

Use closures sparingly

Assigning object properties to a variable if they are access frequently - particularly in a game loop. Object property lookup is slower than literals.

Avoid deep arrays, array lookups can be slow, if you have a multilevel array - then that’s multiple array looksups.

Watch your loops - using a for loop has three operations to perform each iteration. You could optimise that down to a while loop. Probably not a big gain - but in a game loop might be useful.

If you are dealing HTML collection arrays - convert them to normal arrays. They are live objects, and have significant performance overhead.

Cache DOM objects - grab them once - and then store them.

It can be better to add a class to a DOM element, rather than directly changing it’s .styles object. This wont necessary prevent a reflow - but because a class can hold multiple styles, it may mean a single reflow, instead of one per style change.

Keep your DOM depth as shallow as possible. A change at one level can trigger changes all the way to root and the children - and this can take longer to reflow.

Avoid changing things with computed styles (i.e. percentage widths) in JavaScript - this will trigger a reflow / Layout.

Avoid using borders / shadows / gradients where possible. They are quite expensive. There are a number of steps in rendering - Layout (calcs) - Paint (draw) - Composite - the heavier effects will usually trigger a Paint step which increases the whole Reflow time.

Reduce the number of CSS rules you have.

Precalculate anything that has finite set of answers - use a dictionary - or array to store the data and look it up each time you need it, rather than recalculating it.

Function cachig.

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

Why is working with HTML collection arrays risky?

A

You can cause infinite loops - because they are live, you can add an element, which forever extends the page beyond the limit of the loop ending condition.

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

How could you increase the performance of a recursive function like the fibonaci series?

A

You could use memoization - by making the function able to cache it’s results - you can reduce the number of calls significantly.

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

How do gracefully deal with exceptions?

A

If you are using libaries that make use of exceptions, then you really must handle them. Otherwise, I try to avoid them if I can code defensiveily (i.e. using feature detection).

If there are no other options - then wrapping the code in a try/catch/finally block is a good option.

There is also the window.onerror message handler that you can use to detect any unhandled errors.

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

Explain hoisting?

A

When a block of code runs, an execution context is created. There are two phases for this - the creation phase (where memory is allocated), and the execution phase (where the code is run line by line).

The variables and functions that are within the execution context are allocated memory - and so when the execution phase occurs, the memory already exists for the variables and functions. For function statements, the memory already points to the code. For variables and function literals, they are initially set to ‘undefined’ in the creation phase. It is only during the execution phase when the code is executed that the data is assigned.

That is why you can access the variables before they have been assigned and you don’t get an error.

It’s called hoisting, because it appears as though the variables have been moved to the top of the lexical environment - even though that’s not really what is happening.

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

Why should you never use undefined yourself?

A

If you never assign it, then it makes debugging easier. You know that the variable exists, but hasn’t been set. That gives you a big clue as to where and what the bug is.

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

Explain the scope chain

A

Every function when executed is given it’s own execution context. Within that, is a reference to it’s outer environment.

The outer environment is determine by where the code sits lexically. So if function “b” exists within “a” - then “b”’s outer environment is “a”.

If you request a variable within that execution context, the search begins at the current execution context’s variable object. If it can’t be found, the engine will then check the outer environment for the same variable, moving up the chain until it reaches the global execution context.

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

What is the benefits / downsides to memoization?

A

It’s a relatively simple technique that can produce incredible speed increases. So in an algorithm (say a recursive algorithm), it will likely produce a lot of results multiple times in order to get the final answer. By caching the results - for a particular input, we can return the value, rather than calling the function again, which saves dramatically on the amount of processing.

The downside is that we often need fairly large data structures to deal with it.

So it’s a time vs space tradeoff.

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

What are the most common module types?

A

There is AMD, UMD and CommonJS. These are all methods to improve JavaScripts organisation, which was never designed to handle larger projects.

The most well known implementation of the AMD (Asycnchronous Module definition) specification is probably Require.JS - which I have used a bit. It’s nice because it asynchronously loads files when required, and can have the result of improving site performance.

CommonJS - which i’ve only used a little, but it’s typically a server side solution - although I believe Browserify is making use of it in the browser. It’s quite similar to AMD in many respects in that it encapsulates data in a private namespace, and exports the public interface as an object literal.

I’ve never used UMD however, I can’t talk to it’s good / bad points unfortunately.

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

What are the most important paradigms in JavaSCript

A

Prototypal inheritance, and functional programming.

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

What is functional programming?

A

It’s method of programming that breaks the problem into smaller, composable chunks. For instance, the JavaScript library has a number of functions (such as filter) that make use of functional programming.

Javascript is a pretty good language for functional programming because it supports higher order functions (functions that take / return other functions), first class functions, and closures and lambdas.

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

What is a lambda?

A

Essentially an anonymous function - usually used to describe a use of anonymous functions where you can store data within a function for use later on. You could also describe it as “functions used as data”.

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

Explain recursion.

A

Recursion is a programming technique that can be described as a routine that calls itself repeatedly to solve a problem.

Recursion is typically best used when a problem can be broken down into a similar, simpler subset of the original problem.

Eventually the function will call itself at be able to solve the problem - which is known as the base case. This is required to stop infinite recursion.

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

How would you implement a stack in JavaScript?

A

I probably wouldn’t - there is already a stack mechanism in the form of the array with the push and pop methods.

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

How would you implement a queue in JavaScript?

A

I probably wouldn’t, there is already a queue mechanism in Javascript in the form of the array - with the unshift / shift methods.

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

Even though there already exists the queue and the stack - why might you still implement your own?

A

They don’t have a peek method for one, you may also want to use a fixed size of array.

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

What is a priority queue?

A

Like a queue - but each element has a priority associated with it. It’s often implemented with a heap.

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

What are the typical steps in finding a solution using dynamic programming?

A
  1. Find a recursive solution

2. Memorise intermediate steps

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

What are two ways of handling collisions with hash tables?

A

Linear probing… (i.e. if you can’t take the first slot, give it the next available slot) O(n)

Separate Chaining (i.e. each entry in the array is a pointer to a separate array array) O(n/k) where k is the size of the table. However - O(n/k) can be written in worse case scenario as O(n) (because k is fixed)

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

What is the difference between an algorithm that finds a prime based on 2 to n searches, and one that uses the square root?

A

If you have to search from 2 to N the algorithm is around O(n) in terms of speed. This can be VERY long with large numbers. But you can speed this up by using the square root trick. (i.e. a number is a prime if it can’t be divided by any number from 2 - sqrt of n. ) This would give you O(sqrt(n)); complexity

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

What is a stable sorting algorithm?

A

One that preserves the original order of like objects - so if you had two cards, 6 of clubs, and 6 of diamonds, and before the sort they were in that order. A stable sort will retain that order after the sort.

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

What is the entry point for the DOM?

A

Window.documentElement (corresponds to html tag) - can get to the head here… i.e. title etc.

Window.document.body (corresponds to the body element)
WARNING Document.body can be null - especially if you are starting from a script in the head when the body hasn’t loaded yet.

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

What is the difference between an element and a tag?

A

A tag is used in HTML to markup the start and end of an element. It’s literally the opening / closing p.

But an element is the semantics or structure of a part of that page.

So p with text within it would be considered an element, while the p that is used to open the paragraph would be the tag.

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

What is one nice things about the JavaScript concurrency model?

A

Because it’s based on the event loop - which has the concept of run to completion - you shouldn’t end up with functions that are pre-empted by other functions. Each message must be processed completely before the next one is called from the event loop.

The downside is that if a message takes way too long to complete, the user interface can be held up as it is also processed through the event loop - giving users the impression of a sluggish / slow system.

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

Why is the setTimeout’s time only an approximination, and not a guaranteed time.

A

setTimeout puts a message in the queue AFTER the time has passed in the second argument. But if there are other messages in the queue - then they will have to be processed first. This means it cannot guarantee the time it will execute on.

55
Q

Javascript is non-blocking - what does this mean?

A

Things like file IO and XHR requests are made via callbacks and events. This means while the system is waiting on data to come in from a request, other events can be processed.

56
Q

True or false, scope and context are the same thing?

A

False. Scope refers to the visibility of a variable from a given context. Context refers to the way the code was called (or the object to which the function belongs)

Context can be changed by using apply or call (or bind for that matter)

57
Q

When omitting the var keyword - the variable becomes a…

A

an implied global. A property on the window object. (or global object)

58
Q

How can you determine if an object was created from a specific constructor?

A

Use the instanceof operator.

59
Q

Can a javascript constructor return a primitive?

A

No - if no value is specified, it returns an instance of itself. If a primitive (i.e. an int) is returned, then it returns an instance of itself too. BUT if you choose to return an object, then that object is the return value.

60
Q

With regards to ‘this’ in a function - what is the difference between standard function and constructor function?

A

in a standard function this refers to the window object, in a constructor function, ‘this’ refers to the object returned by the constructor function.

61
Q

True or false, an object literal can be used to create privacy?

A

False - only functions can be used to create privacy.

62
Q

What javascript object refers to the application used to view the web page?

A

navigator

63
Q

What object, property combination gives you the protocol used to view a page?

A

location.protocol

64
Q

What should you remember about the last property in an object literal?

A

It shouldn’t be followed by a comma - IE will barf.

65
Q

When you create a DOM click event handler - what is the value of the ‘this’ variable inside the event handler?

A

The DOM element you attached it too (which is why you need to do var self = this)

66
Q

True or false - a function can have it’s own properties and methods?

A

True - the function inherits from Object.

67
Q

Is truthy, the same as true?

A

No - a good example is [] == true;

Now - if ([]) equates to true.

But with == there will coerce the values. true will be coerced to 1 - and [] will be coerced to “”. It will try to get [] to a primitive - using [].valueOf - which doesn’t give a primitive in this case, so it will use [].toString which gives “”.

therefore “” == 1 - this is of course coerced again… 0 == 1 (as empty strings are falsy)
False.

68
Q

How does the garbage collection work in JS?

A

Memory is allocated when a variable is declared, this includes functions allocated to variables, objects etc.

There are two main models of GC, reference counting - which has some issues (cycles).

And then there is mark and sweep. So the browser starts at the root (global object) - and searches the tree. If an object is unreachable, it is marked for deletion and then cleaned up in a later cycle.

This is the most common type of GC in modern browsers, although IE8 which is still in use, uses reference counting which can lead to issues.

You can suggest to the engine that memory should be freed by using delete. But that only works on object properties not set with var.

69
Q

What is a major difference between Array.prototype.map and Array.prototype.forEach?

A

forEach returns undefined and is NOT chainable.

70
Q

Delete on an array item does what?

A

Just sets it to undefined.

71
Q

Why is it risky to assume that a 200 response is the only valid response?

A

Because a 304 (not modified) response is equally valid. It is sent when a conditional get is sent to the server, but false is returned. I.e. the client already has the same representation of the data - and it wont be resent.

Anything other than 200 and 304 means you didn’t get any data.

72
Q

Errors should be thrown…

A

in the low level areas - i.e. libraries, utilities, core etc

73
Q

Try catch blocks should be…

A

at the higher level - client side business logic. Application specific logic.

74
Q

When should you report to the user that there was an error?

A

Only if absolutely necessary - the application should attempt to recover itself. You must determine what are fatal and non/fatal errors and handle reporting based on this.

75
Q

How do you handle event handlers in older browsers?

A

if (window.addEventListener) {
} else {
window.attachEvent()
}

// NOTE: attachEvent (i.e. 8 and earlier) uses onclick instead of click.

76
Q

The target event is…

A

The element the event originated from (may be different to the element the event was assigned to)

77
Q

The srcElement is…

A

the actual element that fired the event

78
Q

What is event bubbling?

A

When an event is fired, say an onclick event, the event is bubbled up the DOM tree. This allows us to do things like event delegation - where a parent or ancestor element can handle the event. Very useful in things like lists of images, where we can have one event handle the event - rather than attaching an event to every img element.

You can prevent an event from bubbling by using evt.stopPropagation.

Event bubbling is now pretty much the standard way of dealing with event propagation in browsers.

79
Q

What is event capturing?

A

Kind of the opposite of event bubbling.

80
Q

What are the three things that happen when a constructor is called with new?

A

A new object is created
It’s prototype is set to the constructors prototype
The constructor is executed with this set to the value of the new object

81
Q

How can you program a constructor defensively such that calling it without new won’t blow things up?

A
function Person() {
    if (this instanceof Person) {
        this.name = "Some guys name";
    } else {
        return new Person();
    }
}

Person.prototype.getName = function () {
console.log(this.name);
}

// This would normally be bad!
var p = Person();

p.getName();

82
Q

Difference between script, script async, script defer

A

Script will start parsing the HTML, and stop when it finds a script tag. It will then request the script, and execute it immediately. Then continue parsing.

With async, it will hit the script tag, and request the file, but continue to parse the HTML. It will run the script as soon as it has downloaded (pausing the parsing).

With defer, it will hit the script tag, download the script asynchronously, and then run the script once the page has been fully parsed.

Use async if the page is modular and doesn’t doesn’t depend on the scripts.

use defer if the page requires the dom to be in place.

BUT IE9 is buggy as shit - so basically don’t use it.

83
Q

What is progressive rendering.

A

useful technique, particularly with mobile or low bandwidth situations. You load images or content only when required

For instance - lazy loading - only load when the images are on page - or about to be on page.

Or prioritize visible content - such as above the fold content.

84
Q

Difference between normalize and resetting css?

A

resetting css is a bit of a shotgun approach, and it tries to remove all browser styles.

normallising tries to make the styles consistent across browsers.

I’d normally try normalising, the normalisers I have seen tend to be more lightweight and there is less work to do.

85
Q

What is block-formatting context?

A

Any time you have a container which is set to float: (anything other than none), overflow:hidden, float left / right or display table, you create a block-formatting context.

All blocks (divs etc) within the block formatting context will default to aligning against the left hand border.

Within a block formatting context, divs may suffer from margin collapse (the div with the tallest margin wins). To fix this, put the div you want to fix the issue for in a block formatting context. (i.e. a new div with overflow set to hidden).

It can be used to fix margin collapses. And also collapsed divs due to a div containing only floated contents. By setting the container to overflow: hidden, it creates a new block context, and fixes the issue.

You can also use it to fix the way text wraps around images. If you want the text to align to the right edge of an image (leaving space under it) - you can set the p to have overflow: hidden, creating a new block formatting context.

86
Q

What is a stacking context?

A

When adding a z-index, the rendering order of a div can be influenced by the z-index. This occurs because a new stacking context is created.

Setting z-index, or non-full opacity to an object creates a stacking context.

87
Q

What are CSS sprites and how would you implement them?

A

You load an image / sprite sheet as the background for an element. Then using the height attribute and the background-position attribute you can set offsets in the sprite sheet.

This can also be used to achieve animation by using the animation attribute in CSS.

background:transparent url(walker_frames.png) 0 0 no-repeat;

You need to set keyframes.

animation: walker 2s steps(10) infinite;

@keyframes walker {
	0% {
		background-position: 0 0;
	}
	100% {
		background-position: 0 -5000px;
	}
}
88
Q

What are some of the things you have to watch when writing efficient CSS?

A

Group common things together and avoid repetition
Avoid using the * selector
Use classes and ID’s over tag names
Avoid redundant selectors
Avoid key selectors that select large number of items

Use a CSS linter

89
Q

How do browsers match selectors?

A

Browser reads the selectors right to left.

It first finds all the elements that match the key selector (right most selector)

Then checks that it matches or is under the next selector to the left and so on.

90
Q

Name two ways to use non-webfonts?

A

@font-face in css

Link to a webfont as as style sheet

91
Q

Explain box model (this answer is from the web)

A

For display purpose, every element in the page is considered a box. The box model refers to the specification of the box attributes such as the width, padding, border and margin.

You can change the box model by setting the box-sizing property. Some values are: content-box (default), padding-box, and border-box)

Content-box: width & height includes content but not padding/border/margin

Padding-box: include up to padding

Border-box: include up to border, but not margin

92
Q

What are the CSS Specificity rules?

A

!important styles beat everything (pretty much)

10000 inline
1000 (id’s)
10 (class, attributes, pseudo classes)
1+ (Pseudo Elements, Elements)

93
Q

Wha tare the three things that are taken into consideration when evaluating the same-origin policy?

A

The protocol, the url and the port. If these don’t match, then a script is marked as potentially malicious.

94
Q

What is the difference between unit tests and integration tests?

A

Unit tests test small individual units of code. Such as a function.

Integration tests test how these units or other units work together as a part of larger piece of software. They are integrated and tested.

95
Q

What is foo.x undefined here?

var foo = {n: 1};
var bar = foo;
foo.x = foo = {n: 2};
A

Because the assignment operator associates right to left.

foo.x = (foo = {n: 2});

But assignments are made left to right. So foo.x exists before the result of foo = {n: 2} exists.

So it exists, then is wiped out by the assignment.

96
Q

Who are some javascript heros?

A
John Resig (creator of jQuery)
Doug Crockford (author)
Cody Lindley (author - dom enlightenment)
MATTIAS PETTER JOHANSSON - Fun Function blog
97
Q

Name the HTTP methods you know

A

Basically correspond to CRUD things

POST - Create
GET - Retrieve
PUT - Update / Replace
PATCH - Update / modify
DELETE - Delete
98
Q

What XMLHttpRequest event do you use to deal with results?

A

XMLHttpRequest.onReadyStateChange

99
Q

What are the rules for implicit type coercion?

A

If the types are the same - use ===

undefined == null

If one is a string, and the other is a number, convert the string to number

If one is a boolean, and the other is a non-boolean, convert the boolean to a number and then compare

While comparing a string, or number to an object, try to convert the object to a primitive type, then compare.

100
Q

What is the value of +’dude’

A

NaN - because + will try to convert ‘dude’ to a number.

101
Q

What is the value of -‘10’ + 5

A

-5 - because - is a unary operator that will convert a string to a number

102
Q
What is the value of a? 
var a = (2, 3, 5);
A

5 - according to the spec, the , operator evaluates left to right and gives you the last value on the right.

103
Q

If var a = 3, b = 5, what is the value of a && b

A

5 - because in logical tests in javascript the value is returned, not true or false.

104
Q

What is the result of -5%2?

A

-1 - the result of a remainder always gets the symbol of the first operand.

105
Q

42.toString()
42..toString()
42 .toString()
(42).toString()

A

error
“42”
“42”
“42”

It’s to do with how the parser lexically parses for valid tokens. 42 on it’s own is not a valid token.

106
Q

What does the following give?

2 in [1, 2]

A

false

Seems wrong - but the indexes of 1 and 2 are actually 0 and 1 - hence 2 is not in there.

107
Q

If you have an array, and you want to pass it to a method that accepts comma separated parameters, how can you do it easily?

A

console.log.apply(console, array);

108
Q

When talking about space complexity of a fibonacci sequence, how deep does the call stack go?

A

Only (n) units deep (i.e. the same as the number we are searching for). This is because when we get to the root of the tree, the recursion begins backtracking. It will then call functions down the right hand leaves of the tree - but it will never get deeper than the original search. So the stack grows, and shrinks continuously until it exhausts all searches.

O(n) complexity

109
Q

What is backtracking?

A

It’s a way of solving problems through recursion. Usually employed if you don’t have enough information to solve a problem at each step. Maze solving is a good example.

110
Q

What does the following pseudo code describe?

boolean solve(Node n) {
            if n is a goal node, return true
            foreach option O possible from n {
                if solve(O) succeeds, return true
            }
            return false
        }
A

Backtracking.

111
Q

How do you normalise a vector?

A

Divide each element by it’s magnitude / length;

|a| = sqrt( x * x + y * y);

a. x = x / |a|;
a. y = y / |a|;

NOTE: This works for the 3D arrays too.

112
Q

Why do we use normalised vectors?

A

Because if we want someone to move a certain distance, say 20 units, then by normalising the position - and multiplying by 20 (the speed) - this gives you a movement of 20 units.

113
Q

Tight coupling is a form of…

A

technical debt.

114
Q

Object composition is where objects use…

A

services from other objects

115
Q

What’s the best way to avoid fragile inheritance chains?

A

Favour composition over inheritances.

116
Q

Simple way to describe Dependency inversion principle?

A

Program against interfaces, not objects.

117
Q

Prototype objects are only found on..

A

Functions - especially constructor functions.

118
Q

Why is it that when you create an object:

var obj = {};

obj.prototype will return false?

A

Because .prototype doesn’t actually point to a prototype. The true pointer is an internal value called [[Prototype]].

This is key - when you create a FUNCTION, you can access it’s .prototype value. BUT when you create an object FROM that function, you will not be able to access the pointer to .prototype, from that object.

function foobar() {};
foobar.prototype // Object {}
var b = new foobar();
b.prototype // undefined

So it makes sense that:

b.constructor.prototype // Object {}
Object.getPrototypeOf(b); // Object {}

Works…

b.constructor.prototype works - because remember, the prototype property only exists on constructor functions!!

NOTE: object literals can also be used the same way - they have constructor properties too - despite not having been constructed.

119
Q

What is the difference between __proto__ and prototype?

A

__proto__ is the variable that is actually followed when looking up methods/properties in the prototype chain.

Prototype is the value on the constructor function which is used to build __proto__ when you use new to create an object.

.prototype does not exist on object instances - it will be undefined.

( new Foo ).__proto__ === Foo.prototype
( new Foo ).prototype === undefined

120
Q

What is the default prototype for functions and objects?

A

Function.prototype

Object.prototype

121
Q

What does Function.prototype.__prototype__ point to?

A

Object.prototype

122
Q

What does the prototype chain look like for a function named Employee (that hasn’t been instantiated?)

A

Employee.prototype - Function.prototype - Object.prototype

123
Q

What does the prototype chain look like for a an object named employee - which was instantiated from the function constructor named Employee.

A

employee(Instance) - Employee.prototype - Object.prototype

124
Q

Give an example of using short circuiting to avoid ‘has no property’ issue.

A

If (obj && obj.property) {

}

125
Q

What will “apple” || true return?

A

“apple”

126
Q

How would you write this ternary expression in shorthand?

param = param ? param : ‘’;

A

param = param || ‘’;

127
Q

Why??

if (“sidewalk”) {
alert(“sidewalk” == false); // => false
alert(“sidewalk” == true); // => false
}

A

Because a non-empty string is truthy.
Then in the alerts - when a string and a boolean are compared. The engine tries to convert to numbers.

false = 0 and “sidewalk” == NaN - Therefore false.

true = 1 and “sidewalk” == NaN - Therefore false

Best way to remember - is that “1” == 1 is true. Because it tries to convert to number, and succeeds.

128
Q

console.log(null == undefined);

A

true

129
Q

How can you force boolean comparison?

A

!a == !b

130
Q

How can you force string comparison?

A

”” + a == “” + b

131
Q

How can you force numerical comparision?

A

+a == +b

132
Q

for in - has one caveat, what’s that?

A

It reaches out and gets properties from the protototype (just one prototype down the chain).

You can use hasOwnProperty to check though.

133
Q

Do you ever use singletons?

A

Yes - but not frequently.

I mean, object literals are essentially singletons - so in that sense, yes. But as a design pattern, only if I have a good reason to.

I might use it for a library for instance - in much the same way as jQuery is essentially a singleton.

But only if it makes sense. Otherwise they can be worse than the problem they are trying to solve (global variables).