Skip to content

Instantly share code, notes, and snippets.

@ethanjiezhou
Last active July 23, 2016 20:11
Show Gist options
  • Save ethanjiezhou/039bd4ed9441ff440509752b3eed89fb to your computer and use it in GitHub Desktop.
Save ethanjiezhou/039bd4ed9441ff440509752b3eed89fb to your computer and use it in GitHub Desktop.
Q&A GUIDE - JavaScript

JavaScript Basic Issues Q1 - Q20


  1. What is "closure" and how to implement it? When to use it? - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures - http://howchoo.com/g/mge2mji2mtq/javascript-closures-by-example - http://stackoverflow.com/questions/111102/how-do-javascript-closures-work - http://javascriptissexy.com/understand-javascript-closures-with-ease/ - http://stackoverflow.com/questions/2728278/what-is-a-practical-use-for-a-closure-in-javascript
Closure is a function having access to parent scope, even after the parent function has closed.

Closure has three scope chains, it has access to its own scope; it has access to outer function's scope; and it has access to the global scope.
  1. What is "hoisting" and how to implement it? - http://www.sitepoint.com/back-to-basics-javascript-hoisting/ - http://code.tutsplus.com/tutorials/javascript-hoisting-explained--net-15092 - http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html
Hoisting is JavaScript default behaviour of moving declarations on top. In JavaScript a variable can be declared after it has been used. In other words, a variable can be used before it has been declared.

It's better to declare all variables on the top of code to avoid hoisting.
  1. What is the difference between "call", "apply" and "bind" method? - http://stackoverflow.com/questions/1986896/what-is-the-difference-between-call-and-apply - http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/ - http://hangar.runway7.net/javascript/difference-call-apply
``apply`` and ``call`` both have two parameters, the first parameter is used for defining scope, the second parameter is used for arguments.	The first parameter can be default. As for ``bind``, to assign a scope to a function.

The difference is that ``apply`` lets you invoke function with arguments as a array; ``call`` requires the parameters to be listed explicitly. 
  1. What is call method, also see apply() and bind()? - call() is used when you want to control the scope that will be used in the function called. You might want the this keyword to be something else than the scope you assigned the function to, in those cases you need to use call() or apply() to bring the right scope into the function - It also allows you to call utility methods outside the scope, but still bring the local scope into the method, for example, when using "private" functions javascript var obj = (function() { var privateFn = function() { alert(this.id); } return { id: 123, publicFn: function() { privateFn.call(this); } }; }()); obj.publicFn(); - In the example above, privateFn is not exposed in obj but it can still be constructed as if it was a part of the public scope (using this in the same way) - The main difference is that apply lets you invoke the function with arguments as an array; call requires the parameters be listed explicitly javascript // Pseudo syntax theFunction.apply(valueForThis, arrayOfArgs); theFunction.call(valueForThis, arg1, arg2, ...) Sample code that utilizes call and apply method javascript function theFunction(name, profession) { alert("My name is " + name + " and I am a " + profession + "."); } theFunction("John", "fireman"); theFunction.apply(undefined, ["Susan", "school teacher"]); theFunction.call(undefined, "Claude", "mathematician");

  2. What is the difference between event bubbling and event capturing? Which is better? - http://stackoverflow.com/questions/4616694/what-is-event-bubbling-and-capturing

**Event bubbling** and **event capturing** are two ways of event propagation in HTML DOM, when an event occurs in an element inside another element, and both event elements have registered a handle for that event. The event propagation mode determines in which order the elements receive the event.

With **bubbling**, the event is first captured by the innermost element and then propagated to outer elements.

With **capturing**, the event is first captured by the outermost element and propagated to the inner elements.
  1. Explain what is 'event delegation' in JS? - DOM event delegation is a mechanism of responding to ui-events via a single common parent rather than each child, through the magic of event "bubbling" (aka event propagation)

  2. How to use the “eval” function? - http://www.w3schools.com/jsref/jsref_eval.asp

The ``eval()`` function evaluates or executes an arguments.

