Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

May 12, 2015

JavaScript variable scopes

In this post, we will learn JavaScript’s variable scope and hoisting and all the idiosyncrasies of both.
We must understand how variable scope and variable hoisting work in JavaScript, if want to understand JavaScript well. These concepts may seem straightforward; they are not. Some important subtleties exist that we must understand, if we want to thrive and excel as JavaScript developers.

Variable Scope
A variable’s scope is the context in which the variable exists. The scope specifies from where you can access a variable and whether you have access to the variable in that context.

Variables have either a local scope or a global scope.

Object Oriented JavaScript

Guys, do you all know that Javascript is the world’s most misunderstood programming language. Despite its popularity, few know that JavaScript is a very nice dynamic object-oriented general-purpose programming language. How can this be a secret? Why is this language so misunderstood? Lets see!!
Object-oriented programming is a programming paradigm that uses abstraction to create models based on the real world. It uses several techniques from previously established paradigms, including modularity, polymorphism, and encapsulation. In the past, it was a common argument that JavaScript was a basic language and was very ‘slap dash’ with no real foundation; this is no longer the case.

JavaScript can have all that an Object-Orientated language has to offer. It follows all the principles of object oriented programming – Inheritance, Encapsulation, Abstraction and Polymorphism. In OOP, few terminologies are usually followed:

1. Class
Defines the characteristics of the Object.
e.g:
1. //Person Class
2. function Person() { }
Wasn’t that simple??
Another way of defining class is
1. var Person = function () { };

2. Object
An Instance of a Class.
e.g:
1. var person1 = new
Person();
2. var person2 = new
Person();
Here person1 and person2 are instances of class Person.

3. Property
An Object characteristic, such as gender, color, type etc.
e.g:
1. function Person(gender) {
2. this.gender = gender;
3. };
4. var person1 = new Person('Male');
5. //display the person1 gender
6. alert('person1 is a ' + person1.gender); // person1 is a
Male

4. Method
An Object capability, such as walk.
e.g.:
1. function Person(gender) {
2. this.gender = gender;
3. //method
4. this.getGender = function() {
5. return this.gender();
6. }
7. };

5. Constructor
A method called at the moment of instantiation (the moment when the object instance is created). The constructor is a method of the class. In JavaScript, the function serves as the constructor of the object; therefore, there is no need to explicitly define a constructor method.
6. Inheritance
Inheritance is a way to create a class as a specialized version of one or more classes (JavaScript only supports single class inheritance). The specialized class is commonly called the child, and the other class is commonly called the parent. In JavaScript you do this by assigning an instance of the parent class to the child class, and then specializing it. In modern browsers you can also use Object.create to implement inheritance.
In the example below, we define the class Studentas a child class of Person. Then we redefine the sayHello() method and add the sayGoodBye() method.
1. // define the Person Class
2. function Person() {}
3. Person.prototype.walk = function() {
4. alert ('I am walking!');
5. };
6. Person.prototype.sayHello = function() {
7. alert ('hello');
8. };
9. // define the Student class
10. function Student() {
11. // Call the parent constructor
12. Person.call(this);
13. }
14. // inherit Person
15. Student.prototype = new Person();
16. // correct the constructor pointer because it points to
Person
17. Student.prototype.constructor = Student;
18. // replace the sayHello method
19. Student.prototype.sayHello = function() {
20. alert('hi, I am a student');
21. }
22. // add sayGoodBye method
23. Student.prototype.sayGoodBye = function() {
24. alert('goodBye');
25. }
26. var student1 = new Student();
27. student1.sayHello();
28. student1.walk();
29. student1.sayGoodBye();
30. // check inheritance
31. alert(student1 instanceof Person); // true
32. alert(student1 instanceof Student); // true

Using Object.create the inheritance line would instead be:
1. Student.prototype = Object.create(Person.prototype);

7. Encapsulation
A Class defines only the characteristics of the Object, a method defines only how the method executes. In the previous example, Student does not need to know how the Person class’s walk() method is implemented, but still can use that method; the Student class doesn’t need to explicitly define that method unless we want to change it. This is called encapsulation, by which every class inherits the methods of its parent and only needs to define things it wishes to change.

8. Abstraction
Abstraction is a mechanism that permits modeling the current part of the working problem. This can be achieved by inheritance (specialization), or composition. JavaScript achieves specialization by inheritance, and composition by letting instances of classes be the values of attributes of other objects.
The JavaScript Function class inherits from the Object class (this demonstrates specialization of the model) and the Function.prototype property is an instance of Object (this demonstrates composition).
1. var foo = function(){};
2. alert( 'foo is a Function: ' + (foo instanceof Function) );
3. alert( 'foo.prototype is an Object: ' + (foo.prototype instanceof Object)
);

