JavaScript 3 Flashcards

1
Q

What is a three step ‘algorithm’ for creating a JavaScript object?

A

First, write a constructor function that sets the instance properties of the new object.

Second, define instance methods on the prototype object of the constructor.

Third, define class fields and class properties on the constructor itself.

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

Is there a JavaScript equivalent of the ‘final’ keyword in Java that declares instance variables as constants?

A

No

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

If I want to emulate a static function on a JavaScript object, where do I declare the function?

A

On the constructor

Constructor.myfunc = function() {};

This would allow you to call the function without instantiating an object - you would normally not use the ‘this’ keyword in a method like this.

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

The expression ‘o instanceof c’ returns true if…

A

the object o inherits from c.prototype - the relationship does not have to be direct.

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

In JavaScript - Constructors act as the public identity, but the formal identity resides with the…

A

‘prototype’.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q
Does the following function declaration have a constructor name?
var Complex = function (x) { .... };
A

No

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

Does the following function declaration have a constructor name?

var Complex = function Complex(x) { …. };

A

Yes - it will be Complex.

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

A set is…

A

A data structure that holds a collection of values with no duplicate values.

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

The job of toLocaleString is to…

A

Convert a string in a locale sensitive method

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

The job of valueOf is to…

A

Convert the object into a primitive value when used in a numeric context.

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

What method invokes the toJSON method on an object?

A

JSON.stringify()

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

JavaScript equality operators evaluate object equality by…

A

Reference not the values - i.e. it checks that they point to the same object.

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

How should you implement equality testing in JavaScript?

A

Use a similar method to Java. Define methods such as “equals” - which take one object as an argument and return true or false depending on the result.

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

If the < or <= operators are called on an object, what function is called to perform the test?

A

The valueOf() method is called to see if it can compare using the result of that method.

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

What method should be used instead of using the less than / greater than operators?

A

Using Java conventions - create a method called compareTo. Then pass it the object we are comparing to. Use a test against 0 to determine the result.

i.e.

a b - becomes a.compareTo(b) > 0;
a != b - becomes a.compareTo(b) != 0;

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

B is a subclass of A. If method B.method wants to call the overridden method A.method, what is this called?

A

Method chaining

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

B is a subclass of A. If we want to call the overridden constructor A from B - what is this called?

A

Constructor chaining

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

The key to subclassing in JavaScript is the proper initialisation of the…

A

prototype object - if B extends A, then B.prototype must be an heir of A.prototype

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

What two lines of code are the most important part of subclassing in JavaScript?

A
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B; // Override the inherited constructor property

Without these lines - any objects created are simply subclasses of Object.

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

How would you get the width of a window?

A

window. innerWidth
window. outerWidth

You may have to take into account the scrollbar though

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

Is the use of querySelector and querySelectorAll okay?

A

Yes, most modern browsers support it - there is an IOS8 bug which prevents some selector types working (i.e. a + p) - and IE 8 support is spotty (but should be okay for basic selectors).

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

Write a simple query that returns all elements with the class “foobar”…

A

var allFoobars = document.querySelectorAll(“.foobar”);

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

What selector syntax is used with querySelector and querySelectorAll?

A

Basically the same as CSS - with the exception of older browsers that may only have partial support (i.e. IE) - it’s pretty much the same shit. NOTE: this is because IE 8 does not support CS3, and only parts of CS2.1

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

If you use querySelector on a class, and there are multiple elements with this class, which one does it return?

A

The first one it finds.

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

How can you reference the HTML element directly via JavaScript?

A

document.documentElement

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

What is the best way to determine if JavaScript is running?

A

You can set a class with the value “no-js” on the HTML element.

Then in an IIFE you can get the value of document.documentElement and remove the class “no-js” from that element.

If JavaScript is running, the class is removed. If it is not running, the class remains indicating javascript is not running.

It’s a good idea to do this in pure javascript (not jQuery) and load it in the head. That way it runs before the body loads - minimising any “flash” that may occur due to late loading.

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

True or false, a variable holding a primitive type in Javascript really directly contains the primitive, and not a reference?

A

True

When you assign a primitive value to a variable, a copy of that value is copied into that variable.

So:

var red = "red";
var color = red;

Each one has it’s own copy of “red”.

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

What will the following print out?

console.log(typeof null);

A

object

It’s technically an error in the JavaScript specification

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

Since typeof null returns ‘object’, what’s the best way to tell if you have a null value?

A

Compare directly

if (value === null) {}

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

What is the output for the following two lines?

console. log(“5” == 5);
console. log(“5” === 5);

A

true
false

That’s because == will coerce the value of “5” into an integer.

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

What is the output for the following two lines?

console. log(undefined == null);
console. log(undefined === null);

A

true

false

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

If you have a variable:

var val = true;

What is the value after the following line:

var newval = val.toString();

A

“true”

It will convert true to a string.

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

Primitive values have methods, are primitive values considered to be objects in Javascript?

A

No

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

A javascript object could be thought of as a…

A

hashtable

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

Objects are represented by…

A

reference types

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

Reference values are synonomous with…

A

objects

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

Any function can be a…

A

constructor

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

By convention, constructors begin with…

A

an uppercase letter to differentiate them from other non-constructors

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

Reference types store the object directly in the variable, true or false?

A

false.

They store the address in the variable (and are therefore like a pointer).

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

Removing the reference to an object is referred to as dereferencing in JavaScript - it is essentially the same as deleting the pointer. How do you achieve this in JS?

A
var object = new Object();
object = null;

Assign null to it.

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

What is the output of the following:

var object1 = new Object();
var object2 = object1;

object1. myCustomProperty = “superman”;
console. log(object2.myCustomProperty);

A

Superman

Because they are reference types, they both point to the same object. Adding a property on one, makes it appear on the other.

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

What are the built in reference types?

A
Array
Object
Error
Date
Function
RegExp
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

A ‘literal’ is what?

A

syntax that allows you to define a reference type without explicitly creating an object, using new and the constructor.

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

How do you create an object with the object literal syntax?

A

var object = {
name: “The principles of OOP JS”,
year: 2014
};

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

Which is valid?

var object = { "superman": "yup" }
var object2 = { superman: "Oh yup" }
A

They both are - putting the property name in quotes is not required, but is useful for using names that have spaces or other special characters.

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

The following is logically equivalent to what?

var object = {
“superman”: “yup”,
“chicken”: “soup”
}

A

var object = new Object();

object. superman = “yup”;
object. chicken = “soup”;

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

Does using an object literal (i.e. var obj = { }) call the constructor?

A

No, and that is true for all object literals.

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

How do you declare an array literal?

A

var array = [‘red’, ‘green’, ‘blue’];

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

