Javascript Basics – variable function loop if-then-else print

Learn the very basics of Javascript: variables, functions, loops, if-then-else and printing. Run the short example in your browser, then view the source.
Knowing the basics will make it more fun to jQuery/PhoneGap/Cordova/ProcessingJs.

Prequisites: Short HTML5 page.
See this Javascript in action – from the comfort of your own web browser.

<!doctype html>
<html>
<head>
	<title>Javascript Basics - variable function loop if-then-else print</title>
	<meta charset="utf-8" />
</head>
<body>
	<h1>Javascript Basics</h1>
	<pre id="tOut"></pre>
	<p>To see how this page is made, just right click and View Page Source.
	More tutorials like this on <a href="http://terokarvinen.com">TeroKarvinen.com</a></p>
	<script type="text/javascript" charset="utf-8">
		// Javascript goes last, just before /body. For performance. 
		// Functions are just declared here,
		// they are only run when called. We call them in main program.  
		function square(x) {
			return x*x;
		}
		function print(s) {
			// modify contents of PRE whose id is "tOut"
			tout=document.getElementById('tOut');
			tout.innerHTML += s + "\n";
		}
		// main
		print("Hello Javascript world!");
		print(2+2);
		// call function (now it runs)
		square(3); // result ignored, because we didn't print
		print(square(10));
		// variable assingment
		var area=square(2);
		print(area);
		// string catenation
		print("Area of the square is "+area);
		// loop
		var i=0;
		while(i<10) {
			print(i);
			i++;
		}
		// if-then-else
		if (1<2) {
			print("1<2, not a surprise");
		} else {
			print("This is never printed. ");
		}
		print("What next?");
		print("Practice these basics. Try jQuery and Processing.js.")
	</script>
</body>
</html>

Posted in Uncategorized | Tagged , , , , , , , , , , , , , | Comments Off on Javascript Basics – variable function loop if-then-else print

Comments are closed.