Category: JavaScript

Styling External Links in your site with CSS

Are you looking for an easy way to style and denote external links in your web site or blog, it is always good for the user to know when they are going to navigate away from your page, enriching the user experience. Perhaps most of the sites out there achieve this by placing code on the Back End. Here I going to share with you what I found on this topic, and how to do it just using CSS.

Clicking on external links, navigating away..

denote external links

We are going to use CSS selector to apply styles to all the “a” (anchors) except for internal links. This is translated into code like this:

a[href*="//"]:not([href*="mywebsite.com"]) {
    /* css code here  */
}

 

Notice that we combined the selector with some regular expression, the * mean select all elements, for a full list of selectors, you can visit:
http://www.w3schools.com/cssref/css_selectors.asp

Now, you can combine this selector with the ::after of the <a> element to include for example an icon that might looks like the externals links on Wikipedia.
(from http://www.w3schools.com/)
after browser suport

Although Wikipedia doesn’t use this approach, they use a class instead to insert the icon at the end of the external links, this should be done manually. With the method exposed here all the externals links will be styled automatically when the page loads.
external links wikipedia

 

book

Book Tip

CSS Mastery
Fully updated to the latest CSS modules, make the journey to CSS mastery as simple and painless as possible. This book dives into advanced aspects of CSS-based design, such as responsive design, modular CSS, and CSS typography. Through a series of easy-to-follow tutorials, you will learn practical CSS techniques you can immediately start using in your daily work.
Amazon

 

Here is a working example of how all the external links are decorated with the Wikipedia’s external link icon

a[href*="//"]:not([href*="example.com"]):after {
    margin-left: 3px;
    content: url(data:image/svg+xml,%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%20standalone%3D%22no%22%3F%3E%3Csvg%20xmlns%3D%22
http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2212%22%20height%3D%2212%22%3E%3Cpath%20fill%3D%22%23fff%22%20stroke%3D%22%2306c%22%20d%3D%22M1.5
%204.518h5.982V10.5H1.5z%22%2F%3E%3Cpath%20d%3D%22M5.765%201H11v5.39L9.427%207.937l-1.31-1.31L5.393%209.35l-2.69-2.688%202.81-2.808L4.2%202.544z%22
%20fill%3D%22%2306f%22%2F%3E%3Cpath%20d%3D%22M9.995%202.004l.022%204.885L8.2%205.07%205.32%207.95%204.09%206.723l2.882-2.88-1.85-1.852z%22%20fill%3D
%22%23fff%22%2F%3E%3C%2Fsvg%3E)
    }

Also you can denotate all the links that navigate away from your page even internal links that get open in another tab or windows:

:not compatibility

One last thing to keep in mind when you use this approach is the browser compatibility with the :not css selector, for example Internet Explorer starting supporting it from version 9:
(from http://www.w3schools.com)
not css selector browser compatibility

Ultimately, for the no compatible browsers you can detect the browser version with JavaScript or Jquery and then select all the external links and apply the style using JavaScript code:
Jquery Example:

$(function() {
  $('a').each(function(i, e) {
    if ($(e).attr("href") && ($(e).attr("href").indexOf("http://") > -1 || $(e).attr("href").indexOf("https://") > -1)) {
      $(e).css({
        "background-image": "linear-gradient(transparent,transparent),url(data:image/svg+xml,%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%20standalone%3D%22no%22%3F%3E%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2212%22%20height%3D%2212%22%3E%3Cpath%20fill%3D%22%23fff%22%20stroke%3D%22%2306c%22%20d%3D%22M1.5%204.518h5.982V10.5H1.5z%22%2F%3E%3Cpath%20d%3D%22M5.765%201H11v5.39L9.427%207.937l-1.31-1.31L5.393%209.35l-2.69-2.688%202.81-2.808L4.2%202.544z%22%20fill%3D%22%2306f%22%2F%3E%3Cpath%20d%3D%22M9.995%202.004l.022%204.885L8.2%205.07%205.32%207.95%204.09%206.723l2.882-2.88-1.85-1.852z%22%20fill%3D%22%23fff%22%2F%3E%3C%2Fsvg%3E)",
        "background-repeat": "no-repeat",
        "padding-right": "13px"
      });
    }
  });
});

 

Working example:

CSS Tooltip, without JavaScript or Jquery

In this article I’m going to explore how to Create css tooltip, without using JavaScript or JQuery plugins.

css tooltip

Tooltips

Tooltips are great artifact to complement/enrich the user experience providing hint and more information to the user. There are a lots of JavaScript plugins that provides this functionality, but if you don’t feel like adding that weight to your site, adding more files and more JavaScript code, we can take care of it just using plain CSS.
As an alternative we can use the HTML title attribute to effectively accomplish the same solution, but you can’t style the tooltip to your liking.
Sometimes I prefer to use CSS alternatives to common JavaScript interactions when I’m developing specially when I’m developing prototypes. There are some projects where downloading a plugin or creating a new file for a few lines of code seems like overkill.

Here is a working example:

Hover over this

 

Creating a Css Tooltip

To create our tooltip just using css, we are going to take advantage of the ::before and ::after selector, we are going to use the ::before for the tooltip body and the ::after for the littler arrow. We are going to set the Tooltip content with data-tooltip parameter of the html element.

 <span class="tooltip-toggle" data-tooltip="Sample text for your tooltip!">
     Hover over this
 </span>

 

book

Book Tip

CSS Mastery
Fully updated to the latest CSS modules, make the journey to CSS mastery as simple and painless as possible. This book dives into advanced aspects of CSS-based design, such as responsive design, modular CSS, and CSS typography.

Amazon

 

 

Definition and Usage.

::after selector inserts something after the content of each selected element(s).
You can use the content property to specify the content to insert. This property can be combined with the attr() attribute to get the text from an html atribute.
::before selector inserts something before the content.
Example:

.tooltip-toggle::before {
  position: absolute;
  top: -80px;
  left: -80px;
  background-color: green;
  border-radius: 5px;
  color: #fff;
  content: attr(data-tooltip);
  padding: 1rem;
  text-transform: none;
  -webkit-transition: all 0.5s ease;
  transition: all 0.5s ease;
  width: 160px;

.tooltip-toggle::after {
  position: absolute;
  top: -12px;
  left: 9px;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-top: 5px solid green;
  content: " ";
  font-size: 0;
  line-height: 0;
  margin-left: -5px;
  width: 0;
}
}

With the :hover we can show/hide the tooltip as a transition:

.tooltip-toggle:hover::before,
.tooltip-toggle:hover::after {
  opacity: 1;
  -webkit-transition: all 0.75s ease;
  transition: all 0.75s ease;
}

.tooltip-toggle::before,
.tooltip-toggle::after {
  color: #efefef;
  font-family: monospace;
  font-size: 16px;
  opacity: 0;
  pointer-events: none;
  text-align: center;
}

Here is the full code example of the css tooltip:

Interview Question

You can also use this article as reference to create css interview questions for a seasoned front-end developer, to validate the deep experience on using, formating the ::before and ::after elements.

Arrays as Multipurpose Data Structures in JavaScript

In JavaScript the Array object is a very powerful data structure with it you can “simulate” other data structures, like Queues, Stacks, List, etc.

There is a list with some of the most important methods of the array object in JavaScript, we going to use them to create/simulate our data structures, you can see example of these methods in action, below.

Array.push(value1, value2, value3,…) – Add one or more Elements to the end of the array. This method will return the new length of it. You can specify multiple comma separated values.
Array.pop() – Removes the last element from an array and returns it.
Array.unshift(value1, value2, value3,…) – Add one or more elements to the beginning of the array. This method will return the new array length. You can specify multiple comma separated values.
Array.shift() – Removes the first element from an array and returns it.
Array.splice(splice(start, deleteCount[, item1[, item2[, …]]])) – The splice() method changes the content of an array by removing existing elements and/or adding new elements.

Data Structures array

Other useful methods.

We are not going to use this methods to create the data structures showed in this post, but it might be handy.

Array.reverse() – Reverses the order by position (the first element becomes the last and the last one becomes the first, etc).

var arr = ['a', 'b', 'c'];
arr.reverse();
console.log(arr); //this will display ["c", "b", "a"]

Array.sort([compareFunction]) – Allows you to sort an array by specifying a compare function which has access to each value in the array you want to sort.

var arr = ['d', 'e', 'b', 'c', 'a'];
arr.sort(function(a, b){
  if (a < b) { return -1; } if (a > b){ return 1; }
  // a must be equal to b
  return 0;
});
console.log(arr); //this will display ["a", "b", "c", "d", "e"]
//Note: for this simple sort you can do arr.sort(), an you'll obtain the same result.

Array.join(separator) – This method takes one or more items in the array and returns a string of values joined by their separator. If you don’t specify a separator, the default is a comma.

var arr = ['a', 'b', 'c'];
var str = arr.join('-');
console.log(str); //this will display "c-b-a"

Array.indexOf(value) – This method allows you to find the first occurrence of the specified value, or –1 if not found.

var arr = ['a', 'b', 'c'];
if(arr.indexOf("a") > -1)
console.log('found "a" in arr');

 

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

 

 

Data Structures

  • Arrays used as Queue

  • Arrays used as Stack

  • Arrays used as List

 

Arrays as Queue:

A queue follows the First-In First-Out (FIFO) paradigm: the first item added will be the first item removed. An array can be turned into a queue by using the push() and shift() methods. push() inserts the passed argument at the end of the array, and shift() removes and returns the first item, consider the following example:

function Queue(length) {
    var ret = [];

    ret.enqueue = function(a) {
        if(ret.length == length){
             ret.shift();
        }
        return Array.prototype.push.apply(this, arguments);
    };
    ret.dequeue = function(){
        return Array.prototype.shift.apply(this);
    }
    return ret;
}

var aux = Queue(3);
aux.enqueue('cat');
aux.enqueue('dog');
aux.enqueue('duc');
aux.enqueue('worm');
console.log(aux); // should contain dog, duc, worm
aux.dequeue();
console.log(aux);

Arrays used as Stack.

A stack follows the Last-In First-Out (LIFO) paradigm: an item added last will be removed first. The Array class has 2 methods that provide stack functionality. they are push() and pop(). push() appends an item to the end of the array, and pop() removes and returns the last item in the array
push(data) adds data.

pop() removes the most recently added data.

function Stack() {
    var ret = [];

    ret.push = function(a) {
        return Array.prototype.push.apply(this, arguments);
    };
    
    ret.pop = function(){
        return Array.prototype.pop.apply(this);
    }

    return ret;
}

var stack= Stack();
stack.push("A");
stack.push("B");
stack.push("C");
console.log(stack);
stack.pop();
console.log(stack);

Arrays used as List.

A List a collection of unsorted elements, where you can add or remove elements.

function List() {
    var ret = [];
    ret.add = function(element) {
        return Array.prototype.push.apply(this, arguments);
    };
    ret.remove = function(element){
        return Array.prototype.slice.apply(this, ret.splice(ret.indexOf(element), 1));
    }
    return ret;
}

var aux = List();
aux.add('cat');
aux.add('dog');
aux.add('duc');
aux.add('worm');
console.log(aux); 
aux.remove('dog');
console.log(aux);

Wrapping up:

As you can see the those three data structures queue, stack and list are simple arrays wrapped in a function to rename the methods used to add or remove elements from the collections with more semantic names. If you have any enhancement or any subjection please don’t hesitate to share with us.

References to learn more:

developer.mozilla.org – Arrays

Closure in JavaScript through examples

javascript closureWhat is Closure?

A Closure is a named or anonymous function defined within the context of an object or any other function, which preserves and access to the context where it was declared.

To understand closure, it requires you to be familiar with basic JavaScript concepts, such as scope of variables and functions.

A closure is a named or anonymous function:
javascript closure
This is not a closure:

//Named function
function greetings() { //this is not a closure function.
    return ‘Howdy’;
}

//anonimous function
var greetings2 = function () { //this is not a closure function.
    return ‘Hello’;
}

greetings(); //Shows Howdy.
greetings2(); //Shows Hello.

Basically a closure function is a function that can access to the variables declared in the outer context, including global variables.

 

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

 

Closures in action.

Here is an example that will help you recognize when you need to use a Closure.

How to do it correctly.

Suppose you want to use a variable to count and want to create a function to increment the count variable.

var counter = 0;
function increase() {
    counter += 1;  // increment its current value.
    console.log(counter);
}

increase();
increase();
increase();

 // The counter is now equal to 3.

Here we have a solution, but has flaws; the counter variable is global, any script on the page would have access to it and could change it without calling the increase function .

We need to make sure that the counter variable is only modified by the increase function.

Therefore, move the definition of the variable inside the function, so no one can modify it without calling the function increase:

function increase() {
    var counter = 0;
    counter += 1; // increment its current value.
    console.log(counter);
}

increase();
increase();
increase();

// We expect the value of the count variable is 3, but it will be 1.

Now the counter variable is not accessible from the outside (now is protected), but this wong work properly because every time you call the function it will define the variable account.

We need to create an internal function to solve this:

var increase = (function() {
    var counter = 0;
    return function () {
        return counter += 1;
    }
 console.log(counter);
})(); //* IIFE Auto-invoked function.

increase();
increase();
increase();

// The counter is now equal to 3.

*IIFE Immediately Invoked Function Expression (see Encapsulation in JavaScript).

A common mistake

Here’s an example of misuse of Closure function. Suppose we have the following code:

function count() {
     var i;
     for (i = 1; i <= 3; i ++) {
         setTimeout (function () {
             console.log ('The count value is '+ i);
         }, 1000); // 1000 milliseconds = 1 second
     }
}
count();

And this is how you can solve it:

function count() {
     var i;
     function display(j) {
         return function () {
             console.log ('The counter value is ' + j);
         }
     };

     for (i = 1; i <= 3; i ++) {
         setTimeout (display(i), 1000);
     }

}
count();

I’m not going to explain in detail how this is solved, I’ll leave it to you, if you understand what happened then you understand JavaScript closure. 😉

Other references:

https://developer.mozilla.org/es/docs/Web/JavaScript/Closures
http://javascriptissexy.com/understand-javascript-closures-with-ease/
http://www.w3schools.com/js/js_function_closures.asp

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 &gt;= 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 😉