Javascript – Interesting parts

Posted: June 17, 2010 in Javascript
Tags:

Java Script – Object based dynamic typing language

first-class functions, inner functions, closures and prototypes are interesting areas which gives strong knowledge on javascript and helps in building efficient client side frameworks.

inner functions & closures – Inner functions (functions defined within other functions) are created each time the outer function is invoked, and variables of the outer functions for that invocation continue to exist as long as the inner functions still exist, even after that invocation is finished (e.g. if the inner function was returned, it still has access to the outer function’s variables) — this is the mechanism behind closures within JavaScript. Inner functions get access to the parameters and variables of the functions they are defined within.

prototypes – Every object is linked to a prototype object from which it can inherit properties. JS uses prototypes instead of classes for inheritance. It is possible to simulate many class-based features with prototypes in JS.  The prototype link is used only in retrieval. If we try to retrieve a property value from an object, and if the object lacks the property name, then JS attempts 2 retrieve the property value from the prototype object. And if that object is lacking the property, then it goes to its prototype, and so on until the procfess finally bottoms out withObject.prototype. If the desired property exists nowhere in the prototype chain then the result is the undefined value. This is called delegation. The prototype relationship is dynamic relationship. If we add a new property 2 a prototype, that property will immediately be visible in all of the objects that are based on that prototype.

functions as object constructors – Functions double as object constructors along with their typical role. Prefixing a function call with new creates a new object and calls that function with its local this keyword bound to that object for that invocation. The constructor’s prototype property determines the object used for the new object’s internal prototype. JavaScript’s built-in constructors, such as Array, also have prototypes that can be modified.

functions as methods – Unlike many object-oriented languages, there is no distinction between a function definition and a method definition. Rather, the distinction occurs during function calling; a function can be called as a method. When a function is called as a method of an object, the function’s local this keyword is bound to that object for that invocation.

Global Variables – Use it for maintaining application level assets. Following are the ways 2 define global variables

1. var a = 1;
2. window.a =1;  (window global object, a container for all global variables),
3. a = 1; (without declaration)

To be manageable always use single global variable and augment it with what ever new assets you want to add to the same variable at the later point of time. This will save us avoiding bad interactions with other applications, widgets or libraries.

var MYAPP = {};

MYAPP.myvar = 1;

MYAPP.user = {‘first-name’ : ‘vj’, ‘last-name’:’mahankali’};

MYAPP.myfunction = function(){};

Scope – A variable declared in a block is visible everywhere in the function containing the block. So its better to declare variable at the top of the function in stead of the site of first use.

Reserved words – (like try, class, if, protected … etc) can not be used to name variables or parameters. When they used as keys in object literals, they must be quoted.

Unicode – JS characters are 16 bits. This is enough to cover 65, 536 characters and to represent over it JS uses pair of characters. Unicode considers the pair to be a single character.

parseInt – Use radix parameter to see different results for parseInt(“08”), parseInt(“09”). Ex: parseInt(“08”, 10). Useful for date related operations.

Floating Point – 0.1 + 0.2 is not equal to 0.3, so for correct calculations scale them to integer arithmetic. Ex: instead of using 1.25$ use it as 125 cents.

NaN

typeof NaN === ‘number’ //is true even though NaN is not a number
NaN === NaN // false
NaN !== NaN // true
isNaN(NaN) // true
isNaN(0), isNaN(‘0’) // false
isNaN(‘oops’) // true

Falsy Values

NaN – Number type, null – Object type, undefined – Undefined type

== Vs ===, != Vs !==

Always use === or !== bcos these two will correctly validate the comparision correctly based on both operand type and their value.
Some of confusing validations with == operator…

” == ‘0’ // false
0 == ” // true
false == ‘false’ // false
false == ‘0’ // true
null == undefined //true

With statement

Avoid using With to avoid confusion and for better performance
Ex: with (obj) { a = b; } is same as
a = b;
a = obj.b;
obj.a = b;
obj.a = obj.b;

eval – Used for run time evaluation

1. Avoid using eval due to security (grants too much authority to eval’d text), performance reasons.
2. Function constructor is another form of eval and should be avoided. Declare and pass correct values to function as a 2 parameter function can be called with single or two parameters but its not a good idea to pass single parameter.
3. Giving string arguments to setTimeout, setInterval methods will make them act as eval, so avoid it.

Typed Wrappers –

Avoid using them as it is unnecessary and confusing.
Ex: Use {}, [] instead of new Object, new Array. No need of new Boolean(false), new Number, new String.

void – Is a operator that takes operand and returns undefined. This is not useful and confusing so avoid it.

Bitwise Operators

JS does not have integers, it only has double precision floating-point numbers. So the bitwise operators convert their number operands into integers and after the operation they convert them back. It gives performance issues as they are very far from the hardware, so avoid using it.

Function Statement Vs Function Expression

1. function statement is shorthand for a var statement with a function value.
function foo() {}
var foo= function foo() {} // foo is a variable which has function value
Second one is ideal use of language as functions are values assigned to a variable.
2. In JS we don’t need to declare function before using it (as they always be moved to the top of scope in which it is defined), which makes us to keep javascript file includes at the end of the web page for better performance.
3. The first thing in a statement cannot be a function expression bcos the official grammer assumes that a statement that starts with the word function is a function statement. Workaround is wrap function expression in parentheses.
(function(){})();

Array –

Known common operations – pop, push, reverse, concat, join, sort (default is string based, need to write custom implementation for numbers)
Other interesting operations …

shift – removes first element for array and returns it, returns undefined for empty array, slower than pop
unshift – like push except it puts items onto the front, returns new length
slice – makes a shallow copy of a portion of an array
splice – removes elements n adds elements at specified position

Enumeration – for in statement (for(val in myobj)) can be used 2 loop over all of the properties, functions in an object and on its prototype. To filter out necessary stuff use reflection (typeof or hasOwnProperty) to validate. There is no guarantee on the order of the names that returns, for getting it in proper order avoid using for in statement and use for.

Read other interesting stuff from here

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s