Category: JavaScript

Basics Browser Console Object API

Browser console API

This article will be focused in the console object API available in Google Chrome, Mozilla Firefox, and later versions of Internet Explorer browser. We are going to cover few of them in this article, for a full list of available commands go to the References section at the bottom of this article .

The Console object is available in two places: the code and the browser's JavaScript Console.
You probably already know of console.log in my opinion this is the most used command of the console object.

  • console.log

    – For basic logging, Use this to print in the browser's console general string messages about actions taking place within the code, also you can print Objects, Arrays, etc..
    e.g:

    console.log("simple text"); //simple text
    
    var str = 'World';
    console.log("Hello", str); //Hello World
    
    var arr = ['val1','val2','val3','val4'];
    console.log(arr); //["val1", "val2", "val3", "val4"]
    
    var userName = 'jomendez'
    console.log("Authenticating user '%s'", userName); //Authenticating user jomendez
    

 

  • console.error

    – For logging errors in your code. I use console.error within error callbacks on AJAX requests and anywhere else an error might be thrown like a try{}...catch{}. While similar to console.log, this method also includes a stack trace where the error was thrown.
    javascript browser console error

 

     

    book

    Book Tip

    Speaking JavaScript: An In-Depth Guide for Programmers
    Like it or not, JavaScript is everywhere these days—from browser to server to mobile—and now you, too, need to learn the language or dive deeper than you have. This concise book guides you into and through JavaScript, written by a veteran programmer who once found himself in the same position.

    Amazon

     

  • console.dir(object)

    – When you log a DOM element to the console it displays in an HTML format. To display the JavaScript representation you may  use the dir() method
    browser console dir

  • console.group(title)

    – This command is used to create a group of console logging commands it accepts an optional title parameter. To end the grouping just call grouEnd() see below.

    var userName = "jomendez", authenticated = false;
    console.group("Authentication phase");
    console.log("Authenticating user '%s'", userName);
    // place your authentication code here...
    if (!authenticated) {
      console.log("User '%s' is not authenticated.", userName)
    }
    console.groupEnd();
    

    browser console group

 

  • console.groupCollapsed()

    – Exactly the same as the above method, except for the fact the initial group is collapsed and not opened.

 

  • console.groupEnd()

    – This allows you to end the group defined above.

 

  • console.time(label)

    – The console.time() help you to measuring how long a portion of code can take to be excecuted, you must pass a string to the method to identify the time marker. When you want to end the measurement call console.timeEnd() and pass it the same string passed to the initializer. The console logs the label and time elapsed when the console.timeEnd() method fires.

    console.time("Measure Array");
        var array= new Array(1000000);
        for (var i = array.length - 1; i >= 0; i--) {
            array[i] = new Object();
        };
    console.timeEnd("Measure Array");
    

    Result:
    Measure Array: 1923.457ms

 

  • console.timeEnd(label)

    –This allows you to stop the timer logging function and the elapsed time will be printed out,  see the code above.

 

  • console.table()

    - You can use console.table() to View structured data. With this you can view arrays objects, etc.

    function Person(firstName, lastName, age) {
      this.firstName = firstName;
      this.lastName = lastName;
      this.age = age;
    }
    
    var family = {};
    family.mother = new Person("Susan", "Doyle", 32);
    family.father = new Person("John", "Doyle", 33);
    family.daughter = new Person("Lily", "Doyle", 5);
    family.son = new Person("Mike", "Doyle", 8);
    
    console.table(family);
    

    browser console table

 

  •  console.clear()

    - You can use the console.clear() command to clear the browser console.

 

References:

You can find a full list for the console api for the most popular browsers, NodeJs and Firebug:
Chrome: http://developers.google.com/chrome-developer-tools/docs/console-api/
Firebug: http://getfirebug.com/wiki/index.php/Console_API
Firefox: http://developer.mozilla.org/en-US/docs/Web/API/console
Internet Explorer: http://msdn.microsoft.com/en-us/library/ie/hh772183.aspx
Node.js: https://nodejs.org/api/console.html
Safari: http://developer.apple.com/library/safari/documentation/AppleApplications/Conceptual/ Safari_Developer_Guide/Console/Console.html

