Functions

 

Chapter: 24

User-defined Functions


JavaScript Functions


A JavaScript function is a block of code designed to perform a particular task.
The main advantages of using functions:
Code reuse: Define the code once, and use it many times.
Use the same code many times with different arguments, to produce different results.
A JavaScript function is executed when "something" invokes, or calls, it.

JavaScript Functions

What is a function?

Arithmetical term
Profession
A certain block of code that can be reused over and over again

Defining a Function


To define a JavaScript function, use the function keyword, followed by a name, followed by a set of parentheses ().

The code to be executed by the function is placed inside curly brackets {}.
function name() {
//code to be executed
}
JS
Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

Defining a Function

Add the corresponding keyword and symbols to create a function named "test".

test()


/* some code */


Calling a Function


To execute the function, you need to call it.
To call a function, start with the name of the function, then follow it with the arguments in parentheses.
Example:
function myFunction() {
alert("Calling a Function!");
}

myFunction();
JS
Always remember to end the statement with a semicolon after calling the function.

Calling a Function

Fill in the blanks to define and call the "hello" function.

hello() {

alert("Hi there");

}

();

Calling Functions


Once the function is defined, JavaScript allows you to call it as many times as you want to.
function myFunction() {
alert("Alert box!");
}

myFunction();
//"Alert box!"

// some other code

myFunction();
//"Alert box!"
JS
You can also call a function using this syntax: myFunction.call(). The difference is that when calling in this way, you're passing the 'this' keyword to a function. You'll learn about it later.

Calling Functions

How many times can the function be executed inside a web page?

1024
As many as needed
2

Chapter: 25

Function Parameters


Function Parameters


Functions can take parameters.
Function parameters are the names listed in the function's definition.

Syntax:
functionName(param1, param2, param3) {
// some code
}
JS
As with variables, parameters should be given names, which are separated by commas within the parentheses.

Function Parameters

What do you need to do to create a parameter?

Write a variable name in the parentheses
Use the "param" keyword
Use the "var" keyword

 Parameters


After defining the parameters, you can use them inside the function.
function sayHello(name) {
alert("Hi, " + name);
}

sayHello("David");
JS
This function takes in one parameter, which is called name. When calling the function, provide the parameter's value (argument) inside the parentheses.
Function arguments are the real values passed to (and received by) the function.

Using Parameters

When and how is the parameter used?

By placing the value before the function call
By placing the value before the function name
By calling the function and placing the value in the parentheses

Function Parameters


You can define a single function, and pass different parameter values (arguments) to it.
function sayHello(name) {
alert("Hi, " + name);
}
sayHello("David");
sayHello("Sarah");
sayHello("John");
JS
This will execute the function's code each time for the provided argument.

Function Parameters

Drag and drop from the options below to declare a function and call it, by passing "Test" as the argument:

function

myAlert(txt) {


alert("Hello " + txt);


}


myAlert
("Test")

;


Chapter: 26

Using  Multiple Parameters with Functions


Multiple Parameters


You can define multiple parameters for a function by comma-separating them.
function myFunc(x, y) {
// some code
}
JS
The example above defines the function myFunc to take two parameters.

Multiple Parameters

What character is used to separate parameters from each other?

;
,
&
:

Multiple Parameters


The parameters are used within the function's definition.
function sayHello(name, age) {
document.write( name + " is " + age + " years old.");
}
JS
Function parameters are the names listed in the function definition.

Multiple Parameters

What is the output of this code? function test(x, y) { if(x>y) { document.write(x); } else { document.write(y); } } test(5, 8);

5
85
8


Multiple Parameters


When calling the function, provide the arguments in the same order in which you defined them.
function sayHello(name, age) {
document.write( name + " is " + age + " years old.");
}

sayHello("John", 20)
JS
If you pass more arguments than are defined, they will be assigned to an array called arguments. They can be used like this: arguments[0], arguments[1], etc.

Multiple Parameters

Fill in the blanks to create a function alerting the sum of the two parameters.

myFunction(x, y)

{

alert(x
);

}

Multiple Parameters


After defining the function, you can call it as many times as needed.
JavaScript functions do not check the number of arguments received.
If a function is called with missing arguments (fewer than declared), the missing values are set to undefined, which indicates that a variable has not been assigned a value.

Multiple Parameters

How many times can the declared function be used?

