Category: Javascript

console.log vs alert

If you’re debugging an application, then you want some feedback to know what’s going on inside the program. You can manually step through every function in your code. Or you can output a message to the screen or to the console. But which one is best, or do they both have their merrits?

Alert() is old school

Modern browsers have a superb set of debugging tools and options, but before this was not always the case. So in order to see what whas happening, you had to get a message to the outside. Alert() makes a pop-up window and writes a custom message in it. Ideal for checking the contents of variables and so on.

What are some of the drawbacks of Alert()?

  • alert() blocks your code until you press ‘OK’. Thus slowing the debugging process.
  • You cannot see more than one alert() message at a time. This forces you to use your memory. And multiple runthroughs to be sure if you’ve forgotten something.
  • alert() outputs a string, but it has only limited formating. For example: If you feed it an object it will just output [object] instead of the contents of that object

Alert [object]

  • You have the potential risk of showing an alert() to an end user.

Console.log() is the way

It has the same purpose as alert() but it does it more elegantly. It’s not blocking, you can view multiple logs at one time and you can feed it any object you like.

It’s purely designed for developers and thus is the prefered way to do your debugging.

So, alert is bad and console.log is good?

I wish it was so simple. In most cases I would advise to use console.log(). But in some cases alert() is the way to go.

For example:

var anArray = new Array(20);
anArray[4] = "red";
anArray[10] = 30;

console.log will format this to show only the filled array slots. and you won’t know how large the array is. alert() on the other hand will show every entry separated with a comma.

alert console.log array

It could save you some time knowing about it. While it’s easier to see which positions are filled in console.log, you can’t see the lenght of the array at the same time. console.log(anArray.lenght);  But if you don’t type the previous statement, then it’s easy to overlook.

alert() can offcourse be used to alert() the end user of something. But then this is not debugging, but rather user experience. (a bad user experience according to me.)

Don’t be so sloppy, let’s invoke strict mode

Normal JavaScript is pure chaos! You can initialize undeclared variables, you can compare strings and numbers, and you can do a lot of other stuff that makes your head pop. Therefore, normal JavaScript is sometimes called “sloppy”. Fortunately, there is a solution: You can force “strict mode” on your code to end the chaos and start the logic.

strict mode only works in ECMAScript 5 or higher implementations. Luckily, older browser will just ignore it and process your code as normal.

How to invoke strict mode

If you want to declare strict mode to your code then at the following line at the top of your code.

"use strict";

This will force strict mode onto everything inside the script tag. You can also use strict mode in functions.

