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/

NUS MComp CS5344 Big Data Technologies

Big Data. It is not important, you are not required to web-scrap some big size of data.

Technologies.Yes, this is the point.

You can learn mapReduce/Hadoop, recommendation systems, page ranks and all kinds of algorithms. They are really hard to understand and even harder to implement. So you are required to understand them to conquer the tests (people did get 0000 mark).

Three programming labs + 3 online-tests + 2 open-book algo tests + 1 final team project. There are a lot of things to learn if you want and the Professor is great.

Prepare: read all those algorithms in bid data areas.

Not relevant.

NUS MComp CS5224 Cloud Computing

Oh, Cloud computing sounds good.

The lectures are all about the basic concepts in cloud computing. You won’t learn any cloud technologies in the implementation level.

Learn IBM Bluemix, anyone uses or knows it? and Amazon cloud services in basics.

No programming needed. Two closed-book tests, middle term and the final.

Plus a 30% of team project using Cloud/Web/Viz skills. The project can be a simple one, but if you want grade A, then it must be creative and not simple.

You must memorize the lecture notes for the tests or you won’t get a high score.

NUS MComp IS5126 Hands On with Business Analytics

It’s good to take this course if you want to challenge yourself with learning introduction of Python programming and statistics. But, be sure to have programming background or a team member who is strong and willing to solve the assignments.

Two contiguous assignments about analysing the salaries of  NBA players. One big term project (50%) of any topic (better in casual analysis, which is hard). Plus a simple case study presentation.

Lectures are in MBA style case discussions, and not really useful if you are just a new graduate. OK. it’s hard to understand the materials which meant for MBA executives in Harvard. WTF!!!

No exams. The AP won’t fail anyone.

Prepare:

  1. statistics / business analysis background
  2. Python programming
  3. time-consuming (no kidding)

港股黑名单

炒股,如果你只是玩一点零花钱,比如2万块钱,你可以觉得赚亏一倍都没什么大不了,你下个月努力工作就赚回了。

如果你是用5年,10年的积蓄去买股票,那么,可得小心了。赚亏10%,就是你工作好几年赚来的血汗钱。

奇怪的是大多数人买个不到1万快钱的电脑都要货比三家,挑选品牌,但是买股票,却是几分钟内用屁股拍板。

股市的钱有那么好赚,华尔街就不需要存在了。

先贴一条新闻:香港老千股横行 李小加呼吁投资者小心别碰

然后贴一个黑名单

避免常见的几大庄家:

威利系、宏安系、中国星系、詹壳王系、庞壳王系、陈壳王系中的大部分、金利丰系中的大部分、萧才子系、抽水机官永义

然后再避免用大钱去赌创业股和股权集中度超过80%的公司。

我自己的黑名单总结。

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.