Avoid using Keywords
You cannot use the keyword default
:
Uncaught SyntaxError: Unexpected token default
You'll need to rename your function.
Immediately Invoked Function Expressions
Once you've done that, you can wrap it in parenthesis to execute it immediately:
(function dflt(){
var i = 7, j = 15;
document.write( i + j );
})();
Warning: Avoid document.write
Note that document.write
will clear out your document, thus removing the contents of your document. You should instead insert a new text node, or update the contents of an element on the page:
(function dflt(){
var i = 7, j = 15;
document.body.appendChild( document.createTextNode( i + j ) );
})();
You could also add this text node to an element on the page:
var tNode = document.createTextNode( i + j );
document.getElementById("foo").appendChild( tNode );
This would add the resulting text to any element whose id
attribute is foo
:
<span id="foo"></span>