Functions and Control Structures

Functions and Control Structures

Function

JavaScript functions are used to perform operations. There are mainly two advantages of functions:

  • Code reusability: We can call a function several times, so it saves coding.
  • Less coding: It makes our program compact. We don’t need to write many lines of code each time to perform a common task.

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, and a statement block surrounded by curly braces.

Calling a Function

To invoke a function somewhere later in the script, we simply need to write the name of the 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>  

Control Structures

Control structure defines the flow of control within the program.Below are the statements:

  1. if statement: It evaluates the content only if expression is true.
Syntax
if (expression)  
{  
Statement(s) to be executed if expression is true  
}
  1. if-else statement: It allows JavaScript to execute statements in a more controlled way.
Syntax
if (expression){  
Statement(s) to be executed if expression is true  
}else{  
Statement(s) to be executed if expression is false  
}
  1. if-else-if statement: It is an adavance form of if-else statement that allows JavaScript to make correct decision out of severa conditions.
Syntax
if (expression 1){  
Statement(s) to be executed if expression 1 is true  
}else if(expression 2){  
Statement(s) to be executed if expression 2 is true  
}else if (expression 3){  
Statement(s) to be executed if expression 3 is true  
}else{  
Statement(s) to be executed if no expression is true
}

Switch case

The basic syntax of the switch statement is to give an expression to evaluate and several different statements to execute based on the value of the expression. The interpreter checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used.

Syntax
switch (expression){  
case condition 1: statement(S)  
break;  
case condition 2: statement(s)  
break;  
.  
.  
.  
case condition n: statement(s)  
break;  
default: statement(s)  
}