You are on page 1of 10

FUNCTIONS

JAVASCRIPT
INTRODUCTION TO FUNCTION
• Block of code that perform a specific task and
returns a value.
• A function can take zero or multiple parameters.
• Parameters/ arguments are tools by which data can
be passed to a function.
BUILT-IN FUNCTIONS
• A function can be Built-In functions which are
defined by language itself.
• Ready to use component which can be used by the
user/programmers any where in the code. Like
– parseInt() = Used to convert a string value to an integer.
– parseFloat() = Used to get first floating point number
contained in the string or 0 if the string does not begin
with a valid floating point number.
USER DEFINED FUNCTIONS
• Allows a user to create custom or tailored block of
code according to the requirements.
• It need to be declared and coded by the user
explicitly.
• A function to perform its job need to be called.
• Function can accept information in the form of
inputs and gives output as return value.
DECLARING A FUNCTION
• A function name to be given
• A list of parameters/ arguments that will accept
values passed to the function when called.
• Block of code that defined what the function does.
• Syntax
function function_name(parameter1, parameter2)
{
block of javascript code
}
• Function can be declared any where within an
HTML file.
• They are defined within the <head>…</head> tag.
• A functions needs to be parsed before being
invoked or called otherwise it will lead to an error.
PARAMETERS AND ARGUMENTS
• Parameters can be passed to a function by listing
them in the parenthesis followed by the function
name.
• Functions can have multiple parameters separated
by commas.
• The functions has been coded to accept multiple
parameters.
CALLING A FUNCTION
• It can be by passing a static value like
printname(“Bob”);
• It can be by passing a variable value like
var user=“Bob”;
printname(user);
VARIABLE SCOPE
• Any variable used in function with var it will be
having a scope limited to the function.
• It is available to all statements within the javascript
if declared outside the body of the function.
• If a local variable is declared within a function has
the same name as an existing global variable, then
within the function code, that variable name will
refer to the local variable and not the global
variable.
RETURN VALUE
• User defined and built-in functions can return values.
• It can be done using return statement in functions.
• It can return a single value. Like
– function cube(number)
{
var cube=number*number*number;
return cube;
}
– function cube(number)
{
return number*number*number;
}

You might also like