| |
Passing Parameters
Functions may also be called with values, known as parameters, which may be used inside the body of the function. The function in which values are passed, is known as 'parameterized' function. Values are passed to the function by listing them in the parentheses following the function name. Both user-defined functions and built-in functions can accept parameters, process them and return values. During declaration, a function needs to be informed about the number of values that will be passed. Parameters exist only for the life of the function.
| Example |
var x;
function cube( x )
{
document.write ( " Enter the number: " + x );
var cube = x * x * x;
} |
Calling Function
Once a function has been declared, it can be called (or invoked ) in a script anywhere in an HTML page. Function is usually called in the BODY tag of the HTML page, and you usually pass a parameter into the function. The number of parameters being passed should be equal to the number of arguments the function has.
| Example |
<html>
<head>
<SCRIPT LANGUAGE = "JavaScript">
var num;
function cube(num)
{
return num * num *num;
}
</SCRIPT>
</head>
<body>
{
document.write(cube(5));
}
</body>
</html> |
| |
| |
| Summary |
| |
In this chapter you have learnt:
- How looping helps controlling certain operations.
- Different loop structures applicable at different situations.
- Easier decision making through conditional constructs.
- Skipping the loop construct through Break statement.
- Accessing built-in functions.
- Declaring and calling user-defined functions.
|
| |
| |
| Review Questions |
| |
Fill in the Blanks
- ------- allows you to iterate a code in the program.
- ------- statement tests single expression, multiple times.
- The loop construct can be skipped using------- statement.
- Functions are declare and defined using the keyword----------.
Solutions
- Loop
- Switch
- break
- function
True or False
- JavaScript functions may have no parameters.
- In the For loop, update expression can be negative.
- Do-while will always execute a block of code, at-least once.
Solutions
- True
- True
- True
| Exercise |
- Calculate factorial of a number.
- Calculate power to a number through function
- What is the difference between While and Do-while Loop.
|
| Solution |
- View Code View Runtime
- View Code View Runtime
-
Do-while loop will always execute a block of code once, no matter the condition is valid or not, whereas while loop will execute the statements only if the condition is true
|
|
| |
| What's Next |
The next chapter will acquaint you with the concepts of JavaScript Events. The chapter will
further elucidate various
event handlers available in JavaScript
and how to pop-up dialog boxes in the window.
Hop over to the next chapter to get the close-up of JavaScript Events and Dialog boxes.
|
| |
|
|