Confusing?  CommonJS, AMD, RequireJS, UMD, Modules in ES Harmony

A much more comprehensive documentation is written by Addy Osmani:

Writing Modular JavaScript With AMD, CommonJS & ES Harmony

All of these terms are related to manage growing complicated JavaScript source code in both client and server sides for better software engineering purpose.

A. How JavaScript is loaded into browser?

Normally:

  1. By the <script src="”source.js”" async="" defer="defer">
    tag. You can defer it, or make it asynchronous use the new attributes, although buggy.
  2. Use document.write:
    var tag = <script src="”source.js”" ></script >
    document.write(tag);
  3. Use appendchild(script):
    var script = document.createElement(‘script’);
    script.src = “http://googleapis.com”;
    document.documentElement.firstChild.appendChild(script);
  4. XHR and eval:
    $.ajax({url: url}).done(function(js){eval(js);})
  5. In Chrome, use <link rel=”prefetch” > to load resources
  6. Script loaders: CommonJS, AMD, RequireJS, curl.js, UMD, etc..

B. So, How, When And Why Script Loaders Are Appropriate

http://www.html5rocks.com/en/tutorials/speed/script-loading/

Most times, just use the traditional method to minify and concatenate all JavaScript files into a single file and put it just before </body> tag.

C. CommonJS

CommonJS defines a module format such that it works on both client and server side. The drawback for CommonJS in web browser is that it won’t simply allow asynchronous loading.

D. AMD

The Asynchronous Module Definition (AMD) API specifies a mechanism for defining modules such that the module and its dependencies can be asynchronously loaded.

The signature function: define(id?, [dependencies?], factory)

E. RequireJS

It implements AMD and caters for simplified CommonJS wrapping.

F. UMD

The UMD pattern typically attempts to offer compatibility with the most popular script loaders of the day (e.g RequireJS amongst others). In many cases it uses AMD as a base, with special-casing added to handle CommonJS compatibility.

G. Modules in ES5

An ES6 module is a file containing JS code. There’s no special module keyword; a module mostly reads just like a script. There are two differences.

  • ES6 modules are automatically strict-mode code, even if you don’t write “use strict”;in them.
  • You can useimport and export in modules.

You differentiate the normal script and module by giving type attribute in the script tag,

i.e.: set script tag with type=”module”

https://hacks.mozilla.org/2015/08/es6-in-depth-modules/

https://www.nczonline.net/blog/2016/04/es6-module-loading-more-complicated-than-you-think/

JS Questions

1. Explain event delegation, what’s event bubbling/event propagation?

jQuery on DOM event delegation

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

The basic idea behind this notation is DOM event bubbling. Say you have a structure like this:

<html>
<body>
<div id="container">
<ul id="list">
<li><span><a href="http://www.google.com">This is a link</a></span></li>
<li><span><a href="http://www2.google.com">This is a link</a></span></li>
<li><span><a href="http://www3.google.com">This is a link</a></span></li>

</ul>

</div>
</body>
</html>

when you click the text area ‘This is a link’, this ‘click’ event will bubble up to the DOM tree:

a -> span -> li -> ul -> div  -> body -> html -> document root.

So if you register a click event handler to the ul element, it will capture the ‘click’ event happened in a link.

// Attach a delegated event handler
$( "#list" ).on( "click"function( event ) {
var elem = $( this );
if ( elem.is( "[href^='http://www1']" ) ) {//match the element
elem.attr( "target", "_blank" );
}
});

Here you click ‘a’ event, the default action is to trigger some link to follow, to prevent this, use  event.preventDefault(). If you want to stop the bubbling process call event.stopPropagation().

2. Explain how prototypal inheritance works

Inheritance and the prototype chain

JavaScript only has one construct: objects. Each object has an internal link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. null, by definition, has no prototype, and acts as the final link in this prototype chain. Kinda of inheritance.

3. Explain why the following doesn’t work as an IIFE: function foo(){ }();. What needs to be changed to properly make it an IIFE? => (function foo(){})();

4. What’s the difference between a variable that is: null, undefined or undeclared?

Null is null value, undefined is for declared variable which has undefined value, undeclared means the variable is not declared before using it.

5. What is a closure, and how/why would you use one?

6. What’s a typical use case for anonymous functions? for loop. array.map

7. What’s the difference between host objects and native objects?

8. Difference between: function Person(){}, var person = Person(), and var person = new Person()?

The previous is to assign the function call result to person. Using new is to create an instance of the Person object.
9. What’s the difference between .call and .apply?

For .call you pass the parameters comma separated (like normal). For .apply you pass the parameters in an array.