Any
Maximum ten
Only once

Chapter: 27

The Return Statement


Function Return


A function can have an optional return statement. It is used to return a value from the function.

This statement is useful when making calculations that require a result.
When JavaScript reaches a return statement, the function stops executing.

Function Return

When is the "return" statement most frequently needed?

When you need to input data
When you need to add a pop-up window to the screen
When you need to make a calculation and receive the result

Function Return


Use the return statement to return a value.

For example, let's calculate the product of two numbers, and return the result.
function myFunction(a, b) {
return a * b;
}

var x = myFunction(5, 6);
// Return value will end up in x
JS
If you do not return anything from a function, it will return undefined.

Function Return

Where is the "return" statement placed?

At the end of the function description
Outside the curly braces
At the beginning of the function description

Function Return


Another example:
function addNumbers(a, b) {
var c = a+b;
return c;
}
document.write( addNumbers(40, 2) );
JS
The document.write command outputs the value returned by the function, which is the sum of the two parameters.

Function Return

Please enter the corresponding keyword to have the result of the function below displayed on the screen:

function substrNumbrs(first, second)

{

var result = first - second;

result;

}

document.write(substrNumbrs(10, 5));


Chapter: 28

Alert, Prompt, Confirm


The Alert Box


JavaScript offers three types of popup boxes, the AlertPrompt, and Confirm boxes.

Alert Box


An alert box is used when you want to ensure that information gets through to the user.
When an alert box pops up, the user must click OK to proceed.
The alert function takes a single parameter, which is the text displayed in the popup box.
Example:
alert("Do you really want to leave this page?");
JS
Result:contentImageTo display line breaks within a popup box, use a backslash followed by the character n.
alert("Hello\nHow are you?");
JS
Result:contentImage
Be careful when using alert boxes, as the user can continue using the page only after clicking OK.

The Alert Box

How many parameters can be accepted by the "alert" function?

3
1
2

Prompt Box


prompt box is often used to have the user input a value before entering a page.
When a prompt box pops up, the user will have to click either OK or Cancel to proceed after entering the input value.
If the user clicks OK, the box returns the input value. If the user clicks Cancel, the box returns null.

The prompt() method takes two parameters.
- The first is the label, which you want to display in the text box.
- The second is a default string to display in the text box (optional).

Example:
var user = prompt("Please enter your name");
alert(user);
JS
The prompt appears as:contentImage
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value. Do not overuse this method, because it prevents the user from accessing other parts of the page until the box is closed.

Prompt Box

Fill in the blanks to obtain the name of the user and alert it to the screen:

var name =
("Enter your name:");

alert(
);


Confirm Box


confirm box is often used to have the user verify or accept something.
When a confirm box pops up, the user must click either OK or Cancel to proceed.
If the user clicks OK, the box returns true. If the user clicks Cancel, the box returns false.

Example:
var result = confirm("Do you really want to leave this page?");
if (result == true) {
alert("Thanks for visiting");
}
else {
alert("Thanks for staying with us");
}
JS
Result:contentImage
The result when the user clicks OK:contentImage
The result when the user clicks Cancel:contentImage
Do not overuse this method, because it also prevents the user from accessing other parts of the page until the box is closed.

Confirm Box

In the "confirm" dialog box, "OK" returns true, and "Cancel" returns ...

false
undefined
true

Chapter: 29

Module 4 Quiz


The following code will result in what value? function test(number) { while(number < 5) { number++; } return number; } alert(test(2));



What is the output of the following expression? function multNmbrs(a, b) { var c = a*b; } multNmbrs(2, 6);

Nothing
12
24




What is the correct syntax for referring to an external script called "script.js"?

<script src="script.js">
<script name="script.js">
<script href="script.js">

What alert will display on the screen? function test(a, b) { if(a > b) { return a*b; } else { return b / a; } } alert(test(5, 15));


Chapter: 30

Code Project: Currency Converter


Currency Converter


You are making a currency converter app.
Create a function called convert, which takes two parameters: the amount to convert, and the rate, and returns the resulting amount.
The code to take the parameters as input and call the function is already present in the Playground.
Create the function to make the code work.

Sample Input:
100
1.1

Sample Output:
110

Note: Comment down your answer. 
Converting 100 at the rate of 1.1 is equal to 100*1.1 = 110.


Comments