If the argument is an expression, ``eval()`` evaluates the expression. If the argument is one or more JavaScript statements, ``eval()`` executes the statements.
  1. Difference between “window.onload” and $(document).ready? - http://stackoverflow.com/questions/3698200/window-onload-vs-document-ready - http://www.dotnetbull.com/2013/08/document-ready-vs-window-onload.html
The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content has been loaded.
  1. Functions of using “var” compared to not using it - http://stackoverflow.com/questions/1470488/what-is-the-function-of-the-var-keyword-and-when-to-use-it-or-omit-it
If there are in global scope, then there is no difference.

If they are in a function, ``var`` will create a local variable or function. 'no var' will look up the scope chain up until it find the varibale or function, or hit the global scope.
  1. Difference between double and triple equal? - http://stackoverflow.com/questions/523643/difference-between-and-in-javascript

  2. Benefits of using MVVM model compared to MVC - http://stackoverflow.com/questions/1644453/why-mvvm-and-what-are-its-core-benefits - http://www.keylineit.com/what-are-the-benefits-of-mvvm-over-mvc/ - http://stackoverflow.com/questions/5602685/mvvm-unique-benefits - http://www.scottkoland.com/blog/when-should-you-use-the-mvvm-pattern/

  3. How to detect a user is idle on the client side? - http://www.kirupa.com/html5/detecting_if_the_user_is_idle_or_inactive.htm - http://stackoverflow.com/questions/13246378/detecting-user-inactivity-over-a-browser-purely-through-javascript

  4. Promise/ Deferred promise - http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/ - http://blog.mediumequalsmessage.com/promise-deferred-objects-in-javascript-pt1-theory-and-semantics - http://api.jquery.com/deferred.promise/

A promise represents a value that is not yet known. Promises in JavaScript give us the ability to write asynchronous code in a parallel manner to synchronous code.

A deferred represents a work that is not yet finished.

A promise is a placeholder for a result which is initially unknown while a deferred represents the computation that results in the value. Every deferred has a promise which functions as a proxy for the future result. While a promise is a value returned by an asynchronous function, a deferred can be resolved or rejected by it’s caller which separates the promise from the resolver. 
  1. What are 2 (shorthand) boolean operators supported by Javascript? - OR ||, AND &&, NOT EQUAL TO !

  2. What is the result of “20″ + 20?

"20" + 20 = 2020

20 + "20" = 2020

parstInt("20") + 20 = 40
  1. What are the levels of scope in JS?

  2. Is JavaScript multithreaded or single threaded?

    JavaScript is single threaded.

  3. Can JavaScript run in any other environments other than browsers?

    Node.js

  4. Is JS a compiled language?

    JavaScript is an interpreted language, not a compiled language. A program such as C++ or Java needs to be compiled before it is run. The source code is passed through a program called a compiler, which translates it into bytecode that the machine understands and can execute. In contrast, JavaScript has no compilation step. Instead, an interpreter in the browser reads over the JavaScript code, interprets each line, and runs it. More modern browsers use a technology known as Just-In-Time (JIT) compilation, which compiles JavaScript to executable bytecode just as it is about to run.

  5. Why do we say Javascript is a dynamic language?

    All variables are dynamic(both in type and existance), even the code is dynamic.

    You can create new variables at runtime, and the type of variables is determined at runtime.

    You can create new functions at any time, or replace existing functions.

    When used in a browser, code is added when more script files are loaded, and you can load more files any time you like.

  6. Describe what this statement does:

    ("this is foo bar".match(/o/g)||[]).length
  7. What is invoking in Javascript? - The JavaScript code that makes up the body of a function is not executed when the function is defined but when it is invoked. JavaScript functions can be invoked in four ways: - As functions javascript printprops({ x: 1 }); var total = distance(0, 0, 2, 1) + distance(2, 1, 3, 5); var probability = factorial(5) / factorial(13); - As methods: A method is nothing more than a JavaScript function that is stored in a property of an object. If you have a function F and an object O, you can define a method named M of O with the following line javascript O.M = F; Having defined the method M() of the object O, invoke it like this javascript O.M(); Or, if M() expects two arguments, you might invoke it like this javascript O.M(x, y); - As constructors javascript var O = new Object(); var O = new Object; - Indirectly throught their call() and apply() methods

  8. What purpose do Work Workers serve and what are some of their benefits? - Web Workers are background scripts that do not interfere with the user interface or user interactions on a webpage, allowing HTML to render uninterrupted while JavaScript works in the background

  9. What is anonymous function in javascript? - An anonymous function is a function that was declared without any named identifier to refer to it. As such, an anonymous function is usually not accessible after its initial creation ```javascript // Named function function getColour() { return window.location.search.substring(1); }

// Anonymous Function Assigned to Variable
var getColour = function() {
    return window.location.search.substring(1);
};
```
  1. What is design patterns in JS? - https://carldanley.com/javascript-design-patterns/

  2. Explain few ways of writing asynchronous JS?

