Saturday, October 21, 2017

JavaScript ES2015 ES6 Module Support

ES6 lets you natively define and use modules.

Since most Web Browsers do not currently support this feature, the code must be transpiled into ES5 using a tool such as Babel. This must occur at build time as a development step.

The code is transpiled into AMD or CommonJS module format by the tool. The HTML source then references RequireJS/SystemJS that is used by the Browser to load the modules in the depedency order at runtime.

To avoid use of a runtime module loader (for efficiency sake), the code can be bundled using bundlers such as Webpack (AMD module format) or Browserify (commonjs module format; commonly used to package nodejs code for use in a Browser) as a development step. The development step takes the transpiled source code and creates one or more bundled js files that contains code in the module dependency order (hence eliminating the need for a runtime module loader).

Module Export Syntax

Export functions inline

// somefile.js
export function doSomething(doWhat){
}

export function printResults(){
}

// do not export a private function
function privateHelper(){
}

// export a variable
export var pi = 3.142

Export public functions with a declaration

// somefile.js
function doSomething(doWhat){
}

function printResults(){
}

function privateHelper(){
}

// export a variable
var pi = 3.142

// we are renaming printResults to print when exporting
// we are also exporting a variable (can do the same for classes)
// privateHelper is not a part of the Api
export { doSomething, printResults as print, pi}

Specify Default Export

// somefile.js
export function doSomething(doWhat){
}

// make printResults the default function exported out of this module
export default function printResults(){
}

function privateHelper(){
}

// export a variable
export var pi = 3.142

Module Import Syntax

// import all public functions from the module
// methods can be invoked on extModule, e.g. extModule.printResults()
import * as extModule from './somefile.js'

// selective import of functions
// functions are invoked as usual e.g. printResults()
import {doSomething, printResults} as extModule from './somefile.js'

// selective import of functions with an alias
// function are invoked with its alias e.g. print()
import {doSomething, printResults as print} as extModule from './somefile.js'

// import the default function as print()
import print from './somefile.js'

// import the default function and another function
// print() is exported as default, also import doSomething function
import print, {doSomething} from './somefile.js'

Friday, October 20, 2017

JavaScript Module Formats and Loaders

JavaScript Module Formats

How JavaScript code (function) is structured into a module that can be loaded by Module loader at runtime in correct dependency order. This is just a convention followed in plain js to form Modules.
  • AMD Format (Asynchronous Module Dependency) - primarily used in Browser js since it has the advantage of being async loading. define function is used to load dependencies.
  • CommonJS Format - more prevalent in server (nodeJs) apps. require function is used to load dependencies.
  • Universal Module Definition (UMD) - Has both the features of AMD and CommonJS
  • System.register - Specific to SystemJS module loader
  • ES2015 - Native support in ES6 - Need to use something like Babel to use in current browsers

JavaScript Module Loaders

JavaScript libraries that load modules (specified in supported format) while honoring the dependencies.
  • RequireJS Module Loader can load modules in AMD Format
  • SystemJS Module Loader can load modules in CommonJS Format



Thursday, October 19, 2017

JavaScript Modules

Singleton Pattern

Immediately Invoked Function Expression (IIFE) returns an object that contains references to the public API of the module.

displayName function-scoped variable serves as the data member and retains its value as a result of function closure.

var myModule = (function(){
    var displayName

    function setName(name){
        displayName = name
    }

    function printName(){
        console.log('Hello ' + displayName)
    }

    return{
        setName : setName,
        printName : printName
    }
})()

myModule.setName('Bob')
myModule.printName()

Hello Bob

Function Constructor Pattern

MyModule is a reference to a function closure. It is not immediately invoked. It still returns an object that contains references to the public API of the module. We can create multiple instances of this function using the new keyword. Each instance maintains its own state (displayName in this case).

var MyModule = function(){
    var displayName

    function setName(name){
        displayName = name
    }

    function printName(){
        console.log('Hello ' + displayName)
    }

    return{
        setName : setName,
        printName : printName
    }
}

myModule = new MyModule
yourModule = new MyModule
myModule.setName('Jack')
yourModule.setName('Diane')
myModule.printName()
yourModule.printName()

Hello Jack
Hello Diane

// Same as above but using prototype for efficiency
// (function definitions are not duplicated for each instance)
var MyModule = function(){
    var displayName
}

MyModule.prototype.setName = function setName(name){
    this.displayName = name
}

MyModule.prototype.printName = function printName(){
console.log('Hello ' + this.displayName)
}

myModule = new MyModule
yourModule = new MyModule
myModule.setName('Jack')
yourModule.setName('Diane')
myModule.printName()
yourModule.printName()

Hello Jack
Hello Diane

Tuesday, October 17, 2017

JavaScript ES6 ES2015 New Feature Overview

JavaScript adds more useful language features in ES6 (ES2015).