9. Polymorphism

Just like all methods and properties are defined inside the prototype property, different classes can define methods with the same name; methods are scoped to the class in which they’re defined. This is only true when the two classes do not hold a parent-child relation (when one does not inherit from the other in a chain of inheritance).

May 1, 2015

Javascript: Closures and Lexical Scoping

This article is going to focus on a piece of the java-script language that I had trouble understanding, and may be a point of confusion for you. Today I’ll be looking at closures and lexical scoping. Last time, I mentioned that Javascript has more in common with functional languages, than classical languages. Today will be no different as closures and lexical scoping are two more features that come from the functional programming ancestry that Javascript has.

What’s a closure?

To understand what closure is you first need to understand stack-frames. In PHP a stack-frame is created each time a function is called.

function sayHello($name) {
$return = 'Hey there'.$name;
return $return;
}
sayHello('Peter') // echos 'Hey there Peter'.


The above function when run will create a stack-frame for itself, and $return will exist and be available inside that stack-frame. Once sayHello() is done $return vanishes into the garbage collector, and is gone until the next time sayHello() is invoked. However, in Javascript we are able to declare inner and anonymous functions. These functions are enclosed by their containing function and are said to form a closure. A simple example of a closure is

function sayHello(name) {
var phrase = 'Hey there' + name;
var sayHi = function() {
alert(phrase);
};
return sayHi;
}
var talk = sayHello('Peter');
talk(); // alerts 'Hey there Peter'

In Javascript functions still create stack-frames however, inner functions have access to any of the containing functions local variables. So a closure is a stack-frame that doesn’t go away after a function is complete. In the above Javascript sayHi is an inner function of sayHello. As we saw when we executed talk() it still had access to the name variable of its containing function. You create a closure in Javascript each time you put a function inside another function. Closures in Javascript preserve all the local variables that existed in the function when it completed. This phenomenon of local variable preservation is referred to as Lexical Scoping.
Ok, so what?

So by creating closures we can do a number of things. First off we can create visibility, something that many people seem to think Javascript lacks. The following example illustrates this.

function Beer(type) {
this.type = type;
var volume = 0.5;
var lessBeer = function() {
volume = volume - 0.5;
};
this.drink = function() {
if (volume === 0) {
console.log('no more beer :(');
return;
}
lessBeer();
console.log('mmm beer.');
};
};
var stout = new Beer('stout');
console.log(stout.type); // prints 'stout'
stout.drink(); // prints mmm beer
stout.drink(); // prints no more beer :(
stout.volume = 10; // trying to top up doesn't work!
stout.drink(); // prints no more beer :(
stout.lessBeer() // TypeError? must be private

If you run the above code in your favorite Javascript console You should get the results in the comments. What this illustrates is that you cannot fill a beer back up, and that by using closures you can create private variables and functions that cannot be accessed from outside the object. jQuery leverages closures extensively.
More on lexical scoping


Lexical scoping is a fancy term that refers to a function remembering and preserving its state between and after executions. However, lexical scoping in Javascript is not truly static, as the wikipedia may lead you to believe. A simple example of lexical scoping is

var count = 5;
function tellCount() {
console.log(count);
};
tellCount(); // prints 5
count = 7;
tellCount(); // prints 7;

This shows how the local variables in a scope are preserved but the values will always reflect the most current values. While count is contained inside the closure created by tellCount() it updates to reflect the current value in the top most scope, which in this case is window. This trick is useful and infuriating at times. If you’ve ever tried defining functions in a loop you’ve probably been dismayed to find out all the functions always reflect the last value in the loop.

So loops and lexical scoping will eventually cause you some grief. The quickest way to achieve this grief is by defining functions in a loop. Lets say you want to loop over an array and make links that say their value, seems easy right? Well until our good friend lexical scope shows up and drinks all the programatic beer. Take the following example.

var numbers = [ 1, 2, 3, 4, 5 ];
for ( var i in numbers) {
var num = numbers[i];
var anchor = document.createElement('A');
anchor.setAttribute('href', '#');
anchor.appendChild(document.createTextNode(num));
document.body.appendChild(anchor);
anchor.addEventListener('click', function(event) {
alert('My number is ' + num);
event.preventDefault();
}, false);
}

If you run this in firebug’s console you’ll get five links, that have click events on them. However, each link will say ‘My number is 5’, all because of lexical scoping. The event listener uses a closure to refer to num however, it doesn’t maintain the value of num from when the function was declared but instead maintains the last know value of num. Which just happens to be 5. Now most javascript libraries give you a good work around by allowing apply events to collections of elements. jQuery has $.each(), and its $.bind() and friends. Mootools has a similar construct in Element.addEvent. However, if you need a loop variable inside an event one way to do it is to do the following:

var numbers = [ 1, 2, 3, 4, 5 ];
for ( var i in numbers) {
var num = numbers[i];
var anchor = document.createElement('A');
anchor.setAttribute('href', '#');
anchor.appendChild(document.createTextNode(num));
document.body.appendChild(anchor);
var clicker = function(number) {
return function(event) {
event.preventDefault();
console.log('My number is ' + number);
};
};
anchor.addEventListener('click', clicker(num), false);
}

Because the scope container in javascript is a function, you need to use additional functions to bind variables to different scopes. In the above example we use the function clicker to make a closure that contains the correct value for num which becomes number in the closure.

So that’s all for today. Lexical scoping and closures can be a tricky subject to grasp but once you do, they are a powerful feature of the language that you will wonder how you lived without.

JavaScript coding guidelines

1. Use === Instead of ==
JavaScript utilizes two different kinds of equality operators: === | !== and == | != It is considered best practice to always use the former set when comparing. However, when working with == and !=, you’ll run into issues when
working with different types. In these cases, they’ll try to coerce the values, unsuccessfully.

2. Eval = Evil
For those unfamiliar, the “eval” function gives us access to JavaScript’s compiler. Essentially, we can execute a string’s result by passing it as a parameter of “eval”.
                      eval("alert('Hi!')");
There are a couple reasons why the eval function should be avoided. First, it is significantly slower than design time code. Second, it is a security risk. When code is acquired and executed at runtime, it opens a potential threat vector for malicious programmers to exploit.

3. Always comment your code.

4. Use Explicit Blocks
Avoid writing statements without curly braces.
Bad example:
1. if(someVariableExists)
2. x = false
Good example:
1. if(someVariableExists) {
2. x = false;
3. }
With braces statements are more readable.

5. Variable naming
When declaring variables or functions always use camelCase
1. var userId;
2. var slidingPanel;
3. var wrappingElement = function ()
{};

When declaring constructors always use Pascal case
1. function Car(make, model, year) {
2. this.make = make;
3. this.model = model;
4. this.year = year;
5. }
6. var myCar = new Car("Eagle", "Talon TSi", 1993);

Use all upper case when you are defining any constant
1. var PAGE_SIZE = 10;

6. Long List of Variables? Omit the “Var” Keyword and Use Commas Instead.
Bad example:
1. var someItem = 'some string';
2. var anotherItem = 'another string';
3. var oneMoreItem = 'one more string';
Good example:
1. var someItem = 'some string',
2. anotherItem = 'another string',
3. oneMoreItem = 'one more string';

7. Do not create any object using new Object or new Array etc. Instead use literal syntax.
1. var obj = {},
2. arr = [],
3. str = "";

8. Always use semicolon.
Technically, Javascript allows us to get away with omitting semi-colons. But this may lead to issues that can be harder to find.

9. Try to have at max one global variable and use it as your namespace. For example:
1. App: {
2. name: "My App",
3. .
4. .
5. .
6. other properties,
7. init: function () {
8. //Initializations
9. },
10. start: function () {
11. //Start App
12. }
13. }

10. Use decimals cautiously
In javascript, 0.1 + 0.2 comes out to be something like 0.30000000000000004. The reason for this is because
JavaScript uses Binary Floating Point numbers. To get around this issue, you can multiply your numbers to remove the decimal portion. For instance, if you were to be adding up the cost of two items, you could multiply each price by 100 and then divide the sum by 100. Here is an example:
1. var hamburger = 8.20;
2. var fries = 2.10;
3. var total = hamburger + fries;
4. console.log(total); //Outputs 10.299999999999999
5. hamburger = hamburger * 100;
6. fries = fries * 100;
7. total = hamburger + fries;
8. total = total / 100;
9. console.log(total); //Outputs 10.3