JavaScript OOP Issues Q - Q


  1. “Object-Oriented” in JS - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript - http://javascriptissexy.com/oop-in-javascript-what-you-need-to-know/

  2. “Inheritance” in JS - http://javascript.crockford.com/inheritance.html - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_Revisited - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain

JavaScript is a class free and object oriented language, so JavaScript uses prototype to implement inheritance.

Classical Inheritance

	function Parent(value){
	     this.setValue = value;
	}
	fn.method('setValue', function(value){
	     this.value = value;
	});
	Child.inherits(Parent);

Multiple Inheritance

	Child = Parent.swiss(className, 'classMethod', 'ClassMethod');

Constructor Inheritance
  1. Explain “Prototype” in JS - Since Javascript doesn't exactly have sub-class objects, prototype is a useful workaround to make a "base class" object of certain functions that act as objects. Prototype is a pointer to another object. We use it to do inherit functionality - http://stackoverflow.com/questions/572897/how-does-javascript-prototype-work - http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/ - http://sporto.github.io/blog/2013/02/22/a-plain-english-guide-to-javascript-prototypes/

  2. What is Objecte Oriented Javascript? - Using objects in this manner(OOP) allows us to adopt some valuable techniques, including Inheritance (objects can inherit features from other objects), Polymorphism (objects can share the same interface—how they are accessed and used—while their underlying implementation of the interface may differ), and Encapsulation (each object is responsible for specific tasks). We are only concerned with Inheritance and Encapsulation, since only these are applicable for OOP in JavaScript. Essentially, in JavaScript, objects can encapsulate functionalities and inherit methods and properties from other objects - The two important principles with OOP in JavaScript are Object Creation patterns (Encapsulation) and Code Reuse patterns (Inheritance)

  3. What is user constructor? - An object has a build-in property named constructor. It is meant to reference the function which made the object, but it fails to do it sometimes

  4. Define few patterns of inheritance in JS?

    Constructor Pattern

    ES2015 (ES6) Class definitions

    Explicit prototype declaration, Object.create, method factory

    Object.create, top-level factory, prototype post-declaration


JavaScript Data type Issues Q - Q


  1. Is array a JS object? - http://www.w3schools.com/js/js_arrays.asp
Yes, array is a object, and also array is a special object, which can hold more than one values. Array has its own method such as length(), sort(), push(), pop(), shift() and unshift().

Array uses numbered index, but object uses named index.
  1. Difference between “undefined” and “null”? - http://stackoverflow.com/questions/5076944/what-is-the-difference-between-null-and-undefined-in-javascript
In JavaScript, **undefined** means a variable has been declared but has not yet been assigned a value. **Null** is an assignment value. It can be assigned to a variable as a representation of no value.
  1. What is "NaN" and how to use it? - http://www.w3schools.com/jsref/jsref_number_nan.asp
"NaN" represents "Not a number", indicates that the number is not a legal number.

isNaN() function is used to check if a number is a NaN value.
  1. How to check if a variable is an object or not? What if it is “null”? - http://stackoverflow.com/questions/8511281/check-if-a-variable-is-an-object-in-javascript
|           |     typeof    |	
|:---------:|:-------------:|	
|   String  |     string    |	
|   Number  | right-aligned |	
|    Null   |     object    |	
|   Array   |     object    |	
|   Object  |     object    |	
|  Boolean  |    boolean    |	
| undefined |   undefined   |	
  1. What are the built in data types in JS?

    Six data types that are primitives:

    Boolean

    Number

    String

    Null

    Undefined

    Symbol(new in ECMAScript 6)

    and Object


