Projects Are About Humans. Deal With That!

Archive for November, 2007

Functions in JScript

When dealing with a large script, you will very often need to write additional "sub-scripts" that are called by the main script several times. This will save you a lot of time from rewriting the same piece of code every time you need it in the main script. Such "sub-scripts" are called functions. Their main purpose is to take some values, do some actions based on those values, and then return a new result. This way, you won't have to rewrite the pieces of code again and again, but merely call a function that implements that code.

Most of the times you will need to pass information to a function; you can do this by enclosing the information in parentheses after the function's name. These arguments - which is the name of the passed information - are separated by commas. But there are times when you won't need to specify any arguments - you will still need to add the parentheses after the name of the function, but nothing else within them.

There are two types of functions: built-in functions (functions that are built into the language) and user-defined functions (functions that are defined by the user). There are a lot of built-in functions, each one having its purpose, for example the eval() function that takes a string as an argument and evaluates the expression the string holds:

result = eval("(5 * 5) + 3″); //assigns the value 28 to the variable "result"

But the most important thing about functions is creating them on your own. To define a function you must first use the function statement and insert the function's name and arguments, then you must add the actual code. You can use "return" to assign a value to the function's result.

function make_sum(a, b, c) //don't add a semicolon in the end!

{

result = a + b + c;
return result;

}

As you can see, we assign the sum of the arguments a, b and c to the variable result, then we return the value this variable holds.

The result variable is a local variable, which means that it is used only within this function. Local variables are created and then destroyed every time the function is called, and they cannot be accessed by other functions outside it.

No comments

« Previous Page