Functions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

Functions

What is function?
• Functions are very important and useful in any programming language as they make the
code reusable.
• A function is a block of code which will be executed only if it is called.
• If you have a few lines of code that needs to be used several times, you can create a
function including the repeating lines of code and then call the function wherever you
want.
• Functions are the main “building blocks” of the program. They allow the code to be
called many times without repetition.
How to Create a Function in JavaScript
Use the keyword function followed by the name of the function.
After the function name, open and close parentheses.
After parenthesis, open and close curly braces.
Within curly braces, write your lines of code.
Function declaration
function functionname(){

lines of code to be executed

}
Example
function myFunction()
{
document.write("This is a simple function.");
}
myFunction(); - function call

You need to call function in order to execute code written in it.


Naming a function
Functions are actions. So their name is usually a verb. It should be brief, as accurate as
possible and describe what the function does, so that someone reading the code gets an
indication of what the function does.
Examples of such names:
showMessage()
clickButton()
calcSum()
logIn()
logOut()
Function with arguments
A function can have one or more parameters, which will be supplied by the calling code
and can be used inside a function.

function ShowMessage(firstName, lastName) {


document.write("Hello " + firstName + " " + lastName);
}
ShowMessage("Steve", "Jobs");
ShowMessage("Bill", "Gates");
ShowMessage(100, 200);
Function with arguments

You can pass less or more arguments while calling a function. If you pass less arguments
then rest of the parameters will be undefined.
If you pass more arguments then additional arguments will be ignored.
Example
function ShowMessage(firstName, lastName) {
document.write("Hello " + firstName + " " + lastName);
}
ShowMessage("Steve", "Jobs", "Mr.");
ShowMessage("Bill");
ShowMessage();
Function with default values
function showMessage(from, text = "no text given") {
document.write( from + " " + text );
}
showMessage("Ann");

Now if the text parameter is not passed, it will get the value "no text given"

Here "no text given" is a string, but it can be a more complex expression, which is only
evaluated and assigned if the parameter is missing.
Global and Local variables
Variables hold the data or information which can be changed anytime. JavaScript use reserved
keyword var to declare variables. In JavaScript, there are two types of variable and also it tells you
where in your program you are allowed to use the variables and functions that you’ve defined.
Local Variable:
When you use JavaScript, local variables are variables that are defined within functions. They have
local scope, which means that they can only be used within the functions that define them.
Global Variable:
In contrast, global variables are variables that are defined outside of functions. These variables have
global scope, so they can be used by any function without passing them to the function as parameters.
Global and Local variables
Within the body of a function, a local variable takes precedence over a global variable with the same
name. If you declare a local variable or function parameter with the same name as a global variable,
you effectively hide the global variable.

var myVar = "global"; // Declare a global variable


function checkScope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
Global and Local variables
A variable that is declared inside a function definition is called local and has scope to that function
only.
var a = "Dot Net Tricks !"; // Global variable.
function Show() {
var a = "Hello World !"; // A local variable is declared in this function.
document.write("Value of 'a' inside the function " + a); //Hello World !
}
document.write("Value of 'a' outside the function : " + a); //Dot Net Tricks !
A function may access outer variables. But it works only from inside out. The code outside of the
function doesn’t see its local variables.
Global and Local variables
A JavaScript global variable is declared outside the function. It can be accessed from any
function.
var value=50; //global variable
function a(){
document.write(value);
}
function b(){
documet.write(value);
}
Return Value
A function can return zero or one value using return keyword.
function sum(val1, val2) {
return val1 + val2;
};
var result = sum(10,20); // returns 30
function Multiply(val1, val2) {
( val1 * val2);
};
result = Multiply(10,20); // undefined

document.write(result);
Return Value
There may be many occurrences of return in a single function. For instance:
function checkAge(age) {

if (age > 18) {

return true;

} else {

return false;

var age = 17;

if ( checkAge(age) ) {

document.write( 'Access granted' );

} else {

document.write( 'Access denied' );

}
Function Expression
JavaScript allows us to assign a function to a variable and then use that variable as a
function. It is called function expression.
var add = function sum(val1, val2) {
return val1 + val2;
};

var result1 = add(10,20);


var result2 = sum(10,20); // not valid
Summary
Values passed to a function as parameters are copied to its local variables.
A function may access outer variables. But it works only from inside out. The code outside of the
function doesn’t see its local variables.
A function can return a value. If it doesn’t, then its result is undefined.
A name should clearly describe what the function does. When we see a function call in the code, a
good name instantly gives us an understanding what it does and returns.
Examples
function sum(a, b) {
return a + b;
}
var result = sum(1, 2);
document.write( result ); // 3
Examples
Write a function min(a,b) which returns the least of two numbers a and b.
function min(a, b) {
if (a < b) {
return a;
} else {
return b;
}
}
document.write(min(2, 5) + "<br>");
document.write(min(3, -1));
Examples
function concatenate(first, last) {

var full;
full = first + “ “ + last;
return full;
}
function secondFunction() {
var result;
result = concatenate('Zara', 'Ali');
document.write (result );
};
secondFunction();
Examples
function greet(name)
{
return "Hello " + name + "!";
}
document.write(greet("Eric"));
Examples
Define a function called multiplyFive which accepts a number and returns that number
multiplied by 5.
function multiplyFive(number) {
return number * 5;
}
document.write(multiplyFive(3));
document.write(multiplyFive(5));
Examples
Examples

You might also like