function stuff(){
"use strict";
//does strict stuff.

Very important! “use strict” will only work if it’s written at the top of a script or function. Otherwise it will be ignored.

Also note that you can not use it inside if/else, for, do… statements because it only works for the whole script or for functions, not for other blocks.

Why use strict?

It forces you to write more ‘secure’ JavaScript by changing ‘bad syntax’ into actual errors. (undeclared variables, crazy comparisons…).

It restricts you in the use of JavaScript, but that’s not a bad thing. Since it throws more error’s when you do crazy stuff by accident. For example, making global variables in functions, or putting a leading zero in front of a number whithout realizing you just made it an octal and not a decimal.

Give me some examples

"use strict"
name = "Demian"; // name undefined => error
anObject = {a:1, b:2}; //anObject undefined => error

var badCake = “rotten applecake”;
delete badCake;//deleting a variable, object or function is not allowed => error
delete Object.prototype;//undeletable => error

function fun(a, a){};//duplicate parameter name => error

var octalNumber = 010;//I hate octal Numbers => error
//ES6: put 0o in front for Octal notation.
//like this: var a = 0o10;

var escapeThis = \010;//your characters cannot escape => error

var emptyObj = {};
Object.defineProperty(emptyObj, “x”, {value: 0, writable: false});
emptyObj.x = 666;// A read only property cannot be written to => error

var numberOfTheBeast = {get x() {return 666}};
numberOfTheBeast.x = 4; //It’s a demonic getter, don’t write holy numbers on it

with (Math){x = cos(2)}; //’with’ is not allowed => error

eval(“var number = 3”);
console.log(number); //eval cannot create variables in the scope from which it was called => error.

In addition it also future proof’s your code by making reserved keywords not allowed.

  • implements
  • interface
  • let
  • package
  • private
  • protected
  • public
  • static
  • yield

"use strict"
var interface = {}; //error!

Look at MDN for a full list of all the changes “use strict” enforces.

If you turn things around, normal JavaScript allows all of the above, some are legit syntax while others are silent errors.

How does it work internally?

Basically, your strict code is compiled differently from the sloppy code. Therefore, it’s not a subset, it’s JavaScript with different syntax rules.

Is it backwards compatible?

Yes, the “use strict”; syntax is actually a string literal like (“I’m a string”;) which will compile to a non existing variable never to be seen again. Thus it is harmless in older browsers and newer browser will recognize the literal and enforce strict mode.

Be careful when you use strict, older browsers, like Internet Explore 9, will ignore it and execute your code as normal JavaScript, this can have unwanted side effects. Test your code in both browser that support strict mode and browsers that do not. Otherwise you’re bound to run into major troubles.


A backwards compatible Script tag

When the script tag was first introduced only Netscape Navigator and Internet Explorer supported it. Other browsers hopefully ignored the contents or worse, they printed it to the screen for all the world to see. At present day, the script tag works in all major browsers like it’s supposed to. But it wasn’t always like that in the past.

For example, take the script below, nothing wrong with that, or so you would think. It worked in HTML, then it didn’t work in XHTML, and now it works again in HTML5.

function compare(a, b){
if(a < b) return a; //XHTML: it crashes on the '<' symbol
else return b;

Temporary solutions

Because the above doesn’t work in XHTML a solution was provided. the ‘<‘ is a reserved character in HTML, so it’s entity name has to be used: &lt;

function compare(a, b){
if(a &lt; b) return a; //HTML5 crashes here
else return b;

A working solution for XHTML, but it doesn’t work in HTML5 and to top it off, it’s not readable. Fortunately, they invented a different sollution:

<script><![CDATA[//HTML5 crashes here
function compare(a, b){
if(a < b) return a;
else return b;

Just add <![CDATA[]]> around your code. CDATA indicates that the text is free-form and should not be parsed. This enables you to use any reserved character you can think of without punishement. Unfortunately, it still doesn’t work in HTML5.

function compare(a, b){
if(a < b) return a;
else return b;

The above works everyware, finally a full solution. But wait what if you come against a browser that doesn’t support the script tag. (note: All modern browsers support the script tag, we’re talking about ancient browsers here).

The solution: You comment the contents of the script tag with a html comment

function compare(a, b){
if(a < b) return a;
else return b;

A backwards compatible script tag

But how about CDATA? Well, let’s just combine the two solutions into one.

function compare(a, b){
if(a < b) return a;
else return b;

Tadaa!, the most backwards compatible script tag you’ll ever see. enjoy!

And don’t worry about remembering this little line. You won’t need it if you use external scripts. It’s only needed for inline code.

So, the script will always work like this?

Actually, no. The script will definately work, but the ancient browser might not support the script tag or the modern browser might have turned off JavaScript.

in either case, you can and should use the <noscript> tag in the body. This will only display when scripts are not working. For example you can leave a message where the user can download your latest favorite browser which has perfect JavaScript support.

The script tag attributes

JavaScript comes with the script tag, or rather the script tag enables JavaScript to be executed within HTML. You cannot have one without the other. With the script tag, JavaScript blends perfectly with HTML, but it has some peculiarities, which I’m going to discuss below.

//your JavaScript code here

The Script TAG

The script element can be alone, or it can contain some attributes. Nothing is mandatory, some are assumed by the browser when omitted and others require some explanation before use.


Indicates the location of your script, this can be local (on your own server), or global (

Async or DEFER

Both are optional, and mutually exclusive. Meaning, you don’t have to use them, but if you do, you can only use one, not both.

The normal behavior when loading a HTML page is that when you encounter a script tag, you load the script, and then continue with the rest. The result is unwanted because your page appears to freeze until everything is loaded. Async and defer are both solutions to this problem.

If you want to load the page before your scripts execute, you can put your script tags at the bottom of the <body> tag. Async, enables you to start loading your scripts at the start of the page, but it puts them on another thread and thus allows the rest of your page to keep loading. Defer says that the script tag can only load when all the document’s content is parsed and displayed.

You don’t know when a script will finish loading when you use async. So only use async on indepent scripts. For example: If a script depends on another script to run before it can run itself, then it is vital that it does so. Async has a tendency of screwing up these scenarios.

Defer scripts load in order, hopefully, but this is not always the case, so use only one defer if possible. If you put your script at the bottom of the body tag, then you’re triggering the same behavior as the body tag.


This attribute is a new one, and not totally compatible with all the major browsers yet. Use it when you need scripts from a third source (cdn’s). You get scripts from a third party for speed and bandwidth benefits, but what if an attacker takes over the third party and inserts some malicious code into the extarnal script?

The integrety tag will ensure that the file you recieve is the one you want. If it doesn’t match, then the browser will return a network error.

<script src=”” integrity=”sha256-slogkvB1K3VOkzAI8QITxV3VzpOnkeNVsKvtkYLMjfk=” crossorigin=”anonymous”></script>


Another new one. If you need credentials for an external script, then you need the crossorigin attribute. It defaults to ‘anonymous’ and this is the normal behavior. Set it to ‘use-credentials’ when credentials are needed.

Deprecated attributes


The type attribute is optional, or rather the browser will assume the standard value ‘text/javascript’ when you don’t write it (only in HTML5). Known as the MIME type, it indicates the content type of the scripting language you use inside the script tag.

Other variations are “text/ecmascript”, “application/javascript”, “application/ecmascript” and even “application/x-javascript”. In effect, the attribute is deprecated, but still used.

If you write something invalid in type, the browser will ignore the inside of the script tag. BUT!, You can still access the data inside it with JavaScript. This is used in some situations and some template libraries use this hack as well.


Avoid this attribute, it’s deprecated and ignored by all browsers. Older browsers used the language attribute until the type attribute replaced it. The current browsers ignore this attribute, if you’re lucky.


Don’t use it. period.



How a browser implements JavaScript

According to Wikipedia, JavaScript is the following: (please click the link and skim the wikipage)

JavaScript is a high-level, dynamic, untyped, and interpreted programming language…

As correct as this statement and the rest of the wikipage is, it’s not the entire truth. The wikipage talks about JavaScript as an ECMAScript implementation, and when you use JavaScript outside of the browser (in PDF-documents or desktop widgets), this is the only thing you have to know. But you will need a bit more power when you add dynamic behavior inside a browser page.

Javascript implementation

The full Javascript implementation consists of 3 things:

JavaScript Implementation

  • The Core, implemented according to the ECMA-262 standard.
    • This covers syntax, data types, objects, inheritance and so on.
  • Document Object Model (DOM)
    • This allows you to access and modify your HTML
  • Browser Object Model (BOM)
    • Everything outside the context of your page (windows & frames, history, sound…)

EcmA-262 and Ecmascript

ECMA-262 is the standard which defines ECMAScript and JavaScript  is an implementation of ECMAScript. There are other implementations of ECMAScript, for example: ActionScript for Flash.

ECMAScript defines how you write the language. It defines its syntax and how the data types work. Furthermore, it defines what happens when you add a number to a string and also describes the behavior when you parse a string into a number. It defines objects, prototypes and inheritance and much much more…

ECMA-262 also evolved and has different edition’s. Currently, most browsers support edition 5, while edition 6 is only supported by the most recent versions of the major browsers.

Document Object Model (DOM)

Next on the list is the DOM. The main purpose of JavaScript is to make a richer web experience. This is mostly done by manipulating the HTML. This is were the DOM API comes in.

The DOM API provides methods and functions for finding elements in your HTML and then manipulating or deleting them. You can also create new elements from scratch.

W3C standardized the BOM and has levels instead of editions. Currently all the major browsers support DOM Level 3.

Some examples of the DOM API in action

Historically, the DOM is used for input validation and the next thing that comes to mind are calendar widgets, advertizing and drop-down menu’s (although the last one can be done by CSS too).

With the arrival of HTML5 and the canvas element, you can make huge interactive games with it, it even rivals flash games.

Browser Object MODEL (BOM)

The BOM API gives you access to some browser related functionality. For example, create new windows and frames, change the size of the browser and  create custom back and forward buttons.

The arival of HTML5 standardized the BOM. Before it that, it was pure chaos. There is still some browser specific functionality, but this mostly relates to the ActiveXObject of IE and mobile features for smartphones.


JavaScript shines with a codified BOM

The Browser Object Model (or BOM) is an API you use it to access and manipulate the browser window. With the BOM, you can interact outside the boundaries of the displayed page, which is an awesome capability. But the BOM is also an evil dragon, because it doesn’t has any standard, and thus each browser has a different BOM API.

So, no standard eh? Well, for a long time, that was completely true. But HTML5 sought to standardize the BOM and created a specification for it. So now, the major browser have some agreed upon names and methods for the most used functionalities.

What does the BOM do?

Anything that’s browser specific is part of the BOM, but generally you will use it for manipulating windows and frames.

  • ‘Window’: properties and methods related to windows and frames
    • pop-up windows
    • move, resize and close windows
    • alert(“Hello world!”);  //I’m sure you’re familiar with this statement 🙂
  • ‘navigator’: this object provides detailed information about the browser
    • used for user-agent sniffing
    • ‘geolocation’: this is usefull for directed commercials and such.
    • ‘cookieEnabled’: usefull to know.
  • ‘location’: usefull methods to retrieve the URL or parts of the URL of the loaded page
  • ‘screen’: Returns the width and height of the screen.
  • ‘history’: Returns the browser history and allows you to go back or forward to a specific page.
    • privacy related, you cannot read the specific entries of the history object, you only know how many entries their are.
    • It’s mostly used to create custom back and forward buttons

All the major browsers implement the above since HTML5 codified it, and it’s expected that the standard will expand and grow in the future, thus ending the confusion surrounding the BOM.

Then what’s not the same?

Anything that’s browser specific. IE has it’s ‘ActiveXObject’ and mobile browsers will have mobile specific methods.   Fortunately, a lot is the same (since HTML5) and you can do a lot with the standard functionalities already.

If you’re not sure you can use something, then go and check ‘Can I use?‘.

What’s the Difference between BOM and DOM

The Document Object Model (DOM) handles everything related to your page, while the Browser Object Model handles everything outside of the page.


Javascript and the DOM API

Javascript comes with the Document Object Model (DOM), it would be useless without it.  The DOM is not HTML, but it’s an Application programming interface (API) for XML, and it enables you to access your HTML. As a result, it gives you the ability to read, add, delete and modify your html without a page reload.

HTML is an XML variant, and below is a small example of it. (If the following looks unfamiliar to you, then learn some basic HTML)

<title>example title</title>
<p>This is an example of a DOM</p>

The above example is what you type and read, but JavaScript represents it as a node tree that looks like this:

DOM Node Hierarchy

The birth of the DOM API

Javascript only had one purpose when it was first created, and that was to minimize round trips to the server. It was first used for client-side input validation, which needed you to alter the html. Unfortunately, Netscape Navigator 4 and Internet Explorer 4 each implemented it’s own method for accomplisching this feat. It was a big step forward for usability, but it was also a nightmare for programmers, since they couldn’t write cross-platform webpages anymore.

Therefore, the World Wide Web Consortium (W3C) stepped in and created a standard for creating with HTML. And so, DOM Level 1 was born.

Level up

The DOM API has two big groups of methods. The core: which is used for every XML based document and the DOM HTML extensions: for html specific objects and methods.

The internet evolved and so did the API. Level 1 focused on the structure of a document, whereas Level 2 added support for mouse and user-interface events as well as better Cascading Style Sheets (CSS) and traversal methods to iterate over a DOM document. Then came Level 3 which added load and save functionality and validation methods.

You might also hear about DOM level 0, but this never existed. NN4 and IE4 use it to reference to the original DHTML.

=> More detailed info about each level.

It’s only a recommendation

It’s not mandatory, no government enforced a browser manufacturer to use the standard. As a result, not all browsers support everything. A clear overview of which browser supports what is currently not available (read: I can’t find one). As a result, my first option is to go to ‘Can I use‘ and if I can’t find it there, I go to Mozzila’s Developer Network. It covers every method and function, and contains information about browser compatibility.

Hence, use feature detection if you implement an unsupported method. Otherwise you can prompt the user to upgrade to an other browser that does support the recommendations of the standard. Fortunately, most of the modern web browsers implement all of the Level 3 specification.


Question’s and Answers about the DOM

Do other XML based formats have an API?

There are numerous XML markup languages like HTML, furthermore, each comes with it’s own API. They come in all shapes and sizes. A web-based environment uses multiple,but some are only server-side and others represent specific research data and such. Some XML variants: Documents (HTML, XHTML),  Graphics (SVG, XAML),  Mathematics (MathML, CellML), Multimedia presentations (SMIL), Authentication and Authorization (SAML), web feeds (Atom) and many more…

Is the DOM JavaScript Specific?

No, it is not, a lot of other languages implement it as well. That said, EcmaScript Implements the DOM and is a big part of the JavaScript Language.

Is DOM and HTML the same?

Again no, The browser uses the HTML page to built the DOM object. Then in JavaScript, you can access the object and make manipulations. If you take it to the extreme, you can load a page with only JavaScript (so only a html, head and script tag) and generate your entire page from scratch.


The very foundation of Javascript: EcmaScript-262

Let’s start with a bit of history about EcmaScript. Javascript 1.0 releases for the first time in Netscape Navigator 2. It was a blast! It got very popular very quickly that Microsoft decided to duplicate the language in it’s latest edition of Internet Explorer 3 and called it Jscript to avoid licensing issues with Netscape.

Both were ment to be the same, but they weren’t, therefore a standard was needed and ECMA (European Computer Manufacturers Association) stepped in. So they created a commitee of programmers from Netscape, Sun, Microsoft, Borland… and produced standard Ecma-262 alias EcmaScript. Now it was up to the browsers to try and implement that standard.

In addition, implementation differs among all the browsers. Furthermore, to make matters worse or at least a bit more complicated: Ecma-262 evolved and gained newer editions. Currently all major browsers support most of edition 5 and below, while edition 6 is supported by all the latest versions of the major browsers (not IE11, but Edge does)

I think a book can be written about all the differences in implemention for each browser version and EcmaScript edition combination. But rather than doing that (that would be so boring to read) I will direct you to the best resource I have found. =>

EcmaScript-262 Compatibility table

This is an awesome resource to check and verify compatibility differences between all the browsers and there versions. In addition, a code sample is provided for each test. This is handy for if you encounter a browser that isn’t listed in the compatibility table. But you can also learn how to use the features of EcmaScript-262 by looking at specific examples.

EcmaScript-262 Questions and Answers

So Javascript is the same as EcmaScript-262?

No! EcmaScript-262 is the basis of Javascript. In addition you have the DOM (Document Object Model) and the BOM (Browser Object Model). But beware each is, again, differently implemented in each browser.

A handy resource to check for compatibility of certain features is Can I use?

Can I Use? - Compatibility checker

What does ECMA-262 specifiy exactly?

It defines the syntax (curly braces…), the data types (string, float, object…), statements (if, switch, do, while, with…), Keywords (if, switch, break, continue…), Reserved words (abstract, arguments, boolean…), Operators (+, -…), Objects.

ECMA-262 tells you how to write javascript. But it doesn’t say anything about adding properties in HTML. That’s the domain of the DOM.

Which other languages use ECMA-262? and do they all use the same edition of ecmascript?

Javascript: edition 5.1 and 6. Depending on which browser you’re using.
JScript: edition 5.1
JScript.NET: Microsoft’s variant got an upgrade to a full programming language insteas of a scripting language (read: you have to compile it to make it work).
ActionScript: Adobe Flash, Flex and Air. Currently on edition 4.
ExtendScript: every other program from Adobe. edition 3.

Are all these languages the same? Can I just copy code from one into the other.

If only it was that easy. They all implement ECMA-262 but they also have their own extensions and features that make them unique.

For example Javascript and JScript are very alike, safe for two features (see Patrick’s answer)

Which other ECMA standards are important to know.

ECMA-334: C# language specification
ECMA-372: C++/CLI language specification
Here you can find them all and even download the standards in pdf format.

HTML and CSS by W3C are mandatory to know. But beware, browser implement them slightly different, so look up the differences (Can I use?).

Which version of EcmaScript/Javascript am I using?

It depends on the browser your code is running in. So you don’t know which one you are using untill you (or someone else) runs your code. Furthermore, the editions are backwards compatible. As a result, what worked in an older version will also work in a newer one.

There are two possible solutions to this particular problem.
1. Refrain yourself from using the newest features and go back to the javascript stone age.
or 2. Use feature detection. If the feature exists use the fance code otherwise, use supported code from an older version.

You detect which version of Javascript or which browser your code runs in, but this is faulty since you don’t know what features are implemented of the particular version. So, feature detection it is.

But some features are undetectable, as a result user agent sniffing is your only option.