Often we call console.write method from javascript method/function. It is working fine in most browsers. But some times it shows javascript bug (console is undefined).

Internet Exploere has no such console object(Latest version it is added but when IE Developer tool is open). In that time it will show javascript error and qa open bug.

A few days ago that type of problem raised in our development life cycle. The easiest way to solve the problem is

Just write the bellow code in any MasterPage(Base Page, common user control) etc. Just once need the code executed.

The code is

<script type="text/javascript">

      window.console = window.console || {log:function(){}};

</script>

What the code is doing

The above here i use javascript || (OR) operator. It actaully use to perform logical disjunction on 2 expressions.

first time when it execute in browser has window.console object then it returns and assign to window.console object.

If window.console not found then create new object  and assign to window.console object.

 

That way it will solve undefined error and fix the common bug.

Note: if you declare any javasript variable without var it will directly go under window object.

window object is javasript dom object.

 

Quiz:

1.

var i1 = 10;

var i2 = 20;

var result = i1 || i2;

console.log(result) //What will be output. Before execute that code just just think what the result will be then match.

 

2.

 

var i1 = 10;

var i2 = 20;

var result = i1 && i2;

console.log(result) //What will be output. Before execute that code just just think what the result will be then match.

 

 

 

 

 

 

 

Comments

ron's picture

This is helpful for javascript debugging specially in IE. Thanks habib vai for sharing.

Add new comment