Remove Javascript console.log Automatically

| Comments

When writing a large JavaScript application, it is quite often that console.log and other debugging statements are left here and there. Obviously, at one point those statements need to be removed for the production version or even when the code needs to be checked in into the source repository. There are many different ways to do this, there exists a new tool called groundskeeper which can do this removal for you.

Written for Node.js, groundskeeper (GitHub: github.com/Couto/groundskeeper) is created by Luís Couto to handle logging removal by understanding the syntax tree of the code and deleting the relevant parts. It is not based on regular expression at all. Groundskeeper parses the code (via Esprima) and modify the syntax nodes (via falafel) associated with any logging. Beside a command-line tool, groundskeeper is also a library ready to be used in any other tools and build systems.

Using groundskeeper is pretty simple (as its documentation explained). Let’s assume we have the following filter-debug.js:

1
2
3
4
5
6
7
8
9
10
function filter(list, age) {
  var result = [];
  list.forEach(function (person) {
    if (person.name && person.age > age) {
      console.log('including', person.name);
      result.push(person);
    }
  });
  return result;
}

After its package is installed, running something like:

groundskeeper < filter-debug.js > filter.js

will give the following filter.js:

1
2
3
4
5
6
7
8
9
10
function filter(list, age) {
  var result = [];
  list.forEach(function (person) {
    if (person.name && person.age > age) {

      result.push(person);
    }
  });
  return result;
}

The line containing console.log is now a blank line. Because groundskeeper doesn’t delete the line, the processed output still has the same amount of lines of code as the original one.

How about debugger? We know that this statement may cause some problems with old web browsers. Fortunately groundskeeper can also get rid of any debugger statements in the code. In fact, you can even nuke any other custom application logger you might have. Here is a code fragment:

1
2
3
debugger
var list = filter(customers, 25);
RentalApp.Logger.print(JSON.stringify(list, null, 2));

which can be processed via:

groundskeeper -n RentalApp.Logger < rental.js

and give you the remaining output: var list = filter(customers, 25);

The biggest benefit of automatic removal is when it is combined with Git pre-commit hook so that no more manual step is necessary. This is pretty similar to the use of syntax validation trick. Here is an example of such a hook:

1
2
3
4
files=$(git diff-index --name-only --diff-filter=ACM HEAD | grep -P '\.js$')
for file in $files; do
  groundskeeper < $file > $file.tmp && mv $file.tmp $file
done

All touched *.js files will be processed via groundskeeper before they are checked in. This way, none of them will have stray console.log, debugger statements, or any other custom logger calls anymore. Thus, your repository is guaranteed to be free from debugging leftovers!

Avoiding Unwanted Scopes Creation in AngularJS

| Comments

One of the most appreciated features of AngularJs is scopes, at the same time scopes will give you nightmare if don’t avoid unwanted scopes from creating.

Preventing ng-model data scope is one of the main challenge you get quite often. While working with ng-model data, new unwanted scope can be created by ng-repeat or ng-if procedures. Let’s look at the below example

See the Pen Angular unwanted scope creation by Logesh Paul (@logeshpaul) on CodePen.

In the above example, the scope is created separately for innerScope and outerScope, so it does not share it’s data. We can handle this with single scope - One way to do this is we can use “Controller As” approach instead of using scope as a container for all data and functions.

One catchy solution is to keep everything in objects as shown is below example

See the Pen Angular avoiding unwanted scope creation by Logesh Paul (@logeshpaul) on CodePen.

Let me what methods/best practices you follow to avoid unwanted scopes from creating in AngularJS.

Handling Browser Window Resize in ReactJS

| Comments

If you want to handle some use cases like “I want to update a div container width on browser window resize in react application” then you are in the right place.

In jQuery it’s fairly simple like below.

1
2
3
4
5
6
$( window ).resize(function() {
  var reelContainerWidth = $(window).width() - 400;

  // sets the width of reel-container to (window size - 400px)
  $("#reel-container").width(reelContainerWidth);
});

In the React world we have do it in slightly different way.

  1. Set initial width in default state
  2. Calculate viewport width each time the browser windows change size
  3. Re-render our component by passing the updated width through state

React way

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
var React = require("react"),
ReactDOM = require("react-dom");