New features can be used right now while being backwards compatible with older browsers by using Babel js which transpiles ES6 to ES5. Babel js can be used in a build step for a js project.
https://babeljs.io/

ES6 be used on the backend (nodeJs) and front end (React, etc.).

Destructuring

Take an object or an array and rip it apart into variables.

// object
var o = {
    p1: 1,
    p2: 2
}
var {p1, p2} = o
console.log (p1, p2)

1 2

// array
var a = [1, 2]
var [v1, v2] = a
console.log (v1, v2)

1 2

// function arguments
var o = {
    arg1: 1,
    arg2: 2
}

var fn = ({arg2, arg3, arg1}) => {
    console.log(arg1, arg2, arg3)
}

fn(o)

1 2 undefined

Spread Operator

function fn(a1, a2, a3){
    console.log(a2)
}

var arr = [1, 2, 3]
fn(...arr)

2

var arr = [1, 2, 3, 4, 5]
var [first, ...theRest] = arr
console.log(first)
console.log(theRest)

1
(4) [2, 3, 4, 5]]

var ar1 = [4, 5]
var ar2 = [1, 2, 3]

var ar = [...ar2, ...ar1, 6]
console.log(ar)

(6) [1, 2, 3, 4, 5, 6]

Template Strings

// use back tick and ${varName}
var name = "Slim Shady"
var formattedStr = `My name is
${name}`

console.log(formattedStr)

My name is
Slim Shady

Block Scoping

// var scoping is at function level
// No matter where a variable is defined in a function,
// the variable is hoisted to the top of the function
// let
// Limits scope of a variable to a block (e.g. if and loop stmt blocks)
// Use let EVERYWHERE instead of var

let v = 1

if (true){
    let v = 2
    console.log(v)
}

console.log(v)

2
1

Constants

// const to define a variable that can be assigned to only once
// However, an object assigned to a const CAN be mutated
// user const everywhere if you prefer immutable objects in JavaScript

const c = 1
c = 2
console.log(c)

Uncaught TypeError: Assignment to constant variable.

Arrow Functions

var fn =(a, b) => {
    return a + b
}
console.log(fn(1, 2))

// implict return
var fn = (a, b) => a + b
console.log(fn(2, 3))

3
5

const total = [0, 1, 2, 3].reduce((sum, value) => sum + value, 1)
console.log(total)

7

// arrow functions automatically set lexical context
// may not be desired when writing callbacks for some libraries,
// such as jQuery where this is bound to jQuery library
var o = {
data: 1,
print : function(){
console.log(this.data)
}
}
 o.print()

1

// must bind to this in order to access the data
var o = {
data: 1,
print : function(){
setTimeout(function() {
console.log(this.data)
}.bind(this), 100)
}
}
o.print()

1

// Alternate: use arrow function, no need to bind this
var o = {
data: 1,
print : function(){
// automatically binds the this context
setTimeout(() => {
console.log(this.data)
}, 100)
}
}
o.print()

1

var numbers = [1,2,3,4,5]
var strings = numbers.map(n => n.toString())
console.log(strings)

(5) ["1", "2", "3", "4", "5"]

// How to use 'this' in a timer function (without arrow functions),
//  whose context is Global context, not the function context
//  this.val is scoped to the function
//  define'that' variable in the function closure to keep a reference to 'this'
//  to be accessed by setTimeout function that runs in global scope
function fn() {
    var that = this
    this.val = 0

    setTimeout(function inc(){
        // can't use this.val because this function is in global scope
        that.val++
    }, 0)

    this.print = function() {
        console.log(that.val)
    }
}

var f = new fn()

setTimeout(() => f.print(), 100)

1

// arrow functions are lexically scoped to the block they are contained
//  now we no longer have to preserve 'this' in 'that' variable
function fn() {
    this.val = 0

    setTimeout(() => {
        this.val++
    }, 0)

    this.print = function() {
        console.log(this.val)
    }
}

var f = new fn()

setTimeout(() => f.print(), 100)

1

Classes

class Base{
    constructor(){
        this.data = 1 
    }
 
    fn(){
        console.log('Base ' + this.data)
    }
}

class Derived extends Base{
constructor(){
        super()
    }
    fn(){
        console.log('Derived ' + this.data)
    }
}

var base = new Base()
base.fn()

var derived = new Derived()
derived.fn()

Base 1
Derived 1

Module System

Replaces 'require' library

Export (module1.js):
module.exports.pi = () => 3.142
module.exports.multidentity = () => 1

// entire module export is replaced with this function
export default function(){
}
// export entire module
export default {
}

To export function:
export function fn(){
}

To export variable:
export const pi = 22/7

To import:
import module1 from "module1"

To import (with destructuring, selectively pull what you need):
import {pi, multidentity} from "module1"

To import with an alias:
import {pi, multidentity as one} from "module1"
console.log(one)

Async (Generator function) Function