var array = [‘red’, ‘green’, ‘blue’];

Is equivalent to…

A

var array = new Array(‘red’, ‘green’, ‘blue’);

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

The most common way to declare a function is…

A

To use the literal form.

function reflect(value) {
   return value;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

Declare the following using the constructor form:

function reflect(value) {
   return value;
}
A

var reflect = new Function(“value”, “return value;”);

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

Why is using a constructor to create a function a bad idea?

A

It’s more complicated to read, and impossible to debug (since most debuggers don’t recognise them). They are essentially a black box in the application.

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

Declare a regular expression literal that matches one or more numbers.

A

var regex = /\d+/g;

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

Write the following using the constructor method:

var regex = /\d+/g;

A

var regex = new RegExp(‘\d+’, ‘g’);

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

Why are regex literals preferred over regex constructor form?

A

Because you have to escape the string in the regex constructor form.

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

When would you prefer to use the constructor form of the regex object?

A

When you are constructing a regex from a set of strings.

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

The most common way to access properties in JavaScript is via..

A

dot notation

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

The alternative way from dot notion to access a property is…

A

using brackets and a string (like an array).

var value = MyObject[‘thevalue’];

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

What is another way to write:

array.push(12345);

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

Can you use variables to access the properties within an object?

A

Yes

var propertyname = 'push';
var array = [];
array[propertyname](12345);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
61
Q

Which is the only reference type that does not return ‘object’ when typeof is used on it?

A

Functions. They return ‘function’.

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

How can you determine if a variable is an array?

A

variable.constructor === Array;

You can also use instanceof

console.log(variable instanceof Array);

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

How can you determine if a property of an object is an array?

A

obj.variable && obj.variable.constructor === Array

NOTE: We first determine if the property exists.

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

If you create an array literal (i.e. not calling the constructor), what will the following return?

var variable = [];

console. log(variable.constructor === Array);
console. log(variable instanceof Array);

A

true
true

Even if you haven’t used the constructor, it will still return a valid result.

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

Given a function literal (no constructor used) - what will the following return?

function chicken() {return 10;}

console. log(“Checking for a chicken constructor”);
console. log(chicken.constructor === Function);
console. log(chicken instanceof Function);

A

true
true

Even if you haven’t used the constructor, it will still return a valid result.

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

What is the output of the following:

function chicken() { return 10; }

console. log(chicken instanceof Function);
console. log(chicken instanceof Array);
console. log(chicken instanceof Object);

A

true // Definitely a function
false // Definitely not an array
true // But being a reference type, is an Object

NOTE: instanceof can detect inheritence, every reference type inherits from Object.

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

What is the catch with using instanceof on arrays?

A

Arrays can be passed within frames of a webpage - when you check an array that has come from another frame, the array has lost it’s context, and will not be reported as an array.

To fix this - you should use Array.isArray(variable);

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

What is the gotcha with using Array.isArray(variable).

A

It’s doesn’t work in IE8 - it will work on all ECMAScript 5 environments. It should work in Node.js as well.

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

If you can access methods on a primitive type, why aren’t they considered reference types?

A

Because JavaScript uses primitive wrappers behind the scenes, which encapsulates the primitive type when it’s created.

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

When does the primitive type (string in this case) become autoboxed?

var mystring = "foobar";
console.log(mystring.charAt(0));
A

When the code tries to access the variable like an object (line 2)

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

Why doesn’t the following work?

var num = 10;

num. chicken = “foobar”;
console. log(num.chicken);

A

The autoboxing occurs when num is accessed as an object. However, the primitive wrapper only lasts for the duration of that call - so when we try to access it in line 3, we get ‘undefined’.

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

If temporary objects are created for primitive types, why does the following return false?

var string = "foobar";
console.log(string instanceof String);
A

Because the temporary objects are only created when the variable is read.

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

There is a problem with using objects like a primitive type, what is it?

A

Because objects are not treated the same way as primitive types, you can get unexpected results when testing for truthiness.

var fun = new Boolean(false);
if (fun) {
   console.log("this is fun");
}

Even though fun is false, it will execute the “this is fun” line. This is because objects are always treated as true in a conditional statement.

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

Should you manually instantiate primitive wrappers?

A

You can, but it can cause confusion (i.e. the issue with Boolean objects evaluating to true in a conditional statement, even if the value they contain is false).

Best to avoid it.

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

What are the five primitive types?

A
Strings
Numbers
Booleans
null and 
undefined
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
76
Q

You can use typeof to test for the type of primitive type with the exception of…

A

null - which you should always compare with against null.

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

What distinguishes a function from every other object?

A

An internal property named “[[call]]”

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

Can the internal property (of functions) [[call]] be accessed via code?

A

No

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

ECMA Script defines that the ‘typeof’ operator must return function for any object that has…

A

A property named [[call]]

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

Older browsers may have an issue where RegEx objects are identified as…

A

functions - because they have a [[call]] property. But that is no longer the case, and SHOULDN’T be a problem.

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

Which function declaration type is hoisted, function declaration or function expression?

A

Function declaration

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

Why does function hoisting occur for function declarations?

A

Because the function name is known ahead of time.

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

Will this code work?

var result = add(5, 3);

var add = function(num1, num2) { return num1 + num2; };

A

No - because function expressions aren’t hoisted and the function isn’t declared before it’s used.

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

Does JavaScript use first class functions?

A

Yes

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

Why are JavaScript functions considered first class functions?

A

Because you can use them anywhere you use any other reference type (parameters, assign to variables etc).

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

Why can’t the default behavior of the ‘sort’ method deal with numbers effectively?

A

It converts numbers into a string and sorts them. This will not give you correct numerical sort.

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

How do you make the behavior of the ‘sort’ method work for numbers?

A

Pass it a comparison function

var nums = [1, 2, 5, 4, 3, 6, 7, 9];
nums.sort(function(first, second)) {
    return first - second;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
88
Q

You can pass how many arguments to a function, if the function specifies two parameters?

A

As many as you want - they will be stored in the functions internal “arguments” array.

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

If you want to know the number of parameters a function expects, how do you find this out?

A

Read the length property on the function.

console.log(myfunc.length);

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

What is one of the reasons that a IIFE (Immediately invoked function expression) is actually very useful?

A

They create their own execution contexts, which means all the variables and such within that context are immediately available. For instance, when creating a library of functions, there is risk of collision with variable names in your own application - this will avoid it by creating it’s own context.

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

What is AMD?

A

Asynchronous Module Definition. It’s a specification (seen in Require.JS and Dojo Toolkit etc) that defines how to setup modules for asynchronous loading. This means, rather than loading one JS file after the other, you can load them all nearly simultaneously (even if there are dependencies), which increases load speed, fewer page errors etc).

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

What is the lexical environment in JavaScript?

A

It’s a specification that defines how the identifiers to specific variables and functions relate to each other. It’s basically describing how the code within a function relates to each other based on it’s syntax / indentation etc.

Where this is important is in The Scope Chain. So for instance, the pointer to the Outer Environment (which is set in every execution context) is based on the lexical environment (not where the code is executed). So a function called within another function, if declared at the global level, will have its Outer Environment pointer referencing the global scope.

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

What is the execution context?

A

The lexical environment defines how your code is related to each other (i.e. function blocks, nesting etc). The execution context refers to the currently running lexical environment.

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

The name in a name/value pair may only be defined once in any one…

A

Execution context.

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

What is the simplest possible definition of an object in JavaScript?

A

A collection of name value pairs.

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

When you run a JavaScript program, the javascript engine creates two things for you in the global context - what are they?

A

The global object, and ‘this’.

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

Is the global object always called ‘window’?

A

No - it depends on the environment (i.e. Node.js will be different). However, there is ALWAYS a global object.

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

When we refer to variables that are global - what is the most basic definition of this?

A

Anything that is not inside a function - simple as that.

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

If you have a Chrome console open, what is the easiest way to see the value of a variable?

A

Just type it’s name at the console prompt.

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

What does the outer environment mean, and what is it’s relationship to the global context?

A

The outer environment refers to the encapsulating context of a bit of code. Like a function at the top level, it’s outer environment would refer to the global context.

The global context however doesn’t have an outer environment - as it’s as high as we can get.

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

The execution context is created in how many phases?

A

Two

Creation phase
Execution phase

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

Hoisting often is referred to as function / variable definitions being moved to the top of the code. But this is incorrect - how does it actually work?

A

There are two phases that are run when an execution context is created. The Creation phase and the Execution phase. During the Creation phase, the code is parsed for variables, and memory is allocated for variables and functions. This is called “Hoisting”. The code is not actually being moved. It’s just that the first pass allocated memory for variables/functions, before it’s executed.

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

What happens during the creation phase of an execution context?

A

The global object is created
The this variable is created
The outer environment is set (if valid)
Memory space is allocated for variables/functions (hoisting)

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

Why do functions allocated memory for both their name and content, while variables are only allocated memory - but no values are assigned during hoisting?

A

In order for memory to be allocated during the execution contexts creation phase, memory is assigned for the entire function. For variables, it’s only assigned for the type (not the actual value).

This is because values are assigned to variables during the execution phase.

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

What is the placeholder that is put into a variable during the hoisting stage?

A

undefined

NOTE: This occurs with ALL variables, even ones with a value assigned to it. That’s why you will get an error if you attempt to access the variable before the value is assigned (even though you can see the variable due to hoisting).

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

What is the difference between “not defined” and “undefined”?

A

Even though they seem to be the same thing, they are not. Not defined refers to when the compiler finds a token or variable that is being accessed, that has not been declared anywhere.

Undefined however is actually an internal javascript object that is used to identify variables that have not had a value assigned to them yet.

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

What phase of running a javascript file is an Uncaught ReferenceError (i.e. a variable is not defined) reported?

A

During the execution phase. During the creation phase, no memory is assigned for the variable - during the execution phase it tries to access the variable and fails.

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

Why is it a bad habit to set variables to undefined?

A

Because you are changing the meaning of undefined. By never setting undefined yourself, you can be sure that when you come across the value - it’s because the compiler set the value of the variable to undefined. By not changing the meaning, it will help with debugging.

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

Is JavaScript single threaded?

A

Yes - despite what the browser may do to make it run, the javascript engine will for all intents and purposes, be single threaded.

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

Is JavaScript Synchronous, or asynchronous?

A

Synchronous - because one line is executed at a time, one after the other.

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

Invocation, or Invoking a function is what?

A

Running a function, you do this by using parenthesis.

myFunc();

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

What happens when a function is called in JavaScript?

A

A new execution context is created, and put on top of the execution stack.

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

In the context of the execution stack, which execution context is the one that is running?

A

The one on top of the stack (i.e. the last inserted)

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

If you execute a function a(), how many execution contexts are on the execution stack?

A

Two - the global execution context, and the execution context for a. A will be on top of the stack as long as it is running.

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

If you have the following:

function b() {}
function a() { b(); }
a();

What does the execution stack look like after b is invoked?

A

b() - execution context
a() - execution context
Global Execution Context

With b being on top of the stack

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

When a new function is run, what happens?

A

Every function that is invoked creates a new execution context, which means it goes through the same phases, the creation phase, and the execution phase.

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

What is a “variable environment”?

A

When discussing execution contexts, it refers to the locations that variables are stored. It’s somewhat analogous to scope.

Each execution context has it’s own variables environment, which is why you can create a variable named myVar at global, and function level, and there will be no collisions.

118
Q

With the concept of scope chains in mind, in the following code, what is the output:

function b() { console.log(myVar); }
function a() { var myVar = 2; b(); }
var myVar = 1;
a();
A

It may be tempting to say it’s 2 - because b() is executed within the execution context of a. However, the answer is 1.

This is because the scope chain uses the “outer environment” pointer to determine where to look for the variable. If it doesn’t exist the current execution context, it will check the execution context of the outer environment. It doesn’t necessarily go back through the execution stack.

What the outer environment pointer points to is based on the lexical environment. I.e. How you POSITION your code on the page, has an impact on the scope chain.

I.e. it’s not where the function is called from that defines how the scope chain searches for a variable - it’s where it is written in the file (lexical environment).

119
Q

The scope chain is based on what links?

A

The outer environment pointers - which in turn are based on the lexical environment (i.e. where in the source code the function was written).

120
Q

What is the difference in the execution contexts of the following two bits of code:

function b() { console.log(myVar); }
function a() { var myVar = 2; b(); }
var myVar = 1;
a();
/*----------------*/
function a() { 
    function b() { console.log(myVar); }    
    var myVar = 2; 
    b(); 
}
var myVar = 1;
a();
A

Nothing - they will create the same execution contexts.

121
Q

Given the following code, where do the Outer environment pointers point for each execution context?

function a() { 
    function b() { console.log(myVar); }    
    var myVar = 2; 
    b(); 
}
var myVar = 1;
a();
A

For the execution context of A - it points to the global execution context.

For the execution context of B - it points to the execution context of A.

122
Q

What happens if the variable is not found, and the compiler can’t find the variable in the outer lexical environments execution context?

A

It will then search the outer lexical environment of the outer lexical environment, until it reaches the global context.

123
Q

If JavaScript is Sycnrhonous, how does Asynchronous events work?

A

Events when they are occur are added to the Event Queue. When the main execution stack is empty, the JavaScript engine will then process the event queue.

If the event needs to run a function, the JS engine then creates an execution context for that event. The next event will not be processed until this new execution stack is empty again.

124
Q

Are Asynchronous Events, actually asynchronous?

A

No - they are placed in the event queue Asynchronously by the browser (which is external to the JS engine) - however, the actual events are executed synchronously.

125
Q

Can long running functions interrupt how event handlers are executed?

A

Yes - because it’s not truly asynchronous. If a function takes 5 seconds, then during that time, the events for click (or whatever you’ve setup) will be queueing up in the event queue.

Only once the long running function’s execution context, and the global context are finished, will it check the queue.

126
Q

What kind of ‘typing’ does JavaScript use?

A

Dynamic typing (as opposed to static typing)

127
Q

Is undefined an object, or a primitive type?

A

Undefined is a primitive type

128
Q

There is only one numerical primitive type in JavaScript, what is it, and how is it represented under the hood?

A

It’s Number - and it’s a 64bit floating point number under the hood. No matter what type of number it is intended to be.

129
Q

What is the new primitive type that ES6 adds?

A

symbol

130
Q

Are operators functions?

A

Yes, despite the fact their syntax is different, they are basically functions that operate on usually two parameters, but sometimes one and sometimes three.

131
Q

What is the notation called that describes the way parameters are given to binary operators?

A

infix notation (as opposed to prefix and postfix)

132
Q

What is operator associativity?

A

The order that operator functions get called in. Can either be left associativity, or right associativity.

This is relevant particularly when we have operator precedence, and a number of the operators have the same level of precedence.

133
Q

What is the associativity of the assignment operator?

var a = 2, b = 3, c = 4;
a = b = c;
console.log(a);
console.log(b);
console.log(c);
A

It’s right associativity.

a b and c will be equal to 4.

134
Q

What is coercion?

A

When a type is converted to a second type in order to complete an operation.

135
Q

Why does coercion happen so frequently in JavaScript?

A

Because it’s a dynamically typed language.

136
Q

How would the following be coerced?

var a = 1 + ‘2’;

A

12

The number 1 will be coerced to a string.

137
Q

What is the output of the following, and why?

console.log(3 lt 2 lt 1)

NOTE: I have to use lt rather than the arrow - because even using the HTML code for the lt character doesn’t work properly. Stupid, shithouse design.

A

true

Firstly operator precedence is equal for the two less than operators. And since the associativity is left to right. The left hand expression is evaluated first (i.e. 3 lt 2) which gives false.

Then due to coercion, false becomes 0, and 0 is lt 1 - which of course is true. And hence the output is true.

138
Q

Will undefined and null coerce to the same value?

A

No -

undefined coerces to NaN
null coerces to 0

139
Q

If null coerces to 0 when converting to a number, what does the following produce?

null == 0

A

false - null will not coerce to 0 when testing for equality.

140
Q

Where in code does boolean coercion occur as a matter of course.

A

If statements. Whatever you put in there, whether it’s undefined, null, or empty string. Then it converts to false.

141
Q

What is the caveat when using if statements to coerce a value to true / false?

A

If there is a possibility that the number 0 is a valid (i.e. true) response, you cannot test in this way. As 0 coerces to false. You can then test like this:

if (a || a === 0) {
}

142
Q

In the following statement, which order is the evaluation performed?

if (a || a === 0) {
}

A

The a===0 is performed first, because ‘===’ has a higher precedence than ||.

143
Q

Does the || operator return true / false?

A

No - it actually returns the value in the expression that can be coerced to true. so:

false || ‘chicken’

‘chicken’ will be returned.

144
Q

What is the following code doing?

var a = name || ‘Default Name’;

A

If the value ‘name’ is undefined, then ‘Default Name’ will be used. This is because the || doesn’t actually return true or false, it returns the value that can be coerced to true.

This allows you to write code (like the in the question) that can be used to set defaults.

145
Q

What will be returned in the following code?

“hi” || “hello”

A

“hi”

The closest value to the left that can be coerced to true, will be returned.

146
Q

What is the one caveat with using the following pattern?

var a = value || “10”;

A

If the value could possibly be 0, and be valid, this wont work - because it will evaluate to false, and the default value will be given.

147
Q

Does the script tag create a new execution context?

A

No - basically what happens is that all code within the scripts that are loaded via the script tag are concatenated and run like a single file.

148
Q

How do frameworks typically prevent collisions of their code with other frameworks?

A

They may create the code within a single object, then using the ‘or’ pattern check to see if it’s been defined previously.

window.fwObject = window.fwObject || fwObject

149
Q

What is the computed member access operator?

A

the square brackets, used to access properties on object.

person[];

150
Q

Why would you use the [] operator over the . operator to access objects?

A

You can pass variables to the [] operator. But generally, you’d use the . operator.

151
Q

What is another way to write the expression:

person.address.street;

A

person[‘address’][‘street’];

152
Q

What is another way of writing:

var person = new Object();
person.firstname = "steven";
A

var person = { firstname: ‘steven’ }

153
Q

How do you fake namespaces in JavaScript?

A

You can use objects as containers - and thus namespaces.

var foobar = {};

And add code to foobar - then we have a namespaced location in code inside foobar.

154
Q

What is wrong with the following code (assuming this is the only line of code in the file)?

person.address.street = “8 baltimore street”;

A

It will cause an error because address is not defined. This is because the . operator is left associative. When the code runs, it first looks for address - which is undefined, then tries to look for street, which is attached to an undefined object. Basically the expression boils down to:

undefined.street = “8 baltimore street”;

which cannot / will not work.

155
Q

Is JSON the same as Object Literal notation?

A

No

156
Q

What is the difference with regards to key-pairs in JSON as compared with Object literal notation?

A

In JSON the key values HAVE to be wrapped in quotes - whereas in Object literal notation - it’s optional.

157
Q

All JSON is valid Object literal notation syntax, true or false?

A

True

158
Q

All object literal notation syntax is valid JSON, true or false?

A

False

159
Q

How do you convert a JavaScript object into a string?

A

JSON.stringify(myObject);

160
Q

How you convert a string into a javascript object?

A
var str = '{ "firstname": "Caino" }';
JSON.parse(str);
161
Q

Functions are…

A

objects

162
Q

First class functions are…

A

You can do the same thing with functions, that you can do with other types (i.e. assign to variables, pass to functions).

163
Q

What are the two additional properties that functions have, that objects do not?

A

Name - Can be anonymous

Code - contains the code of the function (invokable by using the () operator)

164
Q

What’s the difference between using console.log on an object, and on a function?

A

With an object the contents of the object will be printed to the console. With a function, the actual code will be printed (but you wont be able to see any properties).

165
Q

Whats the major difference between an expression and a statement?

A

A statement does work, an expression is a unit of code that results in a value.

166
Q

What does a function statement look like?

A
function foobar() {
   console.log('hi');
}
167
Q

What does a function expression look like?

A
var anony = function() {
   console.log('hi');
}
168
Q

What is the ‘name’ value of the following function declaration?

var foobar = function() {

}

A

It doesn’t have one - it will be anonymous

169
Q

What is the problem with the following code?

foobar();

var foobar = function() { console.log(‘chicken’); |

A

Function expressions are not hoisted, therefore it will be undefined.

170
Q

What is one reason you might actually want to provide a name for an anonymous function?

A

When debugging, you’ll see the name of the function in the stack trace.

NOTE: Not all browsers support this.

171
Q

If you provide a name to a function expression, is it still called an anonymous function expression?

A

No, it’s now called a named function expression.

172
Q
If you have the following code:
var a = 2;
var b;

b = a;

What is b actually pointing to?

A

b is actually pointing to a second copy of the value in a (2). The variables a and b contain different memory addresses.

This is called “by value”

173
Q

What is meant by “by value”

A

When assigning a variable to another variable, the value that is pointed to by the first variable is copied to a new location - and the variable has a new pointer to it.

174
Q

What values are by reference in JavaScript?

A

Objects / functions

175
Q

What values are by value in JavaScript

A

Primitive types

176
Q
Given the following code:
var a = { greeting : 'hello' }
var b = a;
a = { animal: 'chicken' }

What does a and b contain?

A

a will contain { animal: ‘chicken’ }, b will contain { greeting: ‘hello’ }

This is because the = operator sets up new memory, so by value doesn’t apply when a new variable detected.

177
Q

What does the ‘this’ variable point to in the following code (assuming it’s the only code in the file)?

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

The window object

178
Q

Is the following code valid, if so why?

function a() {
    this.newVariable = 10;
}

console.log(newVariable);

A

Yes, because the this variable in the function points at the window (or global) object.

179
Q

Why is it that the this variable points to the window object when you declare a global function?

A

Because the function is essentially attached (as a method) to the window / global object. The this variable doesn’t usually refer to the method itself, but it’s enclosing object. (think OO programming).

180
Q
What will the "this" variable point to here?
var c = {
   log: function() {
      console.log(this);
   }
}
c.log();
A

The c object.

181
Q
What is the value of a.name after executing the following code?
var a = {
    name: 'chicken',
    log: function() {
    this. name = 'dog';
    console. log(this.name);
        function changeName(newname) {
            this.name = newname;
        }
    changeName('bird');
    console.log(this.name);
} }
A

Dog. This is due to a bug in JavaScript - the changeName function within the log method, will attach the name variable to the global object, as if the function was declared at global scope. You might have expected that it would in fact set the name on the a object to ‘bird’ - but in fact no, it doesn’t.

This is because when the execution context of the internal function (changeName) is created, it’s this variable is pointing at the global object.

182
Q

What pattern can we use to solve the issue the this variable pointing to the global object, for functions that are created within methods of an object?

A

You can store a reference to the this object at the first level of the method.

var a = {

name: 'chicken',
log: function() {

    var self = this; // THIS IS THE PATTERN

    self. name = 'dog';
    console. log(self.name);
        function changeName(newname) {
            self.name = newname;
        }
    changeName('bird');
    console.log(self.name);
} }
183
Q

Can a function be stored in an array?

A

Yes

184
Q

When the execution context is created for a function, what keyword is setup to store the parameters that are passed to the function?

A

The ‘arguments’ keyword

185
Q

Can you set a default value for a parameter in JS?

A

No - but you will be able to in ES6.

186
Q

Is the arguments variable that is found in functions an array?

A

No - it’s array ‘like’. You can see this when you look in the console, the brackets for arguments is italicised. This is indicating it’s not actually an array. It doesn’t have all the features of an array.

187
Q

What is a SPREAD?

A

It’s the replacement for the “arguments” variable found within functions. It will allow you to specify a name of an array like structure that will store any additional values that are passed to a function.

function foobar(a, b, c, …other) {

console. log(arguments);
console. log(other);

console.log("In other"); }

foobar(‘a’, ‘b’, ‘c’, ‘d’, ‘e’);

// NOTE: d and e will be elements within the ‘other’ array

188
Q

Is arguments going to be deprecated in ES6?

A

Yes.

189
Q

What is one approach to dealing with the fact JS doesn’t have function overloading?

A

Generally it’s not an issue, since we can pass as many or as few parameters as we want to a function. But one method is to wrap our calls in different functions.

function greet(firstname, secondname, lang) {}

function greetEnglish(firstname, secondname) {
    greet('Chicken', 'Steve', 'en');
}
function greetSpanish(firstname, secondname){
    greet('Chicken', 'Licken', sp');
}
190
Q

What is wrong with the folllowing code?

function foobar() {
    return 
    {
        firstname: 'chicken'
    }
}

foobar();

A

Because the opening bracket of the object literal is placed on next line after the return, the syntax parser will automatically insert a semicolon. That means this code is simply running:

return;

And will be undefined. You’d have to make sure the opening bracket is on the same line as the return.

191
Q

Why do people always write javascript with the { after the functions / statements etc.

A

It’s not required, and often it’s just style, but there is also an argument to be made that it’s good for muscle memory - i.e. in some cases (like declaring an object literal after a ‘return’ statement, you MUST put the opening brace on the same line as the return). Therefore, by just making this a habit, it will avoid long term issues.

192
Q

Which variables are attached to the global object in the following code:

function foobar() {
   var a = 10;
   b = 20;
   var c, d;
}
A

Only the variable b.
a and c is declared with var, and is local to foobar. With d, even though it’s separated by a , - it is still declared with var according to the parser.

193
Q

What is an IIFE?

A

Immediately Invoked Function Expression.

var foobar = function() {
    return value;
}();
194
Q

Why do IIFE’s work, what property that functions have makes this possible?

A

The fact that every function is essentially an object that has a code property that contains the functions code - means you can actually invoke the function as it’s created and run the code immediately. Essentially, you can directly invoke the function expression by using parenthesis.

195
Q

When you write an IIFE like this, what gets assigned to foobar?

var foobar = function(value) {
    return 'Hello' + value;
}('Steve');
A

Hello Steve

The function object is no longer assigned (as per a typical function expression) - it’s the result of the function.

196
Q

What is wrong with the following code?

function(value) {
    return 'Hello' + value;
}
A

Because it’s an expression - (i.e. there is no function name, so it’s not a statement), then it’s going to throw an error.

197
Q

How do you write an IIFE that simply runs without assigning a value to a variable?

A

var value = ‘chicken’;

(function(value) {
return ‘Hello’ + value;
}(value));

198
Q

Which is the correct way to invoke an IIFE?

}(anyvars));
or
})(anyvars);

