1. Define such a, that expression would resolve to true

(a == 0) && (a == 1) && (a == 2)
Method 1:
var a = {
  i: 0,
  valueOf: function() {
    return this.i++;
  }
};
Method 2:
(function(global) {
  var value = 0;
  Object.defineProperty(global, 'a', {
    get: function() {
      return value++;
    }
  });
})(window)
What's different between two define?
  • a in Method 1 is Object's type instead of Integer's type of Method 2. It leads above expression is only equal in term of value.
  • a in Method 2 can not be changed or listed differ to in Method 1.
  • There's no way to modify value of a in Method 2.
Object in Javascript can be converted to primitives in three context:
  • Numberic toString: happens when a string representation of an object is required.
  • String valueOf: performs two cases
    • In function which need a number, for example Math.sin(obj), isNaN(obj) or +obj.
    • In comparison like == but not for ===
  • Boolean.
Both String conversion and Number conversion try to convert into it's type firstly, but if not success(not define) they will try the other one.

2. What's the different between EMACScript and Javascript?

  • EMACScript is an object-oriented programming language for performing computations and manipulating objects within a host environment.
  • Javascript is one of well-known EMACScript's dialect.

3. Why does nearly every object have a toString method?

When object was to be represented as a text value, it need to be converted into String type and toString will be called automatically.
The default toString function will return [object type].
Common way to use is to detect object class
var toString = Object.prototype.toString;

toString.call(new String) // [object String]
toString.call(undefined) // [object Undefined]

4. Do you know which interpreter Mozilla Firefox uses? Or any other of the browsers?

  • Mozilla Firefox: SpiderMonkey
  • Chrome: V8
  • Safari: Nitro
  • Internet Explorer: Chakra
You need to understand the different between javascript engine and layout engine

5. Is there block scope in JavaScript?

There's no block scope in javascript. Only declarations(variable and function) which you define in block will be hoisted (equivalent to movie to the top of the function or global code) because they are processed before any code is executed.
For that reason, it is recommended to always declare variables at the top of their scope (the top of global code or function code) and declares functions at the bottom of their one.

6. Can you explain how Ajax/XMLHttpRequest works?

Ajax stands for Asynchronous Javascript and XML, it's approach to using a number of existing technologies together, including: HTML or XHTML, CSS, Javascript, DOM, XML, XSLT and most importantly the XMLHttpRequest object to communicate with server-side scripts.
This picture below will describe how it works

The different between ajax and classic web

7. What is JSON?

