Hello, World! in ECMAScript
Example for versions
Rhino 1.6,
SpiderMonkey 1.7
JavaScript uses different commands to output messages depending on what environment is it used in:
-
print
: for interpreters with command-line interface prints the message to standard output stream, but when used in web-browser, calls print dialog instead; -
document.write
: when used in web-browser, prints the message to the current document (web-page); -
console.log
: a command for Firebug plugin which prints the message to debug console of the plugin; -
alert
: when used in web-browser, creates a pop-up information window with the message.
Note that three last commands won’t work in non-browser-based environment, since they use objects (document and console) which are not defined in command-line interfaces.
The example itself works in a smart universal way: since it can be executed in multiple environments with various objects defined, it checks each object in turn, and uses the first available writing method.
if (typeof console === 'object') {
console.log('Hello, World!');
} else if (typeof document === 'object') {
document.write('Hello, World!');
} else {
print('Hello, World!');
}
Comments
]]>blog comments powered by Disqus
]]>