JavaScript 3 Flashcards
What is a three step ‘algorithm’ for creating a JavaScript object?
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.
Is there a JavaScript equivalent of the ‘final’ keyword in Java that declares instance variables as constants?
No
If I want to emulate a static function on a JavaScript object, where do I declare the function?
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.
The expression ‘o instanceof c’ returns true if…
the object o inherits from c.prototype - the relationship does not have to be direct.
In JavaScript - Constructors act as the public identity, but the formal identity resides with the…
‘prototype’.
Does the following function declaration have a constructor name? var Complex = function (x) { .... };
No
Does the following function declaration have a constructor name?
var Complex = function Complex(x) { …. };
Yes - it will be Complex.
A set is…
A data structure that holds a collection of values with no duplicate values.
The job of toLocaleString is to…
Convert a string in a locale sensitive method
The job of valueOf is to…
Convert the object into a primitive value when used in a numeric context.
What method invokes the toJSON method on an object?
JSON.stringify()
JavaScript equality operators evaluate object equality by…
Reference not the values - i.e. it checks that they point to the same object.
How should you implement equality testing in JavaScript?
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.
If the < or <= operators are called on an object, what function is called to perform the test?
The valueOf() method is called to see if it can compare using the result of that method.
What method should be used instead of using the less than / greater than operators?
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;
B is a subclass of A. If method B.method wants to call the overridden method A.method, what is this called?
Method chaining
B is a subclass of A. If we want to call the overridden constructor A from B - what is this called?
Constructor chaining
The key to subclassing in JavaScript is the proper initialisation of the…
prototype object - if B extends A, then B.prototype must be an heir of A.prototype
What two lines of code are the most important part of subclassing in JavaScript?
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 would you get the width of a window?
window. innerWidth
window. outerWidth
You may have to take into account the scrollbar though
Is the use of querySelector and querySelectorAll okay?
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).
Write a simple query that returns all elements with the class “foobar”…
var allFoobars = document.querySelectorAll(“.foobar”);
What selector syntax is used with querySelector and querySelectorAll?
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
If you use querySelector on a class, and there are multiple elements with this class, which one does it return?
The first one it finds.
How can you reference the HTML element directly via JavaScript?
document.documentElement
What is the best way to determine if JavaScript is running?
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.
True or false, a variable holding a primitive type in Javascript really directly contains the primitive, and not a reference?
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”.
What will the following print out?
console.log(typeof null);
object
It’s technically an error in the JavaScript specification
Since typeof null returns ‘object’, what’s the best way to tell if you have a null value?
Compare directly
if (value === null) {}
What is the output for the following two lines?
console. log(“5” == 5);
console. log(“5” === 5);
true
false
That’s because == will coerce the value of “5” into an integer.
What is the output for the following two lines?
console. log(undefined == null);
console. log(undefined === null);
true
false
If you have a variable:
var val = true;
What is the value after the following line:
var newval = val.toString();
“true”
It will convert true to a string.
Primitive values have methods, are primitive values considered to be objects in Javascript?
No
A javascript object could be thought of as a…
hashtable
Objects are represented by…
reference types
Reference values are synonomous with…
objects
Any function can be a…
constructor
By convention, constructors begin with…
an uppercase letter to differentiate them from other non-constructors
Reference types store the object directly in the variable, true or false?
false.
They store the address in the variable (and are therefore like a pointer).
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?
var object = new Object(); object = null;
Assign null to it.
What is the output of the following:
var object1 = new Object(); var object2 = object1;
object1. myCustomProperty = “superman”;
console. log(object2.myCustomProperty);
Superman
Because they are reference types, they both point to the same object. Adding a property on one, makes it appear on the other.
What are the built in reference types?
Array Object Error Date Function RegExp
A ‘literal’ is what?
syntax that allows you to define a reference type without explicitly creating an object, using new and the constructor.
How do you create an object with the object literal syntax?
var object = {
name: “The principles of OOP JS”,
year: 2014
};
Which is valid?
var object = { "superman": "yup" } var object2 = { superman: "Oh yup" }
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.
The following is logically equivalent to what?
var object = {
“superman”: “yup”,
“chicken”: “soup”
}
var object = new Object();
object. superman = “yup”;
object. chicken = “soup”;
Does using an object literal (i.e. var obj = { }) call the constructor?
No, and that is true for all object literals.
How do you declare an array literal?
var array = [‘red’, ‘green’, ‘blue’];
var array = [‘red’, ‘green’, ‘blue’];
Is equivalent to…
var array = new Array(‘red’, ‘green’, ‘blue’);
The most common way to declare a function is…
To use the literal form.
function reflect(value) { return value; }
Declare the following using the constructor form:
function reflect(value) { return value; }
var reflect = new Function(“value”, “return value;”);
Why is using a constructor to create a function a bad idea?
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.
Declare a regular expression literal that matches one or more numbers.
var regex = /\d+/g;
Write the following using the constructor method:
var regex = /\d+/g;
var regex = new RegExp(‘\d+’, ‘g’);
Why are regex literals preferred over regex constructor form?
Because you have to escape the string in the regex constructor form.
When would you prefer to use the constructor form of the regex object?
When you are constructing a regex from a set of strings.
The most common way to access properties in JavaScript is via..
dot notation
The alternative way from dot notion to access a property is…
using brackets and a string (like an array).
var value = MyObject[‘thevalue’];
Can you use variables to access the properties within an object?
Yes
var propertyname = 'push'; var array = []; array[propertyname](12345);
Which is the only reference type that does not return ‘object’ when typeof is used on it?
Functions. They return ‘function’.
How can you determine if a variable is an array?
variable.constructor === Array;
You can also use instanceof
console.log(variable instanceof Array);
How can you determine if a property of an object is an array?
obj.variable && obj.variable.constructor === Array
NOTE: We first determine if the property exists.
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);
true
true
Even if you haven’t used the constructor, it will still return a valid result.
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);
true
true
Even if you haven’t used the constructor, it will still return a valid result.
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);
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.
What is the catch with using instanceof on arrays?
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);
What is the gotcha with using Array.isArray(variable).
It’s doesn’t work in IE8 - it will work on all ECMAScript 5 environments. It should work in Node.js as well.
If you can access methods on a primitive type, why aren’t they considered reference types?
Because JavaScript uses primitive wrappers behind the scenes, which encapsulates the primitive type when it’s created.
When does the primitive type (string in this case) become autoboxed?
var mystring = "foobar"; console.log(mystring.charAt(0));
When the code tries to access the variable like an object (line 2)
Why doesn’t the following work?
var num = 10;
num. chicken = “foobar”;
console. log(num.chicken);
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’.
If temporary objects are created for primitive types, why does the following return false?
var string = "foobar"; console.log(string instanceof String);
Because the temporary objects are only created when the variable is read.
There is a problem with using objects like a primitive type, what is it?
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.
Should you manually instantiate primitive wrappers?
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.
What are the five primitive types?
Strings Numbers Booleans null and undefined
You can use typeof to test for the type of primitive type with the exception of…
null - which you should always compare with against null.
What distinguishes a function from every other object?
An internal property named “[[call]]”
Can the internal property (of functions) [[call]] be accessed via code?
No
ECMA Script defines that the ‘typeof’ operator must return function for any object that has…
A property named [[call]]
Older browsers may have an issue where RegEx objects are identified as…
functions - because they have a [[call]] property. But that is no longer the case, and SHOULDN’T be a problem.
Which function declaration type is hoisted, function declaration or function expression?
Function declaration
Why does function hoisting occur for function declarations?
Because the function name is known ahead of time.
Will this code work?
var result = add(5, 3);
var add = function(num1, num2) { return num1 + num2; };
No - because function expressions aren’t hoisted and the function isn’t declared before it’s used.
Does JavaScript use first class functions?
Yes
Why are JavaScript functions considered first class functions?
Because you can use them anywhere you use any other reference type (parameters, assign to variables etc).
Why can’t the default behavior of the ‘sort’ method deal with numbers effectively?
It converts numbers into a string and sorts them. This will not give you correct numerical sort.
How do you make the behavior of the ‘sort’ method work for numbers?
Pass it a comparison function
var nums = [1, 2, 5, 4, 3, 6, 7, 9]; nums.sort(function(first, second)) { return first - second; }
You can pass how many arguments to a function, if the function specifies two parameters?
As many as you want - they will be stored in the functions internal “arguments” array.
If you want to know the number of parameters a function expects, how do you find this out?
Read the length property on the function.
console.log(myfunc.length);
What is one of the reasons that a IIFE (Immediately invoked function expression) is actually very useful?
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.
What is AMD?
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).
What is the lexical environment in JavaScript?
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.
What is the execution context?
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.
The name in a name/value pair may only be defined once in any one…
Execution context.
What is the simplest possible definition of an object in JavaScript?
A collection of name value pairs.
When you run a JavaScript program, the javascript engine creates two things for you in the global context - what are they?
The global object, and ‘this’.
Is the global object always called ‘window’?
No - it depends on the environment (i.e. Node.js will be different). However, there is ALWAYS a global object.
When we refer to variables that are global - what is the most basic definition of this?
Anything that is not inside a function - simple as that.
If you have a Chrome console open, what is the easiest way to see the value of a variable?
Just type it’s name at the console prompt.
What does the outer environment mean, and what is it’s relationship to the global context?
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.
The execution context is created in how many phases?
Two
Creation phase
Execution phase
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?
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.
What happens during the creation phase of an execution context?
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)
Why do functions allocated memory for both their name and content, while variables are only allocated memory - but no values are assigned during hoisting?
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.
What is the placeholder that is put into a variable during the hoisting stage?
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).
What is the difference between “not defined” and “undefined”?
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.
What phase of running a javascript file is an Uncaught ReferenceError (i.e. a variable is not defined) reported?
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.
Why is it a bad habit to set variables to undefined?
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.
Is JavaScript single threaded?
Yes - despite what the browser may do to make it run, the javascript engine will for all intents and purposes, be single threaded.
Is JavaScript Synchronous, or asynchronous?
Synchronous - because one line is executed at a time, one after the other.
Invocation, or Invoking a function is what?
Running a function, you do this by using parenthesis.
myFunc();
What happens when a function is called in JavaScript?
A new execution context is created, and put on top of the execution stack.
In the context of the execution stack, which execution context is the one that is running?
The one on top of the stack (i.e. the last inserted)
If you execute a function a(), how many execution contexts are on the execution stack?
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.
If you have the following:
function b() {} function a() { b(); } a();
What does the execution stack look like after b is invoked?
b() - execution context
a() - execution context
Global Execution Context
With b being on top of the stack
When a new function is run, what happens?
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.