async function() {
var data = await $.get(url)
console.log(data)
}

Friday, October 13, 2017

Immutable data in JavaScript


Immutable Data

How not to change existing structure data itself but make a new copy of the data to work with

Object 

var a = {p1 : 'A', p2 : 3.142}
// {p1: "A", p2: 3.142}

// Make a copy of object referenced by a
// and replace the value of property p1 with the one specified (i.e. 'B')
var b = Object.assign({}, a, {p1 : 'B'})
// {p1: "B", p2: 3.142}

// same as above, but using the Object Spread Operator
var c = {...a, p1 : 'C'}
//{p1: "C", p2: 3.142}

Arrays

concat, filter, map, and reduce return new arrays.

var a = [1,2,3]
// [1, 2, 3]

// create a new array from contents of a and add another element to it (i.e. 4)
var b = a.concat(4)
// [1, 2, 3, 4]

Objects with Arrays

Objects that have arrays embedded in them.

var a = {p1 : "myList", ar : [1,2,3]}
// {p1: "myList", ar: Array(3)}
// ar : (3) [1, 2, 3]

var b = Object.assign({}, a)
// {p1: "myList", ar: Array(3)}
// ar : (3) [1, 2, 3]

// make a copy of array from object a into object b
// so that changes to either arrays do not effect eachother
b.ar = a.ar.concat(4)
// ar : (4) [1, 2, 3, 4]

Tuesday, October 3, 2017

React JS Q&A

1. What is it?

JavaScript library for building HTML user interfaces for the Web Browser.
React abstracts away the generation of HTML as JSX (a representation of HTML in JavaScript).

2. How does it work?

  • Uses JavaScript to product HTML.
  • Uses JSX, a special syntax to specify HTML tags with in JavaScript. JSX is transpiled to regular JavaScript that runs in any browser (createElement() etc.).
  • React creates a virtual DOM in memory that is rendered as the DOM of the Web Browser.

3. How is React code organized?

  • React code is organized as Components.
  • A React Component is either a Function Component or a Class Component.
  • Function Component is does not have an internal state.
  • Class Component can maintain an internal state.
  • React application is created by composing React Components.
  • React Components are usually rendered on the client although they can rendered on the Server using node.js.

4. What is a React Function Component?

  • Receives props
  • Returns JSX
  • JSX is converted to HMTL by transpiler
const Button = (props) => {
return (
  <div>
      <span>Action: </span>
      <button>{props.label}</button>
    </div>
  );
};

ReactDOM.render(<Button label='Go'/>, mountNode);

5. What is a React Class Component?

  • Class Component receives props just like Function Component but as as data member of the class
  • this.state is a special data member of the class that holds state of the component
  • render() is a special function that returns the JSX

class UCaseComponent extends React.Component {
  state = {enteredValue : 'initial', uppercaseValue : 'initial'.toUpperCase()};
  
  handleTextChange = (e) =>{ 
    this.setState({enteredValue: e.target.value, uppercaseValue :  e.target.value.toUpperCase()});
}
  
  render() {
    return (
    <div>
      <input type="text" value={this.state.enteredValue} onChange={this.handleTextChange}/>
      <div><span>{this.props.labelEnteredValue}: </span>{this.state.enteredValue}</div>
      <div><span>{this.props.labelUppercase}: </span>{this.state.uppercaseValue}</div>
    </div>
   )
  }
}

ReactDOM.render(<UCaseComponent labelEnteredValue='Entered' labelUppercase='Uppercase'/>, mountNode);

6. How does React components pass data?

  • React passes data as properties among components (props).
  • Properties are immutable.

7. How does React maintain state?

  • this.state member (data object) of a React component keeps state around for a component.
  • this.state member of the top-level component maintains state for the application.
  • Change is state automatically triggers a re-render of affected DOM elements. React performs a tree reconciliation of the Virtual DOM with the Browser DOM.
  • To maintain complicated application state, helper state management framework such as Flux can be used along with React.

8. How does React handle HTML events?

  • React encapsulates standard handlers (such as onClick) as function handlers 

9. How can I play with React?

Friday, September 29, 2017

How to guarantee the order of execution in JavaScript?

Use setTimeout() to ensure code is executed in the desired order.


for(i=0; i<100; i++){
setTimeout(function() { console.log(1); }, 0); 
setTimeout(function() { console.log(2); }, 0); 
setTimeout(function() { console.log(3); }, 0);
setTimeout(function() { console.log('-----'); }, 0);
}


1
2
3
-----
1
2
3
-----
1
2
3
-----
1
2
3
-----
.........
.........


for(i=0; i<100; i++){
 setTimeout(function() {
    console.log(1);
    setTimeout(function() {
        console.log(2)
        setTimeout(function() {
            console.log(3)
            }, 0)
        }, 0) 
 }, 0) 
}

100  1
100  2
100  3