var ReelContainer = React.createClass({

  getInitialState: function() {
    return {
      reelContainerWidth: 100
    };
  },

  /**
   * Calculate & Update state of new dimensions
   */
  updateDimensions() {
    const reelContainerWidth = window.innerWidth - 400;

    // sets the width of reel-container state to (window size - 400px)
    this.setState({ reelContainerWidth: reelContainerWidth });
  }

  /**
   * Add event listener
   */
  componentDidMount() {
    this.updateDimensions();
    window.addEventListener("resize", this.updateDimensions);
  }

  /**
   * Remove event listener
   */
  componentWillUnmount() {
    window.removeEventListener("resize", this.updateDimensions);
  }

  render(): React.Element {
    const reelContainerWidth = { width: this.state.reelContainerWidth };

    return(
      <div id="reel-container" style={reelContainerWidth}>
         Reel Content
      </div>
    );
  }
}

module.exports = ReelContainer;

Scope in Javascript

| Comments

Traditionally, JavaScript only has two types of scope:

1) Global Scope: Variables are known throughout the application, from the moment they are declared onwards

2) Functional Scope: Variables are known within the function they are declared in, from the moment they are declared onwards

The most recent JavaScript specs(ES6) now also allow a third scope:

3) Block Scope: Variables are known within the block they are declared in, from the moment they are declared onwards

How do I create block scope variables?

1
2
var myVariable = "Some text"; // Traditional approach
let myVariable = "Some text"; // Blocked scope

Here is some examples to understand scopes better

A globally-scoped variable

1
2
3
4
5
6
var a = 1;

// global scope
function one() {
  alert(a); // alerts '1'
}

Local scope

1
2
3
4
5
6
7
8
9
10
11
var a = 1;

function two(a) {
  alert(a); // alerts the given argument, not the global value of '1'
}

// local scope again
function three() {
  var a = 3;
  alert(a); // alerts '3'
}

Intermediate: No such thing as block scope in JavaScript (ES5; ES6 introduces let)

1
2
3
4
5
6
7
8
9
var a = 1;

function four() {
  if (true) {
    var a = 4;
  }

  alert(a); // alerts '4', not the global value of '1'
}

Global+Local: An extra complex Case

1
2
3
4
5
6
7
var x = 5;

(function () {
    console.log(x);
    var x = 10;
    console.log(x);
})();

This will print out undefined and 10 rather than 5 and 10 since JavaScript always moves variable declarations (not initializations) to the top of the scope, making the code equivalent to:

1
2
3
4
5
6
7
8
var x = 5;

(function () {
    var x;
    console.log(x); // undefined
    x = 10;
    console.log(x); // 10
})();

Intermediate: Object properties

1
2
3
4
5
6
7
var a = 1;

function five() {
  this.a = 5;
}

alert(new five().a); // alerts '5'

Advanced: Closure

1
2
3
4
5
6
7
8
9
10
11
var a = 1;

var six = (function() {
  var a = 6;

  return function() {
    // JavaScript "closure" means I have access to 'a' in here,
    // because it is defined in the function in which I was defined.
    alert(a); // alerts '6'
  };
})();

Advanced: Prototype-based scope resolution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var a = 1;

function seven() {
  this.a = 7;
}

// [object].prototype.property loses to
// [object].property in the lookup chain. For example...

// Won't get reached, because 'a' is set in the constructor above.
seven.prototype.a = -1;

// Will get reached, even though 'b' is NOT set in the constructor.
seven.prototype.b = 8;

alert(new seven().a); // alerts '7'
alert(new seven().b); // alerts '8'

Understanding Closures in Javascript

| Comments

Closure is when a function ‘remembers’ its lexical scope even when the function is executing outside that lexical scope. ~ Kyle Simpson

A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: - It has access to its own scope (variables defined between its curly brackets) - It has access to the outer function’s variables - It has access to the global variables

The inner function has access not only to the outer function’s variables, but also to the outer function’s parameters. Note that the inner function cannot call the outer function’s arguments object, however, even though it can call the outer function’s parameters directly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var pizza = function() {
  var crust = "thin";
  var toppings = 3;
  var hasBacon = true;

  var getToppings = function() {
    return toppings;
  }

  var pizzaInfo = {};
  pizzaInfo.getToppings = getToppings;

  return pizzaInfo;
}

var pizzaA = new pizza();

pizzaA.getToppings(); // returns 3
  • Closures are useful in hiding the implementation of functionality while still revealing the interface
  • Closure is one way of supporting first-class functions; it is an expression that can reference variables within its scope (when it was first declared), be assigned to a variable, be passed as an argument to a function, or be returned as a function result.
References: