How to Write Your First JavaScript Program

JavaScript is an Object-Oriented Programming language (OOP). In OOP, you use objects to write programs.

You can access the HTML elements using ids, classes, etc. but you can also access them using objects. In Document Object Model (DOM), the HTML page is described as a tree structure in which every node represents an object.

1. Your First Program: ‘Hello, World!’

You can write JavaScript code directly in your HTML page using the script tags. It can be kept either in the body or the head tags as follows:

<!Doctype html>
    <script language="Javascript" type="text/javascript"> 

You can write using the dot syntax, in which first you have to write the object name and then a method or property. We’ll now use the document object which represents your HTML page. You have to use the write method to display your text on the HTML page as follows:

document.write(“Hello, World!”)

Type it in between the script tags and save your HTML page with .html extension. When you open the page in the browser, these words will be printed on the screen.

Some old browsers do not support JavaScript so it’s better to comment out your JavaScript. Use <!-- (JS CODE) --> after the script tags. Browsers which are JavaScript compatible will recognize this code and will run it.

2. Mathematical operations in JavaScript

In HTML if you write any mathematical operation, it gets printed as it is because all the values in HTML are texts. Lets see how you can do mathematical operations in JavaScript.

First you have to declare a variable. The format is to first write the keyword, and then the variable name. Keywords are special words defined in JavaScript. For declaring a variable var keyword is defined.

Lets say we have five subjects and we want to evaluate the percentage of the marks of students.

The JavaScript code to implement this can be seen below:

<!Doctype html>
    <script language="Javascript" type="text/javascript">
      var marks = 0
      marks = prompt('Enter your marks ','')
      var result = marks * 0.002
      alert("result: " + result)

In the first line of codevar marks = 0we are initializing the variable. Then we ask for user input. In JavaScript you can use prompt function to ask for user info. The format is as follows:

prompt(‘question’, ‘default value’)

Next, we equate it to the var marks so that the new value that the user enters will now get assigned to this variable.

marks = prompt(‘Enter your marks ’, ‘’)

Default value is usually left blank but if there is no user input, then the default value can be used instead. Next, we assign a new variable result for the output.

var result = marks * 0.002

Now that you have got the user input, you can use alert function to display the result:

alert('result: ' + result)

We use + operator to add the value of result we got as output.

So you have now learned how to write some simple programs in JavaScript.


Related Posts