JavaScript is a versatile programming language primarily used for web development. It's lightweight, interpreted, and works well with HTML and CSS on any operating system.
JavaScript can be embedded in HTML using the <script> tag:
<script type="text/javascript">
// JavaScript code goes here
document.write("Let's Meet JavaScript!");
</script>
Note: The 'type' attribute is optional in modern HTML.
The order of instructions in programming is crucial. Variables should be declared and initialized before use. For example:
var x;
x = 5;
document.write("Value of variable x is: " + x);
Note: If you write line 7 just after line 11, then the following message is displayed.
JavaScript supports various arithmetic operators:
Example of using operators:
var a = 10, b = 5;
var c = a + b;
var d = a - b;
var e = a * b;
var f = a / b;
var g = a % b;
JavaScript can respond to user actions (events) like button clicks:
<button onclick="myFunction()">Click me</button>
<script type="text/javascript">
function myFunction() {
alert("Do You Mind, CLICKING on the Button");
}
</script>
Variables can store different types of data. You can also get user input:
var name = "Akbar";
var reward = 5000;
document.write(name + " gets a reward of Rupees " + reward);
// Getting user input
var userInput = prompt("Enter a number, please: ");
var number = parseInt(userInput);
document.write("Input from the user was: " + number);
Variables in JavaScript can store various types of data:
JavaScript is case-sensitive, so 'myVar' and 'myvar' are different variables.
var x = 5;
var y = "Hello";
var z = true;
An array is a data type which can hold a number of homogeneous set of elements. This allows us to declare an array which contains 25 values, rather than defining multiple variables of the same type like num1, num2, ..., num25.
We can directly access any value just by passing the respective array index number. It is trivial to note that array index starts with 0. Declaration of an array is of the form as shown in line 7 of Fig. 31.
<script>
var arr = [1, 2, 3, 1.7];
document.write(arr);
</script>
Alternatively, we can declare a null array first and assign values to it later, as shown below:
<script>
var arr = new Array();
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
document.write("Elements of Array arr: " + arr);
</script>
So, rather than assigning values one by one, as highlighted in the lines 8-12 in above code, we can use the loop to populate an array. The code in Fig. 31 initializes the array on line 7.
Conditional or selection statement is an essential part of the program where amongst choices, the program chooses on the basis of some constraint. Applying an 'if' statement before one or more lines of code on the basis of some condition enables the program to execute only if the condition is satisfied in that scenario. That is, if the condition is met, then those lines will be executed otherwise skipped.
Now, to check the condition, JavaScript provides set of comparison operators to be used for evaluating the condition. The conditional operators are listed in table:
Operator | Meaning | Example |
---|---|---|
== | Is equal | x == y |
!= | Not equal | x != y |
> | Greater than | x > y |
>= | Greater than or equal to | x >= y |
< | Less than | x < y |
<= | Less than or equal to | x <= y |
For example, for admission to a Montessori school check the age of a child, if the age of at least 4 years old, then admission is granted. So, the code should look like the following:
<script>
var age = 5;
if (age >= 4) {
document.write("Admission Granted !!!");
}
</script>
You may check it for different values of the variable and also for different comparison operators.
A better notion is to align both the scenarios, i.e. if condition is met and vice versa. This is done using an 'if-else' statement, as shown in Fig 27. This way, either of the two situations will definitely happen.
There are scenarios where more than two possibilities exist and for that reason, we can modify our selection statement to be an 'if-else if-else' statement. This way, the set of conditions apply, first with 'if' and thereafter with 'else if' statements. If all the set conditions do not meet then 'else' will take care of it.
<script>
var age = 5;
if (age >= 5) {
document.write("Admission Granted to Nursery Class !!!");
} else if (age >= 4) {
document.write("Admission Granted to KG Class !!!");
} else if (age >= 3) {
document.write("Admission Granted to Preparatory Class !!!");
} else {
document.write("Child is too young to be Admitted in Primary School");
}
</script>
Fig 28: If-else if-else statement.
Iterative statement (like 'For Loop') is used to get similar kind of task done. Rather than writing the same line of code multiple times, the same task is done in much lesser line of code. The 'for loop' works on the basis of an index, which you can initialize in the loop. Next is the terminating condition which needs to be set for the loop to terminate. Lastly, there should be an increment or decrement statement, so that iteration continues till the terminating condition is met.
In the following example (for loop), an index is initialized to 1, the value of index will increment with 1 and loop will execute 10 times, till i reaches 10.
<script>
for (var i = 1; i <= 10; i++) {
document.write("Count Days After 10th: " + i + "<br>");
}
</script>
Fig 29: A simple For Loop, shows how index value increases.
Alternatively, we can decrease the index value and set the condition accordingly; in the code of Fig 30 we increased the step size, too.
<script>
for (var i = 10; i >= 1; i -= 2) {
document.write("Count Days Before 10th: " + i + "<br>");
}
</script>
Fig 30: For Loop with step size of 2.
Multiple iterative statements (For Loops) can be incorporated in such a way that one loop can reside inside the other and are termed as "Nested Loop". In nested loop, initially the outer loop will start and then the inner loop will run and end, and again the outer loop will increment and the inner loop will start and end, and so forth until the outer loop terminates. Fig 31 demonstrates a nested loop.
<script>
for (var i = 1; i <= 3; i++) {
for (var j = 1; j <= 3; j++) {
document.write("The Value for Outer Loop: " + i + " ");
document.write("The Value for Inner Loop: " + j + "<br>");
}
document.write("<br>");
}
</script>
Fig 31: Nested Loop.
In a similar fashion, the code in Fig 32 prints Mathematical Tables from 2 to 5. The outer loop assigns the value, for which the Table is required while the inner loop prints the Table as required.
<script>
for (var i = 2; i <= 5; i++) {
for (var j = 1; j <= 10; j++) {
document.write(i + " * " + j + " = " + (i*j) + "<br>");
}
document.write("<br>");
}
</script>
Fig 32: Printing Mathematical Tables from 2-5.
Take a number as input from the user and write a program to calculate the grade of the student (i.e. Distinction, First, Second or Fail) for the number so input. The condition for grades is given below.
Functions are set of code which occurs in the code quite often that can be segmented once, and called again and again. This way, rewriting the same set of code for similar results can be eliminated. Through functions, different sets of code can be separated resulting in better time of debugging. These functions segregate the program into manageable portions and leads to efficiently managing a large computer program. Programming languages provide tools like functions (we earlier we have used functions getName(), thisDay(), etc). Whenever the function is called, the caller does not necessarily need to know the code behind the function, for sake of abstraction.
A function has a name through which it is identified and called. Additionally, a function can have arguments, which are variables local to that function and their life span is limited to the said function. Variable outside functions are global variables and can be accessed anywhere from the program. Recall the earlier program where we used the function getName() to get the name of the user and greet the user accordingly. Refer to the example, where we used the function getName() to get the name of the user.
We extend the same code, and provide it with values which are assigned to arguments of the function. And thus, we can use them in the function, as shown in Fig 36.
<script>
function greet(name, amount) {
var res = "Hi " + name + ", you gave me " + amount + " ???";
return res;
}
document.write(greet("Ram", 5000));
</script>
Fig 36: A function with arguments
Lastly, later define another function calcBalance() to add to the above v.r.t. the arguments, namely bill and 'amount_rcvd'. The function subtracts bill from 'amount_rcvd' and returns the result. An important point to note in Fig 37 is the lines 5 and 10, where the former prints inside the function and latter always the result outside the scope of the function. Similar approach can be used for testing the values of a function, when frequent occurring set of codes are selected to form a new function.
<script>
function calcBalance(bill, amount_rcvd) {
var balance = amount_rcvd - bill;
document.write("Inside function: " + balance + "<br>");
return balance;
}
var result = calcBalance(2735, 5000);
document.write("Your Balance is: " + result);
</script>
Fig 37: Function returns value
Lastly, later define another function calcBalance() to add to the above v.r.t. the arguments, namely bill and 'amount_rcvd'. The function subtracts bill from 'amount_rcvd' and returns the result. An important point to note in Fig 37 is the lines 5 and 10, where the former prints inside the function and latter always the result outside the scope of the function. Similar approach can be used for testing the values of a function, when frequent occurring set of codes are selected to form a new function.
<script>
function calcBalance(bill, amount_rcvd) {
var balance = amount_rcvd - bill;
document.write("Inside function: " + balance + "<br>");
return balance;
}
var result = calcBalance(2735, 5000);
document.write("Your Balance is: " + result);
</script>
Fig 37: Function returns value