A

Either is actually find - there is not a specifically correct form of this syntax. However, you must be consistent.

199
Q

Does an IIFE have it’s own execution context?

A

Yes - and that means it encapsulates it’s variables.

200
Q

What is one purpose for an IIFE?

A

You can use it as a kind of namespacing - for instance, if you make a library, and you want to make sure no other code can colide with it - then you can wrap it in an IIFE. The IIFE won’t collide with anything because it’s anonymous.

201
Q

How would you access the global object from within an IIFE?

A
(function(global) {
    // Do stuff with the global object
}(window));
202
Q

Why would you use the name “global” inside the IIFE rather than “window” which is the global object?

A

Because “window” may not be the global object in all environments - particularly on the server. But you will still want a global object reference.

203
Q

How would you invoke the following code, such that you pass it both the “whattosay” variable and the “name”?

function greet(whattosay) {
    return function (name) {
        console.log(whattosay + ' ' + name);
    }
}
A

greet(‘Hi’)(‘Tony’);

204
Q

Why does the variable “whattosay” able to be accessed AFTER the call?

function greet(whattosay) {
    return function (name) {
        console.log(whattosay + ' ' + name);
    }
}
var say = greet('Hi');
say('Tony'); // Why do I still get access to hi here?
A

Because it’s a closure. A closure will maintain the variables from the context that it was called in - and be able to access them.