JavaScript Performance Issues Q - Q


  1. Performance optimization techniques in JS - http://jonraasch.com/blog/10-javascript-performance-boosting-tips-from-nicholas-zakas - http://desalasworks.com/article/javascript-performance-techniques/ - https://developers.google.com/speed/articles/optimizing-javascript - http://www.smashingmagazine.com/2012/11/05/writing-fast-memory-efficient-javascript/

JavaScript Debug Issues Q - Q


  1. How to handle errors using “try” and “catch”? - http://www.w3schools.com/js/js_errors.asp
The ``try`` statement lets you test a block of code for errors.

The ``catch`` statement lets you handle the error.

The ``throw`` statement lets you create custom errors.

The ``finally`` statement lets you execute code, after try and catch, regardless of the resule.
  1. Global error handling in JS - http://stackoverflow.com/questions/951791/javascript-global-error-handling - http://danlimerick.wordpress.com/2014/01/18/how-to-catch-javascript-errors-with-window-onerror-even-on-chrome-and-firefox/

JavaScript Cross Domain Issues Q - Q


  1. Cross domain issues - http://stackoverflow.com/questions/3506208/jquery-ajax-cross-domain - http://jquery-howto.blogspot.com/2013/09/jquery-cross-domain-ajax-request.html
One method is using **JSONP**.

Another method is set the ``Access-Control-Allow-Origin``header on your server. Setting it to * will accept cross-domain AJAX requests from any domain.
  1. What is “JSONP”? - http://stackoverflow.com/questions/3839966/can-anyone-explain-what-jsonp-is-in-layman-terms - http://stackoverflow.com/questions/2067472/what-is-jsonp-all-about
JSONP is "JSON with padding", JSONP is used to handle cross domain request issues. Use script tag and callback function to implement crose domain request.
  1. What is Ajax? - AJAX = Asynchronous JavaScript and XML - AJAX is not a new programming language, but a new way to use existing standards - AJAX is the art of exchanging data with a server, and updating parts of a web page - without reloading the whole page javascript $.ajax({ url: “...”, type: GET, //GET, POST. The default value is attribute in <form> dataType: json, //or “xml” or “script”. “xml” return responseXML. The default value is null, return responseText data: { txtName: …, txtPass: …… }, //send data to server success: function(result) {... }, error: function(xhr) {... } });

  2. What is an AJAX request and what is a simple example of where a AJAX request would be used?

  • Asynchronous JavaScript and XML. Client side process used for GET, POST etc to get new data without having to refresh the page
  1. What is local storage? how do you use local storage? How about session storage and cookie? - The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year. Local storage example: your client is inputing a webform including his name year of birth , social, local storage can store those info locally so if he accidently close the page, he won’t have to retype all those stuff again javascript // Store localStorage.setItem("lastname", "Smith"); // Retrieve document.getElementById("result").innerHTML = localStorage.getItem("lastname"); // Delete localStorage.removeItem(“lastname”); - The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the browser window. Cookies are data, stored in small text files, on your computer Create a Cookie with JavaScript - You can also add an expiry date (in UTC time). By default, the cookie is deleted when the browser is closed javascript document.cookie="username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC"; Delete a Cookie with JavaScript - Deleting a cookie is very simple. Just set the expires parameter to a passed date. Note that you don't have to specify a cookie value when you delete a cookie javascript document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC";

JavaScript Storage Issues Q - Q


  1. Compare between local storage vs session storage, session vs cookies, cookies vs caches - http://stackoverflow.com/questions/19867599/what-is-the-difference-between-localstorage-sessionstorage-session-and-cookie - http://www.differencebetween.com/difference-between-cache-and-vs-cookies/

  2. Session management in JS - http://stackoverflow.com/questions/21821937/how-to-manage-server-user-session-within-client-side-single-page-app - http://stackoverflow.com/questions/16329055/javascript-rest-client-and-session-management


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment