Every topic starts at New. Sign in and your practice counts.
Javascript is an exciting language primarily used in development of web pages and scripts. It does not consume much of memory and that is why it is used at the client-end in developing websites, for making pages dynamic. It easily works with programming languages like Java and HTML, on any operating system.
Javascript code can be embedded in HTML with starting and ending tag of <script>, in a webpage. There is no limitation of where to place the code inside a HTML file. For example, the following Javascript code embedded in the body, displays a sentence (string) using 'document.write()' function, as shown in fig-22.
This figure is being prepared.
In the sentence, displayed above we put additional spaces and tabs, which javascript simply discarded. For example, we will get the same output if the statement is like the one commented on line 5. Try it for yourself.
In programming everything that a user or another program does with your program that can be sensed and triggers some task to be done, is called an 'event'. Events are important and critical in the functioning and flow-control of your program.
Similarly, in website development, easiest way to introduce dynamicity is to allow some event to occur and respond accordingly. Alert is the commonly used functionality that
Javascript provides to inform user,about the result of his action or notification.Event based code like'onclick'are put between the start and end of<head>tag;unlike the above example,where we put our code within the<body>tag.The scenario in fig-23, allows the message to be displayed when the button is clicked.Functionality of button is added on lines 4-6,i.e.the message to be displayed when the buttons gets clicked.
<html>
<head>
<script type="text/javascript">
function msgSure(){ <
alert("Are You Sure???")
</script>
</head>
<body>
Do You Mind, CLICKING on the Button -
<input type="button"onclick="msgSure()"value="Be Sure" />
</body>
</html>
OUTPUT
And after the'Be Sure'button is pressed,the generated alert is as follows.
You can try for yourself,by replacing different messages and even arithmetic operations like: alert(2+2) which results as:
A variable is an entity that stores some value for later use. In mathematics, a variable is generally represented by a single character, but not limited to. Similarly, in programming languages, variable should be named in a meaningful manner. Additionally, the type of values the said variable can store is another important aspect. Such that the developer after defining and assigning a variable, is later able to recall about the task and type of values the said variable holds. The basic value that a variable can hold in JavaScript is either a number or set of characters (called string) or a Boolean which is either 'true' or 'false'. It is critical to note that variable naming convention does not support a number to be the first character of the variable name. Since, Javascript is case sensitive; therefore 'reward' and 'Reward' are two different variables. Table 3-3 enlists basic datatypes of JavaScript.
This figure is being prepared.
Table3-3: Basic datatypes supported by Javascript with sample values.
A variable is declared with the 'var' keyword and multiple variables can be declared in the same line of code, too. The first ever assignment of a value to a variable in the life span of program is called 'initialization'. A good programming practice is to declare and initialize the variable at the same time.
Javascript supports arithmetic operators to be used which are Addition (+), Subtraction (-), Multiplication (*) and Division (/). Other than this, the Modulus (%) operator can also be used which gives remainder of a division operation.
The code shown in fig-27, takes 3 variables namely, 'a', 'b' and reward. Only reward is initialized through a constant value in line 5. In line 6 and 7, remainder of reward divided by 10 is stored in 'a' and 'b' is assigned the value when reward is divided by 10, respectively.
<html>
<body>
<script type="text/javascript">
var a,b,reward;
reward = 5555;
a = reward % 10;
b = reward / 10;
document.write('Value of variable a is:',a);
document.write("<br />")
document.write('Value of variable b is:',b);)
</script>
</body>
</html>
Fig-27: Handling and Printing multiple variables.
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 is met makes a typical selection scenario. That is, if the condition is met, then those line(s) will be executed otherwise skipped.
Now, to check the condition, Javascript provides set of comparison operators to be used for evaluating the
| Operator | Name | Example |
|---|---|---|
| == | Is equal | |
| != | Is not equal | |
| > | Greater than |
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 achieved 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, step-size needs to be defined that how many steps the index will take after each iteration; till the terminating condition is met. In the following example 'for loop', an index is initialized to 0 , the value of index will increment with 1 and loop will execute till index value remains less than 10. Fig-31 depicts start, end and iteration of a for-loop.
This figure is being prepared.
Fig-31: 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-32 we increased the step size, too.
Multiple iterative tasks, if can be related then they 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 finish. Thereafter, the index value of outer loop will increment and the inner loop will start and end again, and so forth and so on; till the outer loop terminates. Fig-33 demonstrates a nested loop.
This figure is being prepared.
In a similar fashion, the code in fig-34 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.
<html>
<body>
<script type="text/javascript">
for (var i = 2; i <= 5; i++)
{
document,write("<br /> Table of: ",l,<br />");
for (var j = 1; j <= 10; j++)
{
document,write(i,"x"j,"=",if)," ");
}
document,write("<br /> <br /> ");
}
</script>
</body>
</html>
An array is a datatype which can hold a number of homogenous set of elements. Such that we do not need to define multiple variables of the same type like num1, num2, ... num25. Instead, we can declare an array which contains 25 values. This way, 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-35.
This figure is being prepared.
Alternatively, we can declare a null array first and assign values to it later, as shown below:
This figure is being prepared.
So, rather than assigning values one by one, as highlighted in the lines 8-12 in above code, we can alternatively use for-loop to populate an array. The code in fig-37 initializes a nullarray on line 7. In the next couple of lines a for-loop is taken into account in which user input is taken, via prompt() function.
Function is a set of line 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 fewer lines of code assigning them meaningful names based on their functionality. This leads to efficiently managing a large computer program. Programming languages provide built-in such functions like earlier we have used functions prompt(), input(), etc. Whenever the function is called, the caller does not necessarily need to know the code behind that function, to use it.
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. Variables outside functions are global variables and can be accessed anywhere from the program. Recall the earlier program of fig-23 where we defined a function, namely msgSure() and whenever the button is pressed an alert pops up asking "Are you sure?". In line 4 of the said code, we used the 'function' reserved word to define and named it. However, on line 11, we called the same function just with its name.
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-38.
This figure is being prepared.
Lastly, lets define another function calcBill() which is similar to the above as it accepts 2 arguments, namely bill and 'amount_rcvd'. The function subtracts bill from 'amount_rcvd' and returns the result. An important point to note in fig-39 is the lines 5 and 10, where the former prints inside the function and latter displays 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.
This figure is being prepared.
In the following line of code in fig-24, two variables are defined. One is a boy's name in the variable 'name' while other is 'reward' having value 5000. So, it displays the result in browser.
<html>
<body>
<script type="text/javascript">
var name = "Ahsan";
// document.write(reward);
" var reward;
reward = 5000;
document.write(name, " gets a reward of Rupees ", reward);
</script>
</body>
</html>
This figure is being prepared.
a logo (or image) should be displayed on the new tab.
Now, let's amend the same program for user input, where we want to change the value 'reward'; by taking input from the user. For input from the user we can use the prompt() function, which pops up a message window like that of alert() function. This input will be assigned to a variable at the
OUTPUT
Fig-25: Use of Variables
Create a list of subjects like 'HTML', 'CSS' and 'JavaScript' when clicked a new tab opens up. Relevant keywords and
This figure is being prepared.
backend which can be used, later. A sample code is as follows.
You can replace these lines in the previous example and will get the outputs, as shown in fig-25.
It is important to note that sequence of instructions in programming matters. For example let's look at the following code, where we defined two variables and keeping the good practice in mind, declared and initialized variable name in line 7. However, just to highlight how things can be alternatively done, we declared the reward variable in line 8 but initial value as assigned to it in the next line. In line 12 we print the statement using both the variables, as shown in fig-26.
Note that, if you take line 7 and put after line 11, then the following message is displayed.
This is due to the reason that the variable is defined after the write statement is using the variable. Unless, the variable is declared and holds a value, only then it can be used as per the programming sequence. Hence, sequence of instructions is important and though you might have written a program syntax-wise correctly, but the change of sequence might lead you to unexpected bugs.
| < | Less than |
| >= | Greater than or equal to |
| <= | Less than or equal to |
Table:3.4: JavaScript Conditional Operators
condition. The conditional operators are listed in table.
For example, the admission office of a Montessori school checks the age of a child, if the kid is of at least 4 years old, then admission is granted. So, the code should look something like, as shown in fig-28.
OUTPUT
OUTPUT
</script>
</body>
</html>
Admission Granted !!!
Fig-28: 'if' statement.
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 achieved using an 'if-else' statement, as shown in Fig-29. This way, either of the two situations will definitely happen.
This figure is being prepared.
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. For any other condition that has not been catered for, 'else' will take care of it. In Fig-30 the previous code is extended by checking multiple conditions.
This figure is being prepared.
This figure is being prepared.
OUTPUT
This figure is being prepared.
Once, the user input is taken and the loop terminates, in line 12 the elements of the array are displayed as in pervious example.
Elements of Array using For-Loop are, after declaring a null array:
This figure is being prepared.