Category Archives: JavaScript

Configuring ESLint and Prettier in Atom

Install eslint and optional plugins:

npm install -g eslint eslint-plugin-react

Install atom plugins:


Create .eslintrc either in the root of your application (or your root path if you want it to be global)

Add simple configuration rules:

    "plugins": [
    "parserOptions": {
        "ecmaVersion": 6,
        "sourceType": "module",
        "ecmaFeatures": {
            "jsx": true
    "env": {
        "es6":     true,
        "browser": true,
        "node":    true,
        "mocha":   true
    "extends": [
    "rules": {

Optionally, update atom prettier-atom to format on save (in plugin settings)

ESLint with Visual Studio 2015

If you used Web Essentials as your linter, you probably learned by now that it doesn’t provide that functionality anymore in VS 2015.
One way to fix it is to start using tools like gulp… or you could install a plugin – Web Analyzer

The tool seems to rely on node, so you need to install that as well. Also, it doesn’t look like it installs all of the necessary packages (at least it didn’t work for me, until I installed the packages). So, you may need to run npm install for these packages:
npm install -g eslint eslint-config-defaults
npm install -g babel-eslint

To config it, go to Tools – Web Analyzer – Edit ESLint Settings. All of the configuration settings can be found at For example, if you use Jasmine tests and jQuery, your “env” will look like this:
“env”: {
“browser”: true,
“node”: true,
“es6”: true,
“jasmine”: true,
“jquery”: true

In the “rules” block you can turn on/off individual rules and specify if they should show up as warnings (1) or errors (2).
“rules”: {
“eqeqeq”: 2,

This means that if ESLint sees “==” instead of “===” it will show up as an error in your Visual Studio Error List.

From .Net Developer to Elm. Part 2 – Making a Simple Project.

In this article I’ll write a simple Bayesian Calculator using Elm.
Link to final project – Bayesian CalculatorSource Code

Create a directory for your project.
cd into it.
Run “elm-make” to initialize a new elm project.
Install some packages for working with web:

elm-package install “evancz/elm-html”
elm-package install “evancz/start-app”

start-app takes care of some application wiring,”setting everything up so you can focus entirely on writing your app

If you open elm-package.json, you will see that the packages, which we just installed, were added to “dependencies” node.

I’ll use npm and gulp to manage my build. Also, I’m using bootstrap (cause css is hard)
npm init
npm install bootstrap –save-dev
npm install gulp –save-dev
npm install gulp-elm –save-dev
npm install gulp-rename –save-dev

The last piece of setting up is gulp. In the script, I just combine all css and js into bundles and copy them to dest folder.

We’re ready to start writing our app.

Create Calculator.elm. This is where our code will go.

Create Calculator.html. This will encapsulate resulting JavaScript file from Elm. Since I’m writing a full-screen application, all we have to do is add this to the script block:

var app = Elm.fullscreen(Elm.Calculator);

Now, to the application code.

Our model is quite simple – consists of four string fields related to four input fields on the form.
We have three inputs on the page – all encapsulated inside entryForm:

entryForm : Address Action -> Model -> Html
entryForm address model =
    [ class "form-horizontal" ]
    [ formGroupItem (priorProbabilityItem address model)
    , formGroupItem (hitRateItem address model)
    , formGroupItem (falseAlarmItem address model)
    , formGroupItem (resultItem address model)

formGroupItem is simply a method to produce another div with a class of “form-group”:

formGroupItem : List Html -> Html
formGroupItem body =
    [ class "form-group" ]

body in here is just a list of Html elements that we are passing to our div.

Let’s look at one of the inputs:

priorProbabilityItem : Address Action -> Model -> List Html
priorProbabilityItem address model =
  [ label
      [ for "priorProbability", class "col-md-3 control-label" ]
      [ text "Prior Probability" ]
  , div
      [ class "col-md-9" ]
      [ input
          [ type' "text"
          , placeholder "0.00"
          , value model.priorProbability
          , id "priorProbability"
          , autofocus True
          , Utils.onInput address UpdateInitialProbability

We have a label and a div with an input which maps to priorProbability field in our model.
Every time a user enters something we react to it by addressing UpdateInitialProbability action:

update : Action -> Model -> Model
update action model =
  case action of
    UpdateInitialProbability probability ->
      { model | priorProbability = probability }

In the code above we are updating our model with the new value that a user entered for priorProbability.
We have the same logic for all of the other input fields.

Every time a model changes, we try to show the Bayes calculation result:

resultItem : Address Action -> Model -> List Html
resultItem address model =
  [ label
      [ for "bayesResult", class "col-md-3 control-label" ]
      [ text "New Probability" ]
  , div
      [ class "col-md-9" ]
      [ span [] [ text (bayesResult model) ]

bayesResult is responsible for generating new probability. If some input is invalid, we just don’t display anything. Sure, validation could be a little more sophisticated, but we’re just trying it out.

While in development, make sure to run elm-reactor and gulp in the command line – open two tabs or windows (depending on your console app) for each one and just run “elm-reactor” in one, and “gulp” in another.

In order to see your app in a browser, go to http://localhost:8000/dest/Calculator.html
Every time you save your elm file, it should update the js files in the dest folder. You still have to refresh the browser to see the changes. I haven’t quite figured the auto-refresh part with gulp and elm.

If you want to see the build errors, they should show up in the console, which runs gulp command. Alternatively, if you use Sublime, press Ctrl + B to build it and all errors should show up directly in Sublime.

What’s new JavaScript 2015/es6 (short summary)

  • let – block scope; no hoisting
  • const
  • Blocked scoped functions
        function foo () { return 1 }
        foo() === 1
            function foo () { return 2 }
            foo() === 2
        foo() === 1
  • Destructuring
    let foo = ["one", "two", "three"];
    let [one, two, three] = foo;
    console.log(one); // "one"
    console.log(two); // "two"
    console.log(three); // "three"
    let a = 1;
    let b = 3;
    [a, b] = [b, a];
    console.log(a); // 3
    console.log(b); // 1
    var expense = {
      type: 'Business',
      amount: '$40'
    const {type, amount} = expense;
    //Or use in functions:
    function({type, amount}){}
  • Defaults

    let hasDefaults = function(something = "default"){
    console.log(something); //default
  • Rest/Spread

    function sortRestArgs(...theArgs) {
      var sortedArgs = theArgs.sort();
      return sortedArgs;
    console.log(sortRestArgs(5,3,7,1)); // shows 1,3,5,7
    const defaultColors = ['red', 'green'];
    const extraColors = ['orange', 'blue'];
    [...defaultColors, ...extraColors]
  • Template literals

    var a = 5;
    var b = 10;
    console.log(`Fifteen is ${a + b} and\nnot ${2 * a + b}.`);
    // "Fifteen is 15 and
    // not 20."
  • Arrow Functions

    let add = (a,b) => a+b;
    let sum = add(1,2);

    Also makes ‘this’ behave as you would expect it to behave.

  • Iterators and Generators
    for(let value of ["a", "b", "c"]){
    // "a"
    // "b"
    // "c"
    function* idMaker(){
      var index = 0;
        yield index++;
    var gen = idMaker();
    console.log(; // 0
    console.log(; // 1
    console.log(; // 2
    for(let value of idMaker()){
  • New Data Types

    var myMap = new Map();
    myMap.set(0, "zero");
    myMap.set(1, "one");
    for (var [key, value] of myMap) {
      console.log(key + " = " + value);
    // Will show 2 logs; first with "0 = zero" and second with "1 = one"
    var mySet = new Set();
    mySet.add("some text");
    var o = {a: 1, b: 2};
    mySet.has(1); // true
    mySet.has(3); // false, 3 has not been added to the set
    mySet.has(5);              // true
    mySet.has(Math.sqrt(25));  // true
    mySet.has("Some Text".toLowerCase()); // true
    mySet.has(o); // true
    mySet.size; // 4
    mySet.delete(5); // removes 5 from the set
    mySet.has(5);    // false, 5 has been removed
    var wm1 = new WeakMap(),
        wm2 = new WeakMap(),
        wm3 = new WeakMap();
    var o1 = {},
        o2 = function(){},
        o3 = window;
    wm1.set(o1, 37);
    wm1.set(o2, "azerty");
    wm2.set(o1, o2); // a value can be anything, including an object or a function
    wm2.set(o3, undefined);
    wm2.set(wm1, wm2); // keys and values can be any objects. Even WeakMaps!
    ar ws = new WeakSet();
    var obj = {};
    var foo = {};
    ws.has(window); // true
    ws.has(foo);    // false, foo has not been added to the set
    ws.delete(window); // removes window from the set
    ws.has(window);    // false, window has been removed
  • Modules

    export let a ={};
    export let b =function(){};
    import {a,b} from c
  • Promises

        var p1 = new Promise(        
            function(resolve, reject) {
                    function() {
                    }, Math.random() * 2000 + 1000);
            function(val) {           
            function(reason) {
                console.log('Handle rejected promise ('+reason+') here.');
    //With fetch:
      .then(response => response.json())
      .then(data => console.log(data));
  • Class, constructors
    class Test {
    class SubTest extends Test{
  • Array Helper methods


    let colors = ['red', 'blue', 'green'];
    colors.forEach(c => console.log(c)); 
    let numbers = [1, 2, 3];
    let doubled = => c * 2);
    let sum = numbers.reduce((sum, number) => sum + number, 0)
    let divisibleByTwo = numbers.filter(c => c % 2 === 0);
    let allDivisibleByTwo= numbers.every(c => c % 2 === 0);
    let someDivisibleByTwo= numbers.some(c => c % 2 === 0);
    let users = [ {name: 'Jay'},{name: 'May'},{name: 'Jay'} ]
    let jay = users.find(u => === 'Jay')
  • Enhanced Object Literals

    function test(someValue)
        return {
          someValue: somevalue,
          someFunction: function(){}
    Is now equivalent to 
     function test(someValue)
        return {

Some great resources on es6 – and

Custom Dynamic Error Messages with JQuery Unobtrusive Validation

This could be helpful for the circumstances when you need to dynamically determine the error message for one of you custom validators:

$.validator.addMethod('customvalidatorname', function(value, element, parameters) {
	return validationFunction();
}, function(params, element) {
	return errorMessageFunction();

The third parameter to addMethod can be a function which dynamically determines your error message.