Defining a function
JavaScript Function Syntax A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). A Function is much the same as a Procedure or a Subroutine, in other programming languages. With functions you can use the same code many times with different arguments, to produce different results. A function definition is just a regular variable definition where the value given to the variable happens to be a function var square = function(x) { return x * x; }; console.log(square(12)); // 144
Parameters and scopes
The parameters to a function behave like regular variables, but their initial values are given by the caller of the function, not the code in the function itself. An important property of functions is that the
variables created inside
of them, including their parameters,
are local
to the function. function myFunction( ) { alert( "My Function" ); }
Nested scope
JavaScript distinguishes not just between global and local variables. Functions can be created inside other functions, producing several degrees of locality. When JavaScript reaches a return statement, the function will stop executing.
Return values
Quite often, you'll want to get something back from your functions. This value that you want to get back is called the return value in Javascript. The return value can be a string of text, a number, a Boolean value, or even objects. But they only return one value. You can pass values over to your functions. These values are called
, and they go between the round brackets of the function. If you have more than one value to pass over, you separated them with commas.
Functions as values
Function variables usually simply act as names for a specific piece of the program. Such a variable is defined once and never changed.
Declaration notation
There is a slightly shorter way to say var square = function. The function keyword can also be used at the start of a statement, as in the following: function square(x) { return x * x; } < script type="text/javascript" > function sayHello(name, age) { document.write (name + " is " + age + " years old."); } function square(number) { return number * number; }
Function () Constructor
The function statement is not the only way to define a new function; you can define your function dynamically using Function() constructor along with the new operator.
Function Literals
JavaScript 1.2 introduces the concept of function literals which is another new way of defining functions. A function literal is an expression that defines an unnamed function.