8.6 BASIC PROGRAMMING CONSTRUCTS IN JAVASCRIPT

JavaScript is a programming language that adds interactivity to your website (for example: games, responses when buttons are pressed or data entered in forms, dynamic styling, and animation). For doing that you should know the basics of language, which are discussed below.


Displaying output in JavaScript
JavaScript can “display” data in different ways: 
(i) Writing into an HTML element, using innerHTML
(ii) Writing into the HTML output using document.write()
(iii) Writing into an alert box, using window.alert()


Writing into an HTML element, using innerHTML
To access an HTML element, JavaScript can use the document.getElementById(id) method. The id attribute defines the HTML element. The innerHTML property defines the HTML content:
<html>
<body>
<h1>My First ever Web Page</h1>
<p>My First ever Paragraph</p>
<p id= “demo1”></p>
<script>
document.getElementById(“demo1”).innerHTML = 7 + 6;
</script>
</body>
</html>

Writing into the HTML output using document.write()
Writing into the HTML output using document.write(). For testing purposes, it is convenient to use document.write():
<html>
<body>
<h1>My First ever Web Page</h1>
<p>My first ever paragraph.</p>
<script>
document.write(7 + 6);
</script>
</body>
</html>
Using document.write() after an HTML document is completely loaded, will delete all existing HTML.

Writing into an alert box, using window.alert()
You can use an alert box to display data:
<html>
<body>
<h1>My First ever Web Page</h1>
<p>My first ever paragraph.</p>
<script>
  window.alert(7 + 6);
</script>
</body>
</html>
Example: JavaScript program to calculate multiplication and division of two numbers (input from user).
<!DOCTYPE html>
<html> 
<head>
<meta charset=utf-8 />
<title>Program to calculate multiplication and division of two numbers </title>
<style type= “text/css”>
body {margin: 30px;}
</style> 
<script type = “text/JavaScript” language=”JavaScript”>
function multiplyBy()
{
  num1 = document.getElementById(“fstNum”).value;
        num2 = document.getElementById(“scndNum”).value;
        document.getElementById(“answer”).innerHTML = num1 * num2;
}
function divideBy() 

num1 = document.getElementById(“fstNum”).value;
        num2 = document.getElementById(“scndNum”).value;
document.getElementById(“answer”).innerHTML = num1 / num2;
}
</script>
</head>
<body>
<form>
1st Number : <input type= “text” id=“ fstNum” /><br>
2nd Number: <input type= “text” id= “scndNum” /><br>
<input type= “button” onClick= “multiplyBy()” Value= “Multiply” />
<input type= “button” onClick= “divideBy()” Value= “Divide” />
</form>
<p> Answer is : <br>
<span id = “answer”></span>
</p>
</body>
</html>

Some Basics about JavaScript

Statement-
A statement is a line of code.
Example:
var hello = “Hello”;
var world = “World”;
var message = hello + “ ” + world;
This code can be executed by another program called an interpreter that will read the code, and execute all the statements in the right order.

Case sensitivity-
All JavaScript identifiers are case sensitive. The variables lastName and lastname, are two different variables.
var lastname, lastName;
lastName = “Naman”;
lastname = “Malik”;

JavaScript does not interpret VAR or Var as the keyword var.
JavaScript is a case-sensitive language. This means that the language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters. So the identifiers Time and TIME will convey different meanings in JavaScript.

Semicolon-
Semicolons separate JavaScript statements. Add a semicolon at the end of each executable statement:
var x, y, z;
x = 5;
y = 6;
z = x + y;

Comments-
Comments are statements that will not be executed by the interpreter, comments are used to mark annotations for other programmers or small descriptions of what your code does, thus making it easier for others to understand what your code does.
In JavaScript, comments can be written in 2 different ways:
A. Line starting with //:
// This is a comment, it will be ignored by the interpreter
B. Section of code starting with /*and ending with */, this method is used for multi-line comments:
/*
This is a multi-line comment,
it will be ignored by the interpreter
*/

Variables-
Variables are containers for changeable values. Variables can hold all kind of values and also the results of computations. Variables have a name and a value separated by an equal sign (=). Use the var keyword only for declaration or initialization, first time you use the variable in a document. You should not re-declare same variable twice.

JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data type. Unlike many other languages, you don't have to tell JavaScript during variable declaration what type of value the variable will hold. The value type of a variable can change during the execution of a program and JavaScript takes care of it automatically.
Example:
var value;
var result = 2;
You can also declare multiple variables with the same var keyword as follows –
var value, result;
Example:
This example defines two variables, after computing their addition the result is stored in third variable.
var x = 5;
var y = 6;
var result = x + y;

Types of variable-
Computers are sophisticated and can make use of more complex variables than just numbers. This is where variable types come in. Variables come in several types and different languages support different types.

The most common types are:
a. Numbers:
i. Float: a number, like 1.21323, 4, -33.5, 100004 or 0.123
ii. Integer: a number like 1, 12, -33, 140 but not 1.233
b. String: a line of text like “boat”, “elephant” or “damn, you are tall!” (We will discuss more on strings in later section).
c. Boolean: either true or false, but nothing else
d. Arrays: a collection of values like: 1, 2, 3, 4, ‘I am bored now’
e. Objects: a representation of a more complex object
f. Null: a variable that contains null contains no valid Number, String, Boolean, Array, or Object.
g. undefined: the undefined value is obtained when you use an object property that does not exist, or a variable that has been declared, but has no value assigned to it.

Strings-
This is a string.
“I love programming”;
You can define strings using var keyword either using single or double quotes.
// ‘Single quotes’ 
var str = ‘Please Enter your name’;
// “Double quotes” 
var print = “Thank you for your input”;
Concatenation of strings-
Concatenation is adding two or more strings together to creating a larger string. This is done using the + operator.
var message = ‘ wow’ + ‘JS is easy to learn’ + ‘and ’ + ‘easy to use’;
var firstName = “Alok”;
var lastName = “Kumar”;
var fullName = firstName + “ ” + lastName;
You can make sure the length of your string in JavaScript (length is the number of characters in string) just use the property .length

var sizeofString = ‘I Love India’.length;

Keywords-
There are some reserved words in every language which cannot be used as variables. JavaScript keywords are:

1

2

Conditional Logic-

(i) If Statements
(ii) If…else Statements
(iii) Conditional operator

If Statements-
The ‘if’ statement is the basic control statement that permit JavaScript to make decisions and execute statements conditionally
Syntax
The syntax for a basic if statement is as follows:
if (expression){
Statement(s) to be executed if expression is true
}
Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s) are executed. If the expression is false, then no statement would be not executed. Most of the times, you will use comparison operators while making decisions.
Example:
<html>
<body>
<script type= “text/JavaScript”>
var age = 20;
if( age > 18 ){
  document.write(“<b>Qualifies for driving</b>”);
}
</script>
</body>
</html>

If…else Statements-
The ‘if...else’ statement is the next form of control statement that allows JavaScript to execute statements in a more controlled way.
Syntax
The syntax of an if-else statement is as follows:
if (/* expression */){
Statement executed if expression is true
} else {
Statement executed if expression is false
}
Here JavaScript expression is evaluated. If the resulting value is true, the given
statement(s) in the ‘if’ block, are executed. If the expression is false, then the
given statement(s) in the else block are executed.
Example:
<html>
<body>
<script type= “text/JavaScript”>
var age = 14;
if( age > 18 ){
  document.write(“<b>Qualifies for driving</b>”);
}else{
  document.write(“<b>Does not qualify for driving</b>”);
}
</script>
</body>
</html>

Conditional operator-
In order to avoid the if-else hassle, simple logical comparisons can be utilised.
var adult = (age > 18) ? “YES” : “NO”;
In the above example, ? is a logical operator. The code says that if the value of age is greater than 18, then adult = YES; otherwise, adult = NO.
Basically, if the condition is true, the first argument is accessed and if the comparison/condition is false, the second argument is accessed.

Looping-
Loops are used for statements that need to be repeated. One or more variable in the loop changes so that you can check condition to stop. You can run the same code again and again, each time with a different value. There are three types of loops.

(i) For loop
(ii) For … in loop
(iii) While loop
(iv) Do while loop

For loop-
The easiest form of a loop is for statement. This one has a syntax that is similar to if statement, but with more options:
Syntax-
for (statement 1; statement 2; statement 3) {
code block to be executed
}

Statement 1- is executed before the loop starts.
Statement 2- defines the end condition when the loop had to stop.
Statement 3- is executed each time after the loop has been executed.
Example: for loop to print numbers from 1 to 5
<html>
<body>
<p id="output"></p>
<script>
var text = "";
var i;
for (i = 0; i < 5; i++) {
  text += “The number is “ + i + “<br>”;
}
document.getElementById(“output”).innerHTML = text;
</script>
</body>
</html>

For … in loop
A for...in loop is used to loop through an object’s properties. As we have not discussed Objects yet, you may not feel comfortable with this loop. But once you understand how objects behave in JavaScript, you will find this loop very useful.
Syntax
for (variablename in object)

statement or block to execute 
}

While loop-
While Loops repetitively execute a block of code as long as a specified condition is true.
while(condition){
    // do it as long as condition is true
}
Example: the loop in this example will repetitively execute its block of code as long as the variable i is less than 5:
var i = 0, x = “”;
while (i < 5) {
    x = x + “The number is ” + i;
    i++;
}

Do while loop-
The Do/While Loop is a variant of the while loop. This loop will execute the code block once before checking if the condition is true. It then repeats the loop as long as the condition is true:
do {
    // code block to be executed
} while (condition);
Note: Be careful to avoid infinite looping if the condition is always true!
Example: Print numbers less than 10 using do...while loop:
var i = 0;
do {   
document.write(i + “ “);
    i++; // incrementing i by 1  
} while (i < 10);
Note: i = i + 1 can be written i++.
Example: using this code you can access array with loop.
var myArray = [“aa”, “bb”];
// for-in loop
for (var i in myArray) {
  document.write(myArray[i]+”, ”); // output is : aa,  bb, 
}


Functions
A function is a group of reusable code which can be called anywhere in your program. This eliminates the need of writing the same code again and again. It helps programmers in writing modular codes. Functions allow a programmer to divide a big program into a number of small and manageable functions. Like any other advanced programming language, JavaScript also supports all the features necessary to write modular code using functions. You must have seen functions like alert() and write() in the earlier chapters. We were using these functions again and again, but they had been written in core JavaScript only once.

JavaScript allows us to write our own functions as well. This section explains how to write your own functions in JavaScript.
(i) Function definition
(ii) Function calling
(iii) Function parameters/arguments
(iv) Return statement

Function definition-
Before we use a function, we need to define it. The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces.
Syntax:
<script type= “text/JavaScript”>
function functionname(parameter-list)
{
statements
}
</script> Example:
Try the following example. It defines a function called sayHello that takes no parameters:
<script type= “text/JavaScript”>
function sayHello()
{
alert(“Hello there”);
}
</script>

Function calling-
Calling a Function To invoke a function somewhere later in the script, you would simply need to write the name of that function as shown in the following code.
<html>
<head>
<script type= “text/JavaScript”>
function sayHello()
{
document.write (“Hello there!”);
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type= “button” onclick= “sayHello()” value= “Say Hello”>
</form>
</body>
</html>

Function Parameter/Arguments-
Till now, we have seen functions without parameters. But there is a facility to pass different parameters while calling a function. These passed parameters can be captured inside the function and any manipulation can be done over those parameters. A function can take multiple parameters separated by comma. Example Try the following example. We have modified our “sayHello” function here. Now it takes two parameters. 
<html>
<head>
<script type= “text/JavaScript”>
function message(name, age)
{
  document.write (name + “ is “ + age + “ years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type= “button” onclick= “message(Neha, 7)” value= “some message”>
</form>
</body>
</html>

Return statement-
A JavaScript function can have an optional return statement. This is required if you want to return a value from a function. This statement should be the last statement in a function. For example, you can pass two numbers in a function and then you can expect the function to return their multiplication in your calling program. 
Example: following function that takes two parameters and concatenates them before returning the resultant in the calling program.
<html>
<head>
<script type= “text/JavaScript”>
function concatenate(first, last)
{
  var full;
full = first + last;
return full;
}
function secondFunction()
{
var result;
result = concatenate(Neha, Pant);
document.write (result);
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type= “button” onclick= “secondFunction()” value= “Call Function”>
</form>
</body>
</html>

Licensed under the Creative Commons Attribution Share Alike License 4.0

Made with eXeLearning (New Window)