JSON is a syntax for serializing objects, arrays, numbers, strings, booleans and null.
JSON object contains methods for parsing Javascript Object Notation and converting values to JSON. It can't be called or constructed and aside from its method properties(JSON.parse() and JSON.stringify()) it has no interesting functionality of its own.
✍ JSON is not subset of javascript. In general, JSON spec says that "a string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes." But in javascript "a string can contain anything as long as it's not a quote, a backslash or line terminator(\u000A, \u000D, \u2028, \u2029)", therefore two invisible Unicode characters(U+2028, U+2029) are the resason.
For example: {"JSON":"ro
cks!"}

8. An example of a singleton pattern?

(function(global) {
  var instance;

  function Singleton() {
    if (!instance) {
      instance = this;
    } else {
      return instance;
    }
  };

  global.Singleton = Singleton;
})(this);

new Singleton() === new Singleton()

9. What's the difference between undefined and undeclared?

undefined is the one of built-in types. it has a mean that the variable was declared but not initialized. There are three ways to achive 'undefined':
  • declare variable
  • access not existing property of object
undeclared means that the variable wasn't declared in chaining scope.
declared vs undeclared variables also have mean like that
var declared = 1 // explicit
undeclared = 1

10. Are you familiar with Web Workers?

11 The standard addEventListener is supported in which browsers?

addEventListener is a method registers the specified listener on EvenTarget. The even target may be an Element in document, Document itself, a Window or any other object that supports events(such as XMLHttpRequest).
It is supported in most of browsers except IE 9.
When talking about addEventListener, people often compare it with inline events. Inline events are better in case of browser compatibility but it has many drawbacks.
  • You may only have one inline event assigned.
  • The context this in case of inline event is global compare to HTML element in case of addEventListener.
Microsoft has developed an event registration model, it looks similar to addEventListener but has some important callbacks.
  • Events always bubble, no capturing possibility.
  • this always refers to the windows.
More details

12. What is the difference between == and ===? Which one would you use?

Main difference is that == compares only value while === compares value and type.
The operand == leads to type conversion, when type conversion is involved in comparsion(ie. non-strict mode) Javascript converts String, Number, Boolean or Object operands as follows:
  • Number vs String: try to convert string numeric literal to Number
  • one of the operands is Boolean, the Boolean operand is converted to 1 or 0
  • Object vs Number / String: Object operand is converted to primitive value(if, and only if its comparand is a primitive), a String or a Number, using the valueOf and toString methods
More details

13. what is the difference between var x = 1 and x = 1? Answer in as much or as little detail as you feel comfortable

var x = 1 is explicit declaration while x = 1 is implicit declaration. It leads to
  • Scope inheritance in case 2:
    • if scope chain from execution context doen't declare(both explicit and implicit) variable x, x will declare and initialize on global with configurable = true.
    • Otherwise x will reuse that declaration(in parent scope) and set value with 1.
  • In case 1:
    • var x will be declare in execution context with option configurable = false and also be hoisted.
✍ Everytime a function is called, a new execution context is created. Js interpreter calls with 2 stages:
  • Creation Stage: create the scope chain, create variable object and determine the value of this. Create variable object will lead:
    • Create arguments object, check the context for parameters, initialize the name and value and create a reference copy.
    • Scan the context for function declarations:
      • For each function found, create a property in variable object which has a reference pointer to the function in memory.
      • If function name exists, the reference pointer value will be overwritten.
    • Scan the context for variable declarations:
      • For each one found, create a property in variable object and initialize the value as undefined.
      • If variable name already exists in the variable object, do nothing and continue scanning.
  • Activation / Code Execution Stage: Assign values, references to functions and execute code.
You can think like that
executionContextObj = {
    scopeChain: { /* variableObject + all parent execution context's variableObject */ },
    variableObject: { /* function arguments / parameters, inner variable and function declarations */ },
    this: {}
}

14. Difference between Classical Inheritance and Prototypal Inheritance

In a nutshell, prototypal inheritance is when an object inherits(*) from another object. This is differ from classical inheritance, in which a class inherits from another class.
Classical Inheritance Prototypal Inheritance
Classes typically define the structure of objects The objects themeselves define their own structure and this one can be inherited and modified by other object at the runtime
It is static, means that after defining you can't modify its behavior at runtime It is dynamic, you can add new properties to prototypes after they are created, this allows you to add new methods to a prototype which will be automatically made available to all the objects which delegate to that prototype
It's quite complicate, containing many aspect like abstraction, encapsulation, inheritance and polymorphism therefore it provides some stuffs for you to easily achive OOP, also looks more naturally It's simple, most of OOP aspect you need to implement to achive that
Tight coupling, the gorilla / banna problem
(*): Using the word "inherit" in there means that it's not really inherit, it's something like delegate through the internal property [[Prototype]]. Shortly, object A "inherits" from object B, when you ask for a property or a method on an object, if it's not there, the internal [[Get]] lookup operation will traverse the [[Prototype]] chain not like in classical language, a copy-operation where behavior from the "parent" is duplicated into the "child".

15. What is difference between private variable, public variable and static variable? How we achieve this in JS?

Private variable is only visible in current scope.
Public variable is visible in both current scope and other scopes through accessing.
Static variable belong to class intead of an instance.
function Variable() {
  var private = 1;
  this.public = 2;

}
Variable.static = 3;

16. How to achieve inheritance? Compare ways of inheritance. What are the downsides?

There are three common ways to achieve inheritance.
  • Pseudo-classical pattern, assigning prototype to prototype.
  • Function pattern, declaring attribute in side object and inherit through call it again.
  • Prototypal pattern, using Object.create.
More details
In pseudo-classical pattern, parent and child share same prototype. It leads drawback that when we modify child it will also change in parent.
In function pattern, they don't use prototype concept and is very strict to follow and everytime we create new object javascript engine need to recompile everything.
In prototypal pattern, it cames as standard of EMACScript 5 therefore it leads to browser compability.

17. Why extending array is bad idea?

Javascript prototypal makes it easy to extend all array objects with custom methods. But normally, we extend via Array.prototype because it's much easier and more efficient
Array.prototype.last = function() {
  return this[this.length - 1];
};
[1, 2, 3].last(); // 3
However, extending Array.prototype comes with the price; that price is change of collisions. When scripts coexists with other scripts in an application, it's important for those scripts not to conflict with each other. Extending Array.prototype while tempting and seemingly useful, unfortunately isn't very safe in a diverse environment. Different scripts can end up define same-named methods but with different behavior. Such behavior often lead to inconsitent behavior and hard-to-track errors.
Collisions can happen not only with user-defined code but also with proprietary methods implements by environment itseft(e.g Array.prototype.indexOf) or from future standards

18. Explain how to prototypal inheritance works?

According to section 8.6.2 in ECMA-262, all objects have an internal property called [[Prototype]]. The value of this property is either null or an object and is used for implementing inheritance

19. Explain function hoisting?

Function hoisting happens when it is a function declaration and was declared in other's scope. In the first step, js engine create variable object via scanning var and function declaration
function hositing() {
  // code here
  var x = 1;
  // code here
  function action() {};
}

20. Explain event delegation (what's the difference between on and bind is in jQuery)?

If there are many element inside one parent and you want to handle events on all of them - don't bind handler to each element. Instead, bind the single handler to their parent and get the child from event.target There're two main benefits:
  • Memory footprint which used by event listeners goes down.
  • Also work for new element which is created dynamically.
But it has its own limits
  • Most of event do bubble but not all of them.
  • Delegation puts extra load on the browser because the handler runs when an event happens anywhere inside the container
jQuery bind is used for attaching an event handler directly to elements.

21. What are promises?

  • Promises: describe an object that acts as a proxy for a result that is normally not finished.
  • Callback: is simply a function you pass into another function so that function can call it at a later time.
There are many Promises Proposals but the the most popular one is CommonJS Promises A. The meat of it is entirely about specifying the behavior of a single function, then:
A promise is defined as an object that has a function as the value for the property then:

then(fulfilledHandler, errorHandler, progressHandler)

Adds a fulfilledHandler, errorHandler, and progressHandler to be called for completion of a promise. The fulfilledHandler is called when the promise is fulfilled. The errorHandler is called when a promise fails. The progressHandler is called for progress events. All arguments are optional and non-function values are ignored. The progressHandler is not only an optional argument, but progress events are purely optional. Promise implementors are not required to ever call a progressHandler (the progressHandler may be ignored), this parameter exists so that implementors may call it if they have progress events to report.
This function should return a new promise that is fulfilled when the given fulfilledHandler or errorHandler callback is finished. This allows promise operations to be chained together. The value returned from the callback handler is the fulfillment value for the returned promise. If the callback throws an error, the returned promise will be moved to failed state.

22. what are some things you can do to improve page loading speed?

There're some ways to improve page loading:
  • Should dynamic load javascript and css to prevent blocking render in DOM.
  • Minimize the number of http requests to server as little as possible
    • Combine multiple style sheets into one.
    • Use css instead of images whenever possible.
    • Reduce scripts and put them at the bottom of the page.
    • Use image sprite.
  • Reduce server response time(less then 200ms).
  • Enable compression.
  • Enable browser caching.
  • Minify resources(html, css, javascript).
  • Reduce the number of plugins you use on your site.
  • Reduce redirects.
  • Use a Content Delivery Network.
Tool to check performance:

23. What is the significance of including 'use strict' at the beginning of a JavaScript source file?

There're some reasons why people use strict mode:
  • security.
  • to avoid what they consider to error-prone features.
  • to get enhanced in error checking(means it will throw exceptions in situations that are not specified as errors in non-strict mode).
  • other reasons of their choosing.

24. What's the different between function declaration and function expression

The main difference is about hosting(in declaration not in expression).
FunctionDeclaration :
function Identifier ( FormalParameterListopt ) { FunctionBody }
FunctionExpression :
function Identifieropt ( FormalParameterListopt ) { FunctionBody }
Named function expression demystified
There're four ways to define function
  1. a function defined with the Function constructor assigned to the variable multiply
  var multiply = new Function("x", "y", "return x * y;");
  1. a function declaration of a function named multiply
  function multiply(x, y) {
      return x + y;
  }
  1. a function expression of an anonymous function assigned to the variable multiply
  var multiply = function(x, y) {
      return x + y;
  }
  1. a function expression of a function named func_name assigned to the variable multiply
  var multiply = function func_name(x, y) {
      return x + y
  }
  • A function defined by a Function constructor does not inherit any scope other than the global scope
  • Functions defined by function expressions and declarations are parsed only once while those defined by the Function constructor are not.
✍ function expressions and declarations nested within the function generated by parsing a Function constructor string aren't parsed repeatly
Mozilla function and function scope

25. How would you change the context of the function?

There're three ways to change context: bind, call and apply
  • bind: create function with new context by passing parameters.
  • call and apply: call function with new context. They are different each other through the way they pass parameters to function
Ex: new XXX() There're 4 steps happened when new was called:
  • It creates new object.
  • It sets the constructor to object XXX.
  • It sets up object to delegate to XXX.prototype.
  • It call XXX() in the context of new object.

26. About typeof and instanceOf operators, constructor property?

Object are aggregations of properties. A properties can reference an object or a primitive. Primitives are values, they have no properties. Because Javascript will readily coerce between primitivies and objects.
✍ All examples below are only in non-strict mode. strict mode is quite difference.
String.prototype.returnMe= function() {
  return this;
}

var a = "abc";
var b = a.returnMe();

a; //"abc"
typeof a; //"string" (still a primitive)
b; //"abc"
typeof b; //"object"
a === b; // false
In this case string value is coerced to string object in order to access the property returnMe. The string object is only used for a fraction of second after which it is sacrificed to the Gods of garbage collection. But in this case, we prevent GC through assign to variable.
This is what realy happen
var primitive = "september";
primitive.vowels = 3;
//new object created to set property
(new String("september")).vowels = 3;

primitive.vowels;
//another new object created to retrieve property
(new String("september")).vowels; //undefined
More details: Secret of Javascript Primitives
  • typeof: return built-in type, it has some issues in cases of null return object, any object type other function return object. Normally, people will define their own function instead of typeof using Object.prototype.toString.call() to get internal [[Class]].
  var toType = function(obj) {
      return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
  }
  • instanceOf: check whether anything from left-hand object's prototype chain is the same object as what's reference by prototype property of right-hand object. The problem arise when it comes to scripting in multi-frame DOM environments instanceOf harmful

27. List every way the browser (using HTML, JS or CSS) can communicate with the server?

There're four common ways to communiate with the server:
  • Ajax
  • Tag: Iframe, Embed, Object, Video, Audio, Image.
  • Script tag injection
  • Websocket

28. Using object as key?

A key in object can be only string, therefore if object is used as key, object will be converted to string type via toString method

✍ There're the definition I copy from Internet.

29. What's closure?

Closure is side-effect of lexical scoping. There are two types of scoping: lexical, dynamic. Lexical scoping seem to be more popuplar than dynamic scope.
  • Lexical scoping: is statically defined by the function's physical placement within the written source code.
  function outter() {
      var x = 1;
      function inner() {
        console.log(1)
      }
  }
  • Dynamic scoping:
  void dynamic() {
      console.log(x)
  }

  void main() {
      var x = 1;
      dynamic();
  }
It happens through [[scope]] property, more details in question 13.