205
Q

When an execution context is finished, are variables automatically removed with the context when it’s popped off the stack?

A

No - they are in fact treated separately - due to garbage collection. If there is a reference to those variables (i.e. from a closure) then they will remain until there is no longer any references.

206
Q

How does a the code within a closure find a variable it’s referencing, if the surrounding execution context is no longer on the stack?

A

Because the variables still exist in memory (as there are references to them). The closure will use the scope chain to find them, and since the closure still has a reference to the outer functions memory, it will be able to find the variables.

This is sometimes referred to as “closing in” - the execution context of the closure has “closed in” the variables it would have had access too anyway.

207
Q

What is the gotcha with the following code:

function buildFunctions() {
    var arr = [];
for (var i = 0; i
A

When you access the functions:

var myfunc = buildFunctions();

myfunc0;
myfunc1;
myfunc2;

This will output:

3
3
3

This is because the functions are referencing the final state of the outer counter, not actually storing it’s value each time.

208
Q

What is the name of a variable that is outside of a function, but accessible as a result of being a part of a closure?

A

A “free” variable.

209
Q

How would you fix the following code in ES6, such that the following code would operate as expected (outputing 0, 1, 2)?

function buildFunctions2() {
    var arr = [];
for (var i = 0; i
A

You can use the ‘let’ declaration syntax, which will do the trick. They become sub-segmented as separately scoped variables.

function buildFunctions2() {
    var arr = [];
for (var i = 0; i
210
Q

How would you fix the following code in ES5, such that the following code would operate as expected (outputing 0, 1, 2)?

function buildFunctions2() {
    var arr = [];
for (var i = 0; i
A

You can use an IIFE to create individual execution contexts that store the value of i at each iteration in it’s execution context.

function buildFunctions2() {
    var arr = [];
for (var i = 0; i
211
Q

How can you use closures to make a function factory?

A

function makeGreeting(language) {

    return function(firstname) {
        if (language === 'en') {
            console.log('Hello ' + firstname);
        }
        if (language === 'es') {
            console.log('Hola ' + firstname);
        }
    }
}
var greetEnglish = makeGreeting('en');
var greetSpanish = makeGreeting('es');

greetEnglish(‘Jizzbo’);
greetSpanish(‘Balthazar’);

212
Q

Functions being objects, they get access to three special functions that are useful when dealing with the ‘this’ variable. What are they?

A

Call
Apply
Bind

213
Q

In the following code, logName is external to the person object - how would you convert this code, so that it will run?

var person = {
    firstname: 'John',
    getName: function() {
        var fullname = this.firstname;
        return fullname;
    }
}
var logName = function() {
    // This will cause an error
    console.log('Logged: ' + this.getName());
}
A

You need to bind the person object to the logName function:

var logPersonName = logName.bind(person);
logPersonName();

This will make sure logName is executed such that it’s execution context has it’s external pointer pointing at the person object.

214
Q

Assuming we have a person object, and we want to access one of it’s methods using the ‘this’ variable - how could we do it in a different way to this code:

var person = { // stuff };

var logName = function() {
    console.log('Logged: ' + this.getName());
}
var logPersonName = logName.bind(person);
logPersonName();
A
var logName = function() {
    console.log('Logged: ' + this.getName());
}.bind(person);
215
Q

What is the purpose of the call method on a function?

A

It invokes the function and sets the ‘this’ variable to the object passed to it.

myFunc.call(objectname, param1, param2);

NOTE: Parameters are optional

216
Q

What is one difference between bind and call?

A

Bind makes a copy of the function, while call actually executes it.

217
Q

What is the difference between ‘call’ and ‘apply’?

A

They are basically exactly the same. Call and Apply will invoke the function (instead of copying it like bind does) - but Apply requires any parameters passed to it to be in an array form.

myFunc.apply(myObj, [param1, param2]);

218
Q

Can you use call and apply on an IIFE?

A

Yes - although, it wont be an IIFE anymore, as you don’t use the () operator to invoke it - you use call/apply to invoke it.

(function(param1) {

}).call(myobject, param1);

219
Q

What is function borrowing?

A

Using call or apply, you can borrow the functions from one object, and use the data from another object on it. i.e.

var person1 {
    name: 'sue',
    getName: function() {
        console.log(this.name);
    }
}

var person2 {
name: ‘BillyBob’
}

person1.getName.call(person2);

220
Q

When you use bind to pass a variable to a function, what happens to that parameter?

A

The parameter is permanently set. Therefore you can create a function like such

function multiply(a, b) {
    return a * b;
}

var multiplyByTwo = multiply.bind(this, 2);
// Then use it, but you only pass the second
// parameter
console.log(multiply(10));
// Results in:
20

221
Q

What will be the result of the following function:

function multiply(a, b) {
    return a * b;
}
var multiplyByTwo = multiply.bind(this, 2);
console.log(multiplyByTwo(3, 10));
A

The first parameter given is actually used as the second parameter (since the function was bound - and the first parameter was fixed at that point). The second parameter passed to the function will be essentially ignored.

222
Q

What is function currying?

A

Creating a copy of a function, but with some preset parameters. Very useful in mathematics libraries.

223
Q

The function passed to mapForEach only makes use of one parameter - how could you pass it a custom function that would would allow you to use both a limiter and the item to perform a comparison. i.e. “return limiter > value”.

function mapForEach(arr, fn) {
    var newArr = [];
    for(var i = 0; i
A

You can use bind to fix the first parameter.

var arr1 = [1, 2, 3];
var checkLimit = function(limiter, item) {
     return limiter > item;
}

var arr2 = mapForEach(this, checkLimit.bind(this, 1));

NOTE: ‘this’ needs to be passed - but isn’t used. 1 is the limit, so anything greater than 1 will return true. Bind makes a copy of the function checkLimit and forces the first paramter

224
Q

Do all objects have a prototype property?

A

Yes, even functions

225
Q

In functional programming you should be careful not to…

A

mutate data passed into a function. It’s fine to return NEW data, but you shouldn’t mutate data coming into a function.

226
Q

Can a prototype have it’s own prototype?

A

Yes

227
Q

If you try to access a member variable, and it doesn’t exist on the object, or its prototype, what will the javascript engine do next?

A

It will chck to see if it exists on the prototypes prototype (and so on, until it can’t search anymore).

228
Q

When an object has a prototype (and that prototype may have another prototype) - what is this called?

A

The prototype chain

229
Q

Why shouldn’t you set your prototype directly?

A

It’s a performance issue

230
Q

How do you set the prototype of an object directly?

A

obj1.__proto__ = obj2;

231
Q

When you call an inherited method, the this variable works correctly, why is this?

A

The execution context of the method points to the calling object, not the one that it was created on.

232
Q

Rather than calling bind all the time, how could you wrap a function in such a way, that you can preset the bound value?

A
var checkLimit = function(limiter) {
    return function(limiter, value) {
        return value > limiter;
    }.bind(this, limiter);
}

NOTE: That we do the bind within the function, and that function that is created is returned to the caller.

233
Q

In functional programming you should be careful not to…

A

mutate data passed into a function. It’s fine to return NEW data, but you shouldn’t mutate data coming into a function.

234
Q

What does an object in javascript have it’s __proto__ property set to?

A

Object {}

235
Q

What does a function have it’s __proto__ property set to?

A

function Empty() {}

236
Q

What does an array have it’s __proto__ property set to?

A

[]

Yes - this is an object

237
Q

How do arrays, objects, functions etc have access to default functions and properties (such as apply, call etc)?

A

They are all objects, and their __proto__ property points to a default object provided by the javascript engine. That object has the appropriate methods / properties for that object type. Thanks to the prototype chain, it can find the function you request (on the prototype)

238
Q

If you check the __proto__ property of an object, and look at IT’s __proto__ property, what will it point to?

A

Object {}

239
Q

What is at the bottom of the prototype chain for all objects?

A

Object{}

240
Q

What is the value of __proto__ for the built in Object{}?

A

null

Since it’s bottom of the chain - it makes no sense for it to have any links to a prototype object.

241
Q

What is the prototype of a functions prototype?

var a = function() {};
a.\_\_proto\_\_.\_\_proto\_\_;
A

Object{}

242
Q

How do you get a list of all the properties on an object?

A

for (var prop in myObject) {

}

243
Q

How do you list the values of all the properties on an object?

A

for (var prop in myObject) {
console.log(prop + ‘: ‘ + myObject[prop]);
}

244
Q

If you use the “for in” statement on an object - does it get things off the prototype as well as the object itself?

A

Yes - it gets it from both.

245
Q

If you are using the “for in” statement to report all the properties on that object, how do you make sure they are TRULY properties on that object, and not part of the prototype?

A

You can use the function “hasOwnProperty”

for (var prop in myObj) {
    if (myObj.hasOwnProperty(prop) {
         // print stuff out
    }
}
246
Q

What data is being checked by the hasOwnProperty?

A

the property metadata.

247
Q

Why is the following code a bad idea?

function Person() {
   this.name = "Steveo";
   return { lastname: 'Billyblogs' };
}

var newObj = new Person();

A

When you are using new on a function constructor, you should never return a value in that function - it will get in the way of the JavaScript engines process. (i.e. newObj will not be equal to a Person object.)

NOTE: It is possible to return a value in a function constructor, as long as that is basically the object that was created by new. See jQuery library for example: return jQuery.makeArray( selector, this );

248
Q

What is the name of a function that is used specifically to create objects?

A

function constructor

249
Q

What does the new operator actually do to a function constructor?

A

It creates a new empty object (of the type of the function) and sets the internal this property to point to it. It then returns a pointer to that object. NOTE: It also invokes the function constructor as part of this process.

250
Q

Do function constructors take parameters?

A

Yes - like any other constructor in OO programming.

function foobar(name) {
   this.name = name;
}
251
Q

The prototype property exists on all functions, regardless of whether it’s being used as a function constructor, true or false?

A

true.

252
Q

Why wouldn’t you just add methods to the function constructor, rather than it’s prototype?

A

Because each time you create that object, you will be creating new memory to store that method. By adding it to the prototype, you share that memory between every object that was created via the prototype property.

253
Q

What is the difference between __proto__ and prototype?

A

__proto__ is the ACTUAL object that is used in the prototype chain to look up properties and methods. function.prototype is the object that is used to create the __proto__ when you use new.

254
Q

Why are built in constructors for primitive types (Numbers, Boolean, String) are potentially dangerous?

A

By using built in function constructors to create primitive types, you run the risk of causing problems with the === operator (because a primitive and a value created from a function constructor will not be equal when using the === operator).

The important takeaway is that using new with a function constructor (even an inbuilt one) - creates an object, not a primitive, and that can make code confusing.

255
Q

If you get an undefined error when you use an object created from a function constructor - what’s likely the cause?

A

You forgot the ‘new’ operator when creating the object.

256
Q

What convention can you employ to try and mitigate the potential to forget to call ‘new’ when using a function constructor?

A

You can make sure you name all of your functions that are function constructors with the first letter capitalised. This can give you a visual clue when scanning for errors.

257
Q

What are some examples of internal function constructors in JavaScript?

A

Number
String
Boolean

258
Q

When you create a Number like such:

var a = new Number(10);

Are you creating a primitive?

A

No - you creating an object, with the primitive (number 10) ‘boxed’ inside.

259
Q

How do you create an object using the “create” method?

A
var person = {
   firstname: 'Default',
   greet: function() { return 'hi ' + this.firstname; }
}

var john = Object.create(person);

john. firstname = “John”;
console. log(john.greet());

260
Q

Is the following code valid?

String.prototype.isLengthGreaterThan = function(limit) {
return this.length > limit;
}

A

Yes - but… you have to be careful. This is very powerful.

261
Q

The following is valid:
“string”.length

Is the following valid?
3.isGreaterThan();

(NOTE: I added the isGreaterThan function to the prototype - so it’s a valid function)

A

No - the JavaScript engine will automatically convert a string to an object, but numbers are not automatically converted.

262
Q

When dealing with dates - what’s a good library to use?

A

moment.js

263
Q

When is using the function constructor of a primitive type wrapper a desired feature?

A

When converting a value - however, we don’t use the new operator in this case. And thus we are not creating an object.

264
Q

the “for in” pattern works fine with arrays (because they are objects after all) - but why shouldn’t you use it? And what should you use?

A

You shouldn’t use it because frameworks and other code may add properties (including functions) to the base array prototype. If it does that - they “for in” will output those properties or methods as part of the array, screwing over your code. That’s because even the values you store in an array, are just a key / value pair.

You should use a standard for loop.

265
Q

What is a polyfill?

A

It’s code that adds functionality that older engines / browsers may lack.

266
Q

How do you create an object using the “create” method?

A
var person = {
   firstname: 'Default',
   greet: function() { return 'hi ' + this.firstname; }
}

var john = Object.create(person);

john. firstname = “John”;
console. log(john.greet());

267
Q

What will

var a = 3;
console.log(typeof a);

output?

A

number

NOTE: It’s not uppercase - it’s just a string describing the type.

268
Q

What will

var a = "foobar";
console.log(typeof a);

output?

A

string

NOTE: It’s not uppercase - because the engine is just stating what it is - it’s not an object

269
Q

What will

var a = [];
console.log(typeof a);

output?

A

object

  • NOTE: This is a problem!
270
Q

How can you determine whether a variable is an array?

A
var a = [];
console.log(a.prototype.toString.call(a));

NOTE: This will report:

[object Array]

271
Q

If you use “use strict” at the function scope - does that allow “errors” to be made outside of that scope?

A

Yes - you can have code outside that function that will run fine - but will not run fine inside that execution context because of the “use strict” tag.

272
Q

What is one caveat with using the “use strict” flat at the top of a file?

A

When pushing scripts live, they may be concatenated, and files that weren’t meant to have “use strict” now have it included.

273
Q

How do you implement method chaining?

A

Make sure your functions return the ‘this’ variable. That way you can chain methods together, with each one affecting the original object.

274
Q

You don’t always have access to the console in JavaScript (different hardware / environment) - how do you guard against this?

A

if (console) {
console.log(“Stuff!”);
}

NOTE: Internet explorer doesn’t have a console object unless the console is open.

275
Q

Why might you see a semi colon before an IIFE in a library?

;(function() {
   // Do stuff here?
}());
A

It is a safety measure - if you are including other libraries before your code, the programmers of that code may forget to close out it’s semi colons properly. This will make sure your code is robust.

It’s not always used though - but you may see it.

276
Q

What is transpiling?

A

When a compiler takes one language and compiles it to another.

277
Q

Name some JavaScript anti-patterns?

A
Poluting the global namespace
Inline JavaScript
Using eval() incorrectly
document.write()
modifying default classes prototypes
278
Q

How do you insert a cell into a table in JavaScript?

A
var myTab = document.getElementById('myid')
var row = myTab.insertRow(0)
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
279
Q

How would you create a button using a bootstrap icon from scratch in javascript.

A

button1icon = document.createElement(‘SPAN’);
button1icon.className = ‘glyphicon glyphicon-remove’;
button1 = document.createElement(‘BUTTON’);
button1.className = ‘btn btn-xs btn-danger’;
button1.appendChild(button1icon);
cell4.appendChild(button1);

NOTE: Using bootstrap - and cell4 was previously created.

280
Q

What’s the best way to avoid global pollution of variables?

A

Use an IIFE to wrap the code.

281
Q

What is one way to create a module?

A

Encapsulate all your module code within an IIFE and store that in a variable. Then within the IIFE, return an object that exposes the desired methods.

var fooController = (function() {
    function playTrack() { // Do code stuff here}    
    return {
       play: function() {
           play: playTrack();
       }
    }
}());

fooController.play();

282
Q

What is FOUC?

A

Flash of Unstyled Content - i.e. when the browser displays the page briefly, but it has not been styled.

283
Q

What is a getter / setter in Javascript?

A

It’s a syntax that binds an object property to a function that is called when that property is looked up.

{
    set myValue() {
    },
    get myValue() {
    }
}
284
Q

Setters and getters are a really useful feature, however, they are not supported by browsers as recent as IE9 - what can we do to support the same functionality?

A

Instead of using:

set myValue() { }

We can give the object a property called set.

set: function() { }

And instead of assigning:

myObject.myValue = 0;

We do:

myObject.set(0);

285
Q

textContent is a property that exists on modern browsers - but does something very similar to innerHTML - rather than giving the code both options - why not just stick with innerHTML since it’s used almost everywhere?

     if (element.textContent != null) {
          element.textContent = text;
     } ese {
          element.innerHTML = text;
     }
A

textContent is newer, and liekly a better performing method, so it makes sense to check that it exists and use it if so.

286
Q

What does a facade pattern do?

A

It provides one interface which abstracts away a more complex interface (or set of interfaces). It is a higher level interface, that makes working with the lower level interface(s) easier.

287
Q

What is one common but simple use for the facade pattern in JavaScript?

A

To hide the complexities inherent with multiple browser API’s (backwards compatibility).

288
Q

The Adapter pattern is often used to…

A

Convert between two incompatible interfaces.

289
Q

What is the difference between an adapter and a facade pattern?

A

At first, it can seem like they are very similar. However, a facade is about simplifying an interface. It may take a single input and perform multiple actions behind the scenes.

However an adapter is more about linking two incompatible interfaces.

290
Q

What does document.createTextNode do?

A

It creates a bit of text that would normally be placed within an element (div etc). It’s very similar to myElement.innerHTML.

291
Q

How could you use ‘hasOwnProperty’ to choose which method to call?

A

Say you have an object literal - and the function names match the potential input to a function. i.e. you pass in an element name ‘td’ to be created. Your object literal that has creates the td element has a function called td. You can use logic like:

if (elementHandlers.hasOwnProperty(‘td’)) {
elementName = elementHandlers‘td’;
}

NOTE: You wouldn’t actually pass ‘td’ to the functions, you’d use a variable. That way you can have this single bit of code call whatever function matches the input by the user.