I remember how I started with tennis. My coach handed me a ball and a racket and told me to practice against a wall. The only instruction I got was to hit the ball above the marked line.
Learning a programming language is similar to picking up a sport. You arm yourself with a few statements and practice till you get the hang of them.
For this reason I have loaded the tutorial with dozens of with examples and assignments. So without much ado, let’s start on creating your first JavaScript.
Sponsored Links
Printing text with JavaScript
Start a text editor (example, Notepad in Windows) and type the following:
<HTML> <HEAD> <TITLE>My First JavaScript</TITLE> </HEAD> <BODY> <SCRIPT LANGUAGE="JAVASCRIPT" TYPE="TEXT/JAVASCRIPT"> <!-- document.write("I love JavaScript"); //--> </SCRIPT> </BODY> </HTML>
Save this file with a .html or .htm extension and view it in a browser.
You can also click here to know how it looks. (This opens another window)
Explanation
document.write(“I love JavaScript”); is a JavaScript statement. Note the following points:
- The JavaScript statement is enclosed in the <SCRIPT> and </SCRIPT> tags.
- The code informs the browser to write some text in the document. In this case, the text to be written is I love JavaScript.
- The text is enclosed in quotes and placed inside parenthesis. The quotes are NOT written along with the text; they help to signify the beginning and the end of the text.
- Though, it is not necessary to end JavaScript statements with a semi-colon, its always a good habit. Trust me!
Single and double quotes in JavaScript
You can write the above code with single quotes too and it will give the same result. However, if the text contains double quotes that have to be displayed, you should use single quotes to surround the text as in:
document.write('JavaScript is "NOT" Java');
Click here to view the result.
Similarly, to display single quotes nested them inside double quotes.
Case-sEnSiTiViTy in JavaScript
Like other languages, JavaScript is case-sensitive. This means that DOCUMENT.WRITE will not work. Also, a=2 is not the same as A=2.
Note: Event handlers are not case sensitive.