11. Start Blocks on the Same Line
Most developers that write software in other C-family programming languages use the Allman style of formatting for block quotes.
Bad example:
1. if(myState === 'testing')
2. {
3. console.log('You are in testing');
4. }
5. else
6. {
7. console.log('You are in
production');
8. }
This will work most of the time. However, JavaScript is designed in such a way that following the K&R style of formatting for blocks is a better idea. This format starts the opening curly brace on the same line as the preceding line of code. It looks like this:
Good example:
1. if(myState === 'testing') {
2. console.log('You are in testing');
3. } else {
4. console.log('You are in
production');
5. }
While this may only seem like a stylistic difference, there can be times when there is a impact on your code if you use the Allman style. One fairly serious issue with this is on return statements. Let’s look at an example:
Bad example:
1. return
2. {
3. age: 15,
4. name:Jon
5. }
We would assume that the object would be returned but instead the return value will be undefined. The reason for this is because the browser has inserted a semicolon after the word return, assuming that one is missing.
Good example:
1. return {
2. age: 15,
3. name:Jon
4. }

12. Be Careful Using typeof
Normally, typeof returns the string representation of the value type (‘number’, ‘string’, etc.) The problem comes in when evaluating NaN (‘number’), null (‘object’), and other odd cases. For example, here are a couple of comparisons that might be unexpected:
1. var i = 10;
2. i = i - 'taxi'; //Here i becomes NaN
3. if (typeof(i) === 'number') {
4. console.log('i is a number');
5. } else {
6. console.log('You subtracted a bad value from
i');
7. }
The resulting alert message would be “i is a number”, even though clearly it is NaN (or “Not a Number”). To avoid this what you can do is check if ‘i’ is valid as shown here:
1. if (i && typeof(i) === 'number') {
2. console.log('i is a number');
3. } else {
4. console.log('You subtracted a bad value from
i');
5. }

13. Always pass radix parameter to parseInt
1. parseInt("56"); //Returns 56
2. parseInt("Joe"); //ReturnsNaN
3. parseInt("Joe56"); //ReturnsNaN
4. parseInt("56Joe"); //Returns 56
5. parseInt("21.95"); //Returns 21
parseInt returns all of the number characters it finds until it hits a non-numeric character.
1. parseInt("08"); //Returns 8 - used to return 0 (base 8)
2. parseInt("0x12"); //Returns 18 - assumes hexadecimal
3. parseInt("12", 16); //Returns 18, since base 16 is specified

The second pitfall is in the interpretation of the number.
a. A string with a leading zero was determined to be a number in octal format. Ecmascript 5 removed this functionality. Now most numbers will default to base 10.
b. The one exception is a string that starts with “0x”. This type of string will be assumed to be a hexadecimal number (base 16).
NOTE: We can also use + operator to parse a string number to a number. Example:
1. +"142" returns 142
2. +"142.854" returns
142.854

14. Avoid Reserved / Special Words

15. Types available in JS
a. Numbers
b. Strings
c. Booleans
d. Functions
e. Objects
f. undefined

16. + Operator
The + operator also does string concatenation:
1. "hello" + " world" returns "hello world"
If you add a string to a number (or other value) everything is converted in to a string first.
1. "3" + 4 + 5 returns"345"
2. 3 + 4 + "5" returns "75"

17. Use JSON
When storing data structures as plain text or sending/retrieving data structures via Ajax, use JSON instead of XMLwhen possible. JSON (JavaScript Object Notation) is a more compact and efficient data format, and is language neutral.
JSON is an intrinsic object that provides functions to convert JavaScript values to and from the JSON
format. The JSON.stringify function serializes a JavaScript value to JSON text. The JSON.parse function deserializes JSON text to produce a JavaScript value.

18. Prefer using Dot Notation
Objects properties in javascript can be accessed primarily in two ways: Dot notation and Square bracket notation.
Dot notation:
1. MyObject.property
Square bracket notation:
1. MyObject["property"]
Using dot notation brings consistency and prevent us from using reserved keywords as our properties. On the other hand, with bracket notation, the property name is a string which is evaluated to resolve the property name. The string can be hard-coded, or a variable, or even a function call which returns a string property name. Square notation should be used only in two cases; first, when we have properties that will be evaluated at runtime, and second when we having any property which is a keyword in Javascript.
NOTE: We should never have any property which is reserved keyword in Javascript.

19. Feature-Detect Rather Than Browser-Detect
Some code is written to detect browser versions and to take different action based on the user agent being used. This, in general, is a very bad practice. Any code which even looks at the global “navigator” object is suspect. The better approach is to use feature detection. That is, before using any advanced feature that an older browser may not support, check to see if the function or property exists first, then use it. e.g:
1. if (document.getElementsByClassName) {
2. var element = document.getElementsByClassName('highlight');
3. } else {
4. alert('Your browser lacks the capabilities required to run this
script!');
5. }

20. Use “strict mode” at the top of your javascript code.
Strict mode is a way to introduce better error-checking into your code. When you use strict mode, you cannot, for example, use implicitly declared variables, or assign a value to a read-only property, or add a property to an object that is not extensible.

21. Assign methods to the prototype instead of overwriting the prototype with a new object.
For example:
Bad example:
1. Jedi.prototype = {
2. fight: function fight() {
3.console.log('fighting');
4. },
5. block: function block() {
6.console.log('blocking');
7. }
8. };

Good example:
1. Jedi.prototype.fight = function fight() {
2. console.log('fighting');
3. };
4. Jedi.prototype.block = function block() {
5. console.log('blocking');
6. };