Notes:

There is bug in Internet Explorer 9 where the console object is only defined if the developer tools were open at least once. That means that you get a Reference Error if you refer to console and the developer tools weren’t open before. As a work around, you can check if the console object exists before you call it.

How to do encapsulation in JavaScript

Encapsulation:

If you come from classical object-oriented languages like Java or C#, it might be a littler tricky to do encapsulation in JavaScript (hiding variables from the external scopes).

In this post we going to see tree ways to do encapsulation with JavaScript:

  1. IIFE (immediately Invoked Function Expression).
  2. Closures
  3. getters and setters Properties.
  4. The Revealing Module Pattern.

IIFE (immediately Invoked Function Expression)

First lets cover what an IIFE is:

In JavaScript we declare functions like this:

function myFunc(){
   console.log(myVar); // "Hello World"
}

And we call the function like this:

myFunc();

An IIFE is a combination of both in one, now, the more common and most used method to create an IIFE is with the parenthesis like this:

(function myFunc(){
   console.log("Hello World"); // "Hello World"
})();

There are other ways to create IIFE, you can accomplish this by using any of the following operators: !, +, -, ~.

!function myFunc(){
   console.log("Hello World"); // "Hello World"
}();

+function myFunc(){
   console.log("Hello World"); // "Hello World"
}();

-function myFunc(){
   console.log("Hello World"); // "Hello World"
}();

~function myFunc(){
   console.log("Hello World"); // "Hello World"
}();

Closures:

In JavaScript a variable scope is defined by the curly braces { } of an expression, for example a function:

function myFunc(){
   var myVar = "Hello World";
}
console.log(myVar) //undefined

myVar is not defined outside of the { } of the function, now notice that you can access a variable defined in the outter scope, like this:

var myVar = "Hello World";
function myFunc(){
   console.log(myVar) // "Hello World"
}

With those two concepts you can encapsulate variables and remove it from the global scope and protect your data. This helps prevent variables and function declarations from living longer than expected in the global scope, which also helps avoid variable collisions. Also When your code is minified and bundled into a single file for deployment to a production, you could have collisions of  global variables. If you adopt to use IFFE in every JavaScript file, it will protects you against both of these by providing variable scope for each file.

 

book

Book Tip

Speaking JavaScript: An In-Depth Guide for Programmers
Like it or not, JavaScript is everywhere these days—from browser to server to mobile—and now you, too, need to learn the language or dive deeper than you have. This concise book guides you into and through JavaScript, written by a veteran programmer who once found himself in the same position.

Amazon

 

getters and setters Properties:

Why getters and setters can be used for encapsulation?
A: To limit access to an internal state of an object.

One of the advantages of properties is that you can have behavior in your fields, also limitate the field to be read only and/or write only.

var myObj = {
   get myVar() {
      return 'Using get';
   },
   set myVar(value) {
      console.log('Using set, value: '+value);
   }
};

Note: Up to IE 8, it doesn’t support get and set operators, instead you’ll have to use the __defineGetter__ and __defineSetter__ methods that can be found in Object.prototype.

var myObj = {
    myVar1: 'Hello',
    myVar2: 'World'
};

myObj.__defineGetter__('sayHello', function(){
    return this.myVar1 + ' ' + this.myVar2;
});

myObj.__defineSetter__('sayHello', function(value){
    console.log(value);
});

The Revealing Module Pattern

With this pattern we encapsulate and hide or reveal variable and functions in an object:

var myRevealingModule = (function () {
 
        var privateCountVar = 0;
 
        function privateFunctionIncrement() {
            privateCountVar++;
        }
 
        function publicFunctionStart() {
           return privateFunctionIncrement();
        }
 
        
        function publicGetCount(){
          return privateCountVar;
        }
 
	function publicIncrement(){
	  return privateFunctionIncrement()
	}
 
       return {
            start: publicFunctionStart,
            increment: publicIncrement,
            count: publicGetCount
        };
 
    })();

If you run the code above you'll see that only the methods revealed in the return {...} are public see image below:

  return {
            start: publicFunctionStart,
            increment: publicIncrement,
            count: publicGetCount
        };

encapsulation revealing module pattern

Wrapping up

JavaScript is not an object oriented language, it is a functional language, but we can work around to have some of the goodies of the Object Oriented languages in JavaScript.

Those are some references for what in my opinion are two of the best JavaScript books I ever read (they are free):
http://speakingjs.com/es5/ 
http://addyosmani.com/resources/essentialjsdesignpatterns/book/

 

Thanks for reading 🙂

 

EcmaScript 6, four awesome features

One of the most important things for a Client Side Developer is to keep current on the technologies, because it is always evolving, not only the differents client-side frameworks, but also the JavaScript (EcmaScript) Language itself. The current version adopted by the majority of the browsers up to the moment is EcmaScript 5.

Although the ES6 is not supported a 100% by all the browsers (at least when this article was written) It is important to learn what is coming. Here is a table of compatibility http://kangax.github.io/compat-table/es6/

I was reading about EcmaScript 6 and its new features, and I decided to do some comparison of how we do things today with ES5 and how we can achieve the same things with ES6. I personally believe that the best way to learn new code is writing it, and the comparison may help you to understand ES6 better. It works for me 😉

I put together some code of how we could implement some code in ES5 and how it will be in ES6, I will try to keep it simple, also, this not necessarily mean that the proposed code in ES5 is the only equivalent, in JavaScript there is several ways to achieve the same.

ecmascript 6

Four awesome features in Ecmascript 6:

  • Spread Operators
  • Template strings
  • Arrow function
  • Block scope

 

book

Book Tip

Understanding ECMAScript 6: The Definitive Guide for JavaScript Developers
ECMAScript 6 represents the biggest update to the core of JavaScript in the history of the language. In Understanding ECMAScript 6, expert developer Nicholas C. Zakas provides a complete guide to the object types

Amazon

 

 

Spread Operators:

(from: http://www.2ality.com/2014/07/method-calls.html)
The spread operator (...) mostly replaces apply()
Making a direct method call via apply() only because you want to turn an array into arguments is clumsy, which is why ECMAScript 6 has the spread operator (...) for this. It provides this functionality even in despatched method calls.

e.g:

function add(a, b) {
	return a + b;
}

var nums = [5, 4];

console.log(add(...nums));//ES6
console.log(add.apply(this, nums));//ES5

let arr = [-1, 7, 2];
console.log(Math.max(...arr)); //ES6
console.log(Math.max.apply(this, arr)); //ES5

//Other examples of ES6
    console.log(new Date(...[2011, 12, 24])); //ES6

// Non-destructively concatenate single elements
    console.log( [...arr, 9, -6]); // [-1, 7, 2, 9, -6]//ES6

 

Template strings

Template strings let you interpolate arbitrary expressions into a string:
(learn more at: http://www.2ality.com/2011/09/quasi-literals.html)

e.g:

//ES6
let greetings = {text: 'Hello World'};
let tpl = `Greetings: ${greetings.text}.`;

console.log(tpl);

//ES5
var greetings1 = {text: 'Hello World'};
var tpl1 = "Greetings: {0}.".replace("{0}", greetings.text);

console.log(tpl1);

//-------------------------------------------------------------

//ES6
let text = `This is a text
    with
    multiple lines.`;
console.log(text);

//ES5
let text1 = "This is a text " +
    "with " +
    "multiple lines.";
console.log(text1);

 

Arrow functions

In EcmaScript 5 a function can be used as a subroutine or like a method

e.g:

var myObj = {
        myMethod: function () { //function used as method
           return function () { ... }; //function used as subroutine
        }
    }

The Arrow functions are intended to be used as subroutines in EcmaScript 6

e.g:

var myObj = {
        myMethod: function () { //function used as method
           return  () => { ... }; //function used as subroutine
        }
    }

These are other examples

let square = x => x * x;
var square_ES5 = function(x) { return x * x}

let add = (a, b) => a + b;
var add_ES5 = function(a, b){ return a + b;}

let pi = () => 3.1415;
var pi_ES5 = function(){ return 3.1415; }

console.log(square(5) + " ES6");
console.log(square_ES5(5) + " ES5");

console.log(add(3, 4) + " ES6");
console.log(add_ES5(3, 4) + " ES5");

console.log(pi() + " ES6");
console.log(pi_ES5() + " ES5");

Learn more about EcmaScript 6 Arrow functions here http://www.2ality.com/2012/04/arrow-functions.html

 

Block scope

EcmaScript 5 comes with a function-level scope for variables and functions, with EcmaScript 6 you can use “let” to block scope a variable, to learn more visit: http://ariya.ofilabs.com/2013/05/es6-and-block-scope.html

e.g

//ES5
function blockScope_ES5() {
 try {
 var y = 10; //block scope

 } catch (e) {
 //...
 }
 console.log(y);
}

blockScope_ES5();

//ES6
function blockScope() {

 try {
 let y = 10; //block scoped
 } catch (e) {
 //...
 }
 console.log(y);
}
blockScope();

//-----------------------------------------------

//ES5
function order_ES5(x, y) {
 if (x & gt; y) {
 var tmp = x; //block scope
 x = y;
 y = tmp;
 }
 console.log(tmp === x); // ReferenceError: tmp is not defined
 return [x, y];
}
order_ES5(9, 5);

//ES6
function order(x, y) {
 if (x & gt; y) {
 let tmp = x; //block scoped
 x = y;
 y = tmp;
 }
 console.log(tmp === x); // ReferenceError: tmp is not defined
 return [x, y];
}
order(9, 5);

You can try all this examples in http://www.es6fiddle.com/

Throw exceptions with line number in JavaScript

There might be some scenarios that we need to throw exceptions in JavaScript, and get the line number, and the call stack, specially when we are developing a feature that will be used by other developers. Since JavaScript have far less tools to aid in debugging than other languages, when we are building a functionality it is handy to throw an exception when the developer that is using you code need to meet certain requirements to let them know when have been a violation in the code in the logic.

throw exceptions

This is widely used when we use the network to do the communication and transmit the data with the back-end, and the connection fails and we want to show specifically where in the code the error happened (code line). Especially when the component you are developing takes thousand of code lines. Or when we want to force the consumed of our component to specify a specific type of object. Let's see the following example.

Throw exceptions example:

function someFunction(callback){
    if(typeof callback != ‘function’){
        // throw an exception here
    }else{
        callback();
    }
}

 

javascript book

Book Tip

Speaking JavaScript: An In-Depth Guide for Programmers
Like it or not, JavaScript is everywhere these days—from browser to server to mobile—and now you, too, need to learn the language or dive deeper than you have. This concise book guides you into and through JavaScript, written by a veteran programmer who once found himself in the same position.

Amazon

 

With this code we can achieve it:

var err;
try {
throw new Error('myError');
} catch (e) {
err = e;
}
if (!!err)
console.log(err.stack);

if you put this code in the console (chrome) this is the result:

Continue reading "Throw exceptions with line number in JavaScript"

Optimizing code using Object.defineProperty instead of $scope for $watch in AngularJs

It is all about performance

No long ago I wrote an article about “KnockoutJs computed equivalent in AngularJs”. In that article I pointed that the Angular equivalent of a KnockoutJs computer is the $scope.$watch() service. angularjs performance defineProperty

With the pass of the time, I discovered that using $watch in angular can affect the performance of the application, so I was wondering if there is an alternative to $watch to improve the performance of an application specially if it is a large application...

The answer is yes, there is an alternative to $watch.
Note:
It is using Object.defineProperty(), when you planning to use defineProperty, you have to keep in maind that it is supported only by Internet Explorer 9 and above.

First thing first:

To achieve this we will need to use the "controller As" syntax instead of injecting the $scope.
Although The "Controller As" syntax is basically your controller published to the $scope (this syntax is supported by Angular 1.2 and above), here are some reasons to use the "Controller As" syntax over the $scope syntax:

(from John Papa Angular style guide):

Use the controllerAs syntax over the classic controller with $scope syntax.

Why?: Controllers are constructed, "newed" up, and provide a single new instance, and the controllerAs syntax is closer to that of a JavaScript constructor than the classic $scope syntax.

Why?: It promotes the use of binding to a "dotted" object in the View (e.g. customer.name instead of name), which is more contextual, easier to read, and avoids any reference issues that may occur without "dotting".

Why?: Helps avoid using $parent calls in Views with nested controllers.

<!-- avoid -->


<div ng-controller="Customer">
    {{ name }}
</div>


<!-- recommended -->


<div ng-controller="Customer as customer">
    {{ customer.name }}
</div>


 

book

Book Tip

ng-book - The Complete Book on AngularJS
Ready to master AngularJS? What if you could master the entire framework – with solid foundations – in less time without beating your head against a wall?


Amazon

 

Using defineProperty instead of the angular $watch service, to watch a property.

In general, when we going to need to use a $watch?
A: Whenever we need to subscribe to and object and observe when the value change and trigger an action as a response to that change.

Advise: In general, using $watch in controllers is something to be avoided whenever possible.

Here is a simple example of how to implement defineProperty:

Object.defineProperty(myController.prototype,
    'controllerPropertyName', {
    get: function () {
        return this._personName;
    },
    set: function (newValue) {
        this._personName = newValue;
        //Call method on update here
    },
    enumerable: true,
    configurable: true
});
}

To make this works in angular we will need to wrap the defineProperty within a service:

var myApp = angular.module('myApp', []);
myApp.service('efficientWatch', efficientWatch);

function efficientWatch() {
    this.watch = function (name, controllerProto, func) {
        Object.defineProperty(controllerProto,
        name, {
            get: function () {

                return this._personName;
            },
            set: function (newValue) {
                this._personName = newValue;

                //Call method on update
                if (typeof func == 'function') func(newValue);

            },
            enumerable: true,
            configurable: true
        });
    };
};

You can see the code working together here.
http://jsfiddle.net/ks5et82p/176/

Installing Protractor with npm in windows environment behind a proxy

Installing Protractor npm windows environment behind proxy
In this post we going to assume that you know what is Node, npm, etc so we don't going to explain this.

Installing Protractor npm windows environment behind proxy

First we need to install or update NodeJs (npm comes with node now), you can click here to get the latest version.

We need to setup the npm to work behind a proxy so we can run protractor:

Run this commands in a console, for http and https

npm config set proxy http://proxy.company.com:8080
npm config set https-proxy http://proxy.company.com:8080

 

If you have to set username and password:

http://username:password@proxy.company.com:8080

if your password have an @ then surround it in quotes

http://"username:your@password"@proxy.company.com:8080

To reset proxy for npm:

npm config rm proxy
npm config rm https-proxy

To get the proxy settings for npm:

npm config get proxy
npm config get https-proxy

Quick notes to Setup Protractor

Use npm to install Protractor globally with:

npm install -g protractor

This will install two command line tools, protractor and
webdriver-manager. Try running
protractor --version to make sure it's working.

The webdriver-manager is a helper tool to easily get an
instance of a Selenium Server running. Use it to download the necessary
binaries with:

webdriver-manager update

Now start up a server with:

webdriver-manager start

This will start up a Selenium Server and will output a bunch of info
logs. Your Protractor test will send requests to this server to control
a local browser.

 

Configuration

Create a file called protractor-conf.js in the test directory and add the following configuration to it.

The Selenium webdriver has the ability to execute tests against multiple browsers concurrently, making cross-browser testing easy. Protractor has a sample config file available with all the configuration options.

If you installed Protractor locally, be sure to set the seleniumServerJar and chromeDriver options with the location of these files.

exports.config = {
// location of the Selenium JAR file and chromedriver, use these if you installed protractor locally
// seleniumServerJar: '../node_modules/protractor/selenium/selenium-server-standalone-2.40.0.jar',
// chromeDriver: '../node_modules/protractor/selenium/chromedriver',// location of your E2E test specs

specs: [
  '../test/e2e/*.js'
],// configure multiple browsers to run tests
multiCapabilities: [{
'browserName': 'firefox'
}, {
'browserName': 'chrome'
}],// or configure a single browser

/*
  capabilities: {
   'browserName': 'chrome'
 }
  */
// url where your app is running, relative URLs are prepending with this URL
baseUrl: 'http://localhost:9000/',


// testing framework, jasmine is the default</i>
framework: 'jasmine'
};

Notice that the baseUrl does not determine the location of your app. It just determines relative URLs. If you call browser.get(‘/’) in your Protractor tests, this will redirect to your baseUrl.

Hope this was helpful 😉

How to get the div coordinates with JQuery?

How to get the div coordinates with JQuery and vanilla Javascript?

 
This is specially helpful if you are creating a mouse over porpup, or a custom tooltip and you have to account for the position of you div in the screen or maybe related to other elements, to avoid overlap visibility over other elements in the page, etc.
div coordinates

There are two ways of doing this, with .position() method and .offset() method

$('#elementID').offset()

Returns an object with top and left offsets. (http://api.jquery.com/offset/)

Actually there is two options:
position() or offset().

position() Basically similar to what you could use in the CSS top, left properties.

offset() Will return the distance relative to the document. This considers margins, paddings, and borders.

 

book

Book Tip

Speaking JavaScript: An In-Depth Guide for Programmers
Like it or not, JavaScript is everywhere these days—from browser to server to mobile—and now you, too, need to learn the language or dive deeper than you have. This concise book guides you into and through JavaScript, written by a veteran programmer who once found himself in the same position.

Amazon

 

Here is an example:

<style>
  .someClass{
        position: absolute;
        top:100px;
        left:100px;
        border: solid 3px black;
  }
  span {
     margin:20px;
     padding:20px;
     border: solid 2px black;
     position: absolute;
     top:20px;
     left:20px;
 }
</style>
<divclass="someClass"><span>Hello World!</span></div>
    $('span').position() => { top: 20, left: 20 }
    $('span').offset() => { top: 143, left : 143 }

You can also set the position() and the offset

<divclass="someClass"><span>Hello World!</span></div>
    $('span').position({ top: 20, left: 20 })
    $('span').offset({ top: 143, left : 143 })
 

 

How to achieve the same result with vanilla Javascript?

This function will tell you the div coordinates, (x,y position) of the element relative to the page. Basically you have to loop up through all the element's parents and add their offsets together.

function getPosition(elem) {
    for (var lx=0, ly=0;
         elem != null;
         lx += elem.offsetLeft, ly += elem.offsetTop, elem = elem.offsetParent);
    return {x: lx,y: ly};
}

If you just wanted the x,y position of the element relative to its container, then all you need is:

var x = elem.offsetLeft;
var y = elem.offsetTop;

If you know other way to achieve the same result please feel free to share with us, you can live a comment in the blog or you can contact me @JoMendezdev on Twitter.