10. Explain Function.prototype.bind.

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

11. When would you use document.write()?

Seldom use.

12. What’s the difference between feature detection, feature inference, and using the UA string?

Browser object navigator.userAgent to detect the browser specific objects is feature detection. Feature inference is to use it as a method to guess some features in the browser.

13. Explain Ajax in as much detail as possible.

XMLHTTPREUEST.

14. What are the advantages and disadvantages of using Ajax?

Not updating the whole page.

15. Explain how JSONP works (and how it’s not really Ajax).

Return JSON data as callback in a Script manner to bypass same-origin policy.

16. Have you ever used JavaScript templating?
If so, what libraries have you used?
Handlerbar.

17. Explain “hoisting”.

E.g. call(); function call() { console.log(‘I am declared after the call, but it is ok.’)}

18. What’s the difference between an “attribute” and a “property”?
HTML tag attributes. and JS object property.

19. Why is extending built-in JavaScript objects not a good idea?

May lead bugs if someone else is to use the default function.

20. Difference between document load event and document DOMContentLoaded event?

Load event is fired after all page resources are loaded, DOMContentLoaded event is fired as soon as DOM tree is finished loading.

21. What is the difference between == and ===?

== for equality of values, and === for equality of values and types.

22. Explain the same-origin policy with regards to JavaScript.
JS can only work variables within the same global window environment from the same origin domain.

23. Make this work:
duplicate([1,2,3,4,5]); // [1,2,3,4,5,1,2,3,4,5]

duplicate(arr){ return arr.concat(arr);}

24. Why is it called a Ternary expression, what does the word “Ternary” indicate?

a ? b : c. Ternary means three parameters are present in this operand expression.

25. What is “use strict”;? what are the advantages and disadvantages to using it?

More stricter syntax check to expose bugs earlier.

26. Create a for loop that iterates up to 100 while outputting “fizz” at multiples of 3, “buzz” at multiples of 5 and “fizzbuzz” at multiples of 3 and 5

for i: 100: if (i%3 == 0) fizz;  if (i%5 == 0) buzz; if (i%15 == 0) fizzbuzz ;

27. Why is it, in general, a good idea to leave the global scope of a website as-is and never touch it?

Preserve the global value as it is, and you never know how others will use it. Save for reducing bugs.

28. Why would you use something like the load event? Does this event have disadvantages? Do you know any alternatives, and why would you use those?

Page load event can be used to detect all resources are loaded. Maybe use it to process DOM nodes or to trick CSS.

29. Explain what a single page app is and how to make one SEO-friendly.

SPA. Use semantics HTML.

30. What is the extent of your experience with Promises and/or their polyfills?
What are the pros and cons of using Promises instead of callbacks?

There are some cross-browsers support issues. Promise can handle asynchronous code more easily or construct good code blocks. more readable.

31. What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript?

No trial before. Possible Compilation and debug may be hard with a nice or strict syntax.

32. What tools and techniques do you use debugging JavaScript code?

Chrome Dev Tools.

33. What language constructions do you use for iterating over object properties and array items?

for in loop for object properties and for of loop for array items. Or array.forEach for array items.

34. What do you think of AMD vs CommonJS?

35. Explain the difference between mutable and immutable objects.
What is an example of an immutable object in JavaScript?
What are the pros and cons of immutability?
How can you achieve immutability in your own code?

Mutable object can be changed after its creation, which immutable object doesn’t allow the change of itself. In JS, like strings and numbers are immutable. Say a = {x:2, y:203}, you can mutate it like this a.x = 20; If writing a large web app, there is loss of control on data objects in JS, and hence may cause many data inconsistencies or bugs when displaying data in JS.

Build immutable objects need not to change the original objects. Each change will create a new object and preserve the previous object.

Use Object.assign({target}, source) to perform mutation of objects.

35. Explain the difference between synchronous and asynchronous functions.

Synchronous function needs to wait for its execution completion and return the results back. It stops the other code running in a single-thread environment. While asynchronous function fires the execution and continues to run the other code. It returns the result to interrupt the current code execution once completed.

36. What is the difference between call stack and task queue?

Call stack is a data structure to store method calls within a programme, while task queue is to use to store the sequential tasks to run. Each task could be a small programme.

Ajax

Ajax is ubiquitous. Look around at fackbook, twitter, gmail, outlook web, google maps, google instant search, whichone isn’t utilising Ajax?

What’s Ajax?

AJAX stands for Asynchronous JavaScript and XML. It’s a workaround for web app to communicate with server-side scripts. It can send as well as receive information such as JSON, XML, HTML, and even text files (CSS) and JavaScripts, i.e. JSONP. The most appealing characteristic of AJAX is its “asynchronous” nature, allowing update web page partially upon user events.

The basic idea of Ajax is to use XMLHttpRequest to transfer data asynchronously. Of course, you can also do this in a synchronous way.

The use of Ajax in Web development architecture vs. the traditional method:

When did Ajax come out?

In 2005, Jesse James Garrett coined this term in the article Ajax: A New Approach to Web Applications. The technique came out for many years as a way to avoid reloading the whole web page for better user experience.

How Ajax works?

Ajax uses XMLHttpRequest API. A simple Ajax code is in MDN: Ajax Getting Started. Basically, you create a HTTP request using GET or POST method in JavaScript, not through browser tab URL change of the client side, and with a server side code to match such request to response.

Issues

Since Ajax is requesting resources in browser, there is a Same Origin policy. Most browsers can’t  allow one domain to request data from other domains except specifically allowed (CORS), but JavaScript is a exception. So developers come up with JSONP to overcome this problem. JSONP returns data in a script manner to be executed immediately in browser through a callback function upon loaded. However, this will introduce security issues like Cross site request forgery as the attacker could use the fake web page to request data from the actual web page.

Browsers are implemented differently, and hence the support of XMLHttpRequest is not fully done. There are many libraries to help in writing Ajax such as jQuery, backbone, YUI,  or other big web frameworks like Angular, Dojo. Essentially, they try to detect the client browser and adopt the different underlining implementation of the XMLHttpRequest API.

 

Good JavaScript Charting APIs

1. D3
This is the root of web data visualization. There are many examples to follow but coding is tedious. It’s easy to start but very difficult to master.d3
2. C3
A light-weighted library based on D3.
C3 makes it easy to generate D3-based charts by wrapping the code required to construct the entire chart.
c3
3. ECharts
Charting API from Baidu Inc. It has many geo-charts target to China.
The most comprehensive charting API so far.
ec
4. Hightchart It’s a carefully designed charting tool.Free for non-commercial. Pretty easy to take on.
high
5. Google Charts From Google. A lots of examples and still growing for improvements. However, you can’t use it in intranet environment.
google
6. AMCharts Like highcharts, this is designed by a group of commercial people.
am
7. EJS charts  You need to buy the license to use.
ejs

Mixins in JavaScript

In object-oriented programming, a mixin is a class that contains a combination of methods from other classes.

JavaScript’s object mechanism does not automatically perform copy behavior when you inherit or instantiate. Plainly, there are no “classes” in JavaScript to instantiate, only objects. And objects don’t get copied to other objects, they get linked together. However, we can fake the missing copy behavior of classes in JavaScript using mixins, either explicitly or implicitly. Let’s see a mixin example:

// vastly simplified `mixin(..)` example:
function mixin( sourceObj, targetObj ) {
for (var key in sourceObj) {
// only copy if not already present
if (!(key in targetObj)) {
targetObj[key] = sourceObj[key];
}
}
return targetObj;
}
var Vehicle = {
engines: 1,
ignition: function() {
console.log( "Turning on my engine." );
},
drive: function() {
this.ignition();
console.log( "Steering and moving forward!" );
}
};
var Car = mixin( Vehicle, {
wheels: 4,
drive: function() {
Vehicle.drive.call( this );
console.log(
"Rolling on all " + this.wheels + " wheels!"
);
}
} );

Vehicle and Car are just objects that we make copies from and to, respectively. Car now has a copy of the properties and functions from Vehicle. Technically, functions are not actually duplicated, but rather references to the functions are copied. So, Car now has a property called ignition, which is a copied reference to the ignition() function, as well as a property called engines with the copied value of 1 from Vehicle. Car already had a drive property (function), so that property reference was not overridden.

Let’s examine this statement: Vehicle.drive.call( this ). Because both Car and Vehicle had a function of the same name, drive(), to distinguish a call to one or the other, we must make an absolute (not relative) reference. We explicitly specify the Vehicle object by name and call the drive() function on itBut if we said Vehicle.drive(), the this binding for that function call would be the Vehicle object instead of the Car object, which is not what we want. So, instead we use .call( this ) to ensure that drive() is executed in the context of the Car object. If the function name identifier for Car.drive() hadn’t overlapped with Vehicle.drive(), we wouldn’t have been exercising method polymorphism. So, a reference to Vehicle.drive() would have been copied over by the mixin(..) call, and we could have accessed directly with this.drive().

If you explicitly mix in two or more objects into your target object, you can partially emulate the behavior of multiple inheritance, but there’s no direct way to handle collisions if the same method or property is being copied from more than one source.

Consider this code for an implicit mixin:

 var Something = {
 cool: function() {
 this.greeting = "Hello World";
 this.count = this.count ? this.count + 1 : 1;
 }
 };
 Something.cool();
 Something.greeting; // "Hello World"
 Something.count; // 1
 var Another = {
 cool: function() {
 // implicit mixin of `Something` to `Another`
 Something.cool.call( this );
 }
 };
 Another.cool();
 Another.greeting; // "Hello World"
 Another.count; // 1 (not shared state with `Something`)

With Something.cool.call( this ), which can happen either in a constructor call (most common) or in a method call (shown here), we essentially “borrow” the function Something.cool() and call it in the context of Another (via its this binding) instead of Something. The end result is that the assignments that Something.cool() makes are applied against the Another object rather than the Something object. So, it is said that we “mixed in” Something’s behavior with (or into) Another.

While this sort of technique seems to take useful advantage of this rebinding functionality, it’s a brittle Something.cool.call( this ) call, which cannot be made into a relative (and thus more flexible) reference, that you should heed with caution. Generally, avoid such constructs wherever possible to keep cleaner and more maintainable code.

Ref: Book: this & Object Prototypes

this keyword in JavaScript

A function’s this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode.
In most cases, the value of this is determined by how a function is called. It can’t be set by assignment during execution, and it may be different each time the function is called.

Global context

In the global execution context (outside of any function), this refers to the global object, whether in strict mode or not.

console.log(this.document === document); // true
// In web browsers, the window object is also the global object:
console.log(this === window); // true
this.a = 37;
console.log(window.a); // 37
function test(){
  alert(this.a);
}
test();//37
Function context

Inside a function, the value of this depends on how the function is called.

Simple call

function f1(){
  return this;
}
f1() === window; // global object
In this case, the value of this is not set by the call. Since the code is not in strict mode, the value of this must always be an object so it defaults to the global object.
function f2(){
  "use strict"; // see strict mode
  return this;
}
f2() === undefined; //true
In strict mode, the value of this remains at whatever it’s set to when entering the execution context. If it’s not defined, it remains undefined. It can also be set to any value, such as null or 42 or "I am not this".
Note: In the second example, this should be undefined, because f2 was called without providing any base (e.g. window.f2()). This feature wasn’t implemented in some browsers when they first started to support strict mode. As a result, they incorrectly returned the window object.
As an object method

When a function is called as a method of an object, its this is set to the object the method is called on.

In the following example, when o.f() is invoked, inside the function this is bound to the o object.

var o = {
  prop: 37,
  f: function() {
    return this.prop;
  }
};
console.log(o.f()); // logs 37
Note that this behavior is not at all affected by how or where the function was defined. In the previous example, we defined the function inline as the f member during the definition of o. However, we could have just as easily defined the function first and later attached it to o.f. Doing so results in the same behavior:
var o = {prop: 37};
function independent() {
  return this.prop;
}
o.f = independent;
console.log(o.f()); // logs 37
This demonstrates that it matters only that the function was invoked from the f member of o.

Similarly, the this binding is only affected by the most immediate member reference. In the following example, when we invoke the function, we call it as a method g of the object o.b. This time during execution, this inside the function will refer to o.b. The fact that the object is itself a member of o has no consequence; the most immediate reference is all that matters.

o.b = {g: independent, prop: 42};
console.log(o.b.g()); // logs 42
this on the object’s prototype chain

The same notion holds true for methods defined somewhere on the object’s prototype chain. If the method is on an object’s prototype chain, this refers to the object the method was called on, as if the method was on the object.

var o = {f:function(){ return this.a + this.b; }};
var p = Object.create(o);
p.a = 1;
p.b = 4;
console.log(p.f()); // 5
In this example, the object assigned to the variable p doesn’t have its own f property, it inherits it from its prototype. But it doesn’t matter that the lookup for f eventually finds a member with that name on o; the lookup began as a reference to p.f, so this inside the function takes the value of the object referred to as p. That is, since f is called as a method of p, its this refers to p. This is an interesting feature of JavaScript’s prototype inheritance.

this with a getter or setter

Again, the same notion holds true when a function is invoked from a getter or a setter. A function used as getter or setter has its this bound to the object from which the property is being set or gotten.

function modulus(){
  return Math.sqrt(this.re * this.re + this.im * this.im);
}
var o = {
  re: 1,
  im: -1,
  get phase(){
    return Math.atan2(this.im, this.re);
  }
};

Object.defineProperty(o, 'modulus', {
    get: modulus, enumerable:true, configurable:true});

console.log(o.phase, o.modulus); // logs -0.78 1.4142
 As a constructor

When a function is used as a constructor (with the new keyword), its this is bound to the new object being constructed.

Note: while the default for a constructor is to return the object referenced by this, it can instead return some other object (if the return value isn’t an object, then the this object is returned).

/*
 * Constructors work like this:
 *
 * function MyConstructor(){
 *   // Actual function body code goes here.  
 *   // Create properties on |this| as
 *   // desired by assigning to them.  E.g.,
 *   this.fum = "nom";
 *   // et cetera...
 *
 *   // If the function has a return statement that
 *   // returns an object, that object will be the
 *   // result of the |new| expression.  Otherwise,
 *   // the result of the expression is the object
 *   // currently bound to |this|
 *   // (i.e., the common case most usually seen).
 * }
 */
function C(){
  this.a = 37;
}
var o = new C();
console.log(o.a); // logs 37

function C2(){
  this.a = 37;
  return {a:38};
}
o = new C2();
console.log(o.a); // logs 38
In the last example (C2), because an object was returned during construction, the new object that this was bound to simply gets discarded. (This essentially makes the statement “this.a = 37;” dead code. It’s not exactly dead, because it gets executed, but it can be eliminated with no outside effects.)

call and apply

Where a function uses the this keyword in its body, its value can be bound to a particular object in the call using the call or apply methods that all functions inherit from Function.prototype.

function add(c, d){
  return this.a + this.b + c + d;
}
var o = {a:1, b:3};

// The first parameter is the object to use as
// 'this', subsequent parameters are passed as 
// arguments in the function call
add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16

// The first parameter is the object to use as
// 'this', the second is an array whose
// members are used as the arguments in the function call
add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34
 Note that with call and apply, if the value passed as this is not an object, an attempt will be made to convert it to an object using the internal ToObject operation. So if the value passed is a primitive like 7or 'foo', it will be converted to an Object using the related constructor, so the primitive number 7 is converted to an object as if by new Number(7) and the string 'foo' to an object as if by new String('foo'), e.g.
function bar() {
  console.log(Object.prototype.toString.call(this));
}

bar.call(7); // [object Number]
The bind method

ECMAScript 5 introduced Function.prototype.bind. Calling f.bind(someObject) creates a new function with the same body and scope as f, but where this occurs in the original function, in the new function it is permanently bound to the first argument of bind, regardless of how the function is being used.

function f(){
  return this.a;
}

var g = f.bind({a:"azerty"});
console.log(g()); // azerty

var o = {a:37, f:f, g:g};
console.log(o.f(), o.g()); // 37, azerty
As a DOM event handler

When a function is used as an event handler, its this is set to the element the event fired from (some browsers do not follow this convention for listeners added dynamically with methods other thanaddEventListener).

// When called as a listener, turns the related element blue
function bluify(e){
  // Always true
  console.log(this === e.currentTarget); 
  // true when currentTarget and target are the same object
  console.log(this === e.target);
  this.style.backgroundColor = '#A5D9F3';
}

// Get a list of every element in the document
var elements = document.getElementsByTagName('*');

// Add bluify as a click listener so when the
// element is clicked on, it turns blue
for(var i=0 ; i<elements.length ; i++){
  elements[i].addEventListener('click', bluify, false);
}
In an in–line event handler

When code is called from an in–line handler, its this is set to the DOM element on which the listener is placed:

<button onclick="alert(this.tagName.toLowerCase());">
  Show this
</button>
The above alert shows button. Note however that only the outer code has its this set this way:
<button onclick="alert((function(){return this}()));">
  Show inner this
</button>
In this case, the inner function’s this isn’t set so it returns the global/window object (i.e. the default object in non–strict mode where this isn’t set by the call).

this is neither a reference to the function itself, nor is it a reference
to the function’s lexical scope.
this is actually a binding that is made when a function is invoked, and
what it references is determined entirely by the call-site where the
function is called.

Copy Right @ MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

HTTP Cookie

1. HTTP Cookie Explained
2. Cookie and Security

3. RFC 2109
4. Session Cookie
A session cookie or transient cookie is created by simply not setting a date in the Set-Cookie option when an application creates the cookie.
Session cookies are often used to enable a site to be able to track the pages that a user has visited during a visit so that information can be customized for the user in some way. Some sites use Secure Sockets Layer (SSL) to encrypt the information contained in a cookie.
5. Persistent Cookie
A persistent cookie, an expiration date is set and the cookie is stored on the user’s hard drive until the expiration date or until the user deletes it.
6. HTTP-Only Cookie
Web server can set the HTTPOnly flag on a cookie it creates, indicating the cookie should not be accessible on the client through JavaScript.