JavaScript 101: Functions
This article is part of the JavaScript 101 series, you can find the previous part on the following link: JavaScript 101: Conditionals and Loops.
Into Functions
A function is a set of one or more statements that take inputs, do some specific computation and produce output. The idea behind the functions is to not repeat writing the same code over and over again for different inputs. JavaScript is a programming language that supports the use of functions, there are already build in functions like: console.log()
, alert()
, etc..
A function in javascript can be created using the keyword function, here is the syntax to define a function:
function functionName(param1, param2){
// Function body
}
If we want to create a function in JavaScript, first we have to use the keyword function, the second part is the name of the function which can be what we want, commonly is used a camel case naming convention, the third part is the function and parameters within parenthesis(param1 and param2), and lastly is the body of the function inside the {}
.
Function parameters or arguments are additional information passed to the function. The parameters or the arguments are passed to the function within parentheses and are separated by commas. A function in JavaScript can be without parameters too, but also can have any number of parameters too.
After defining a function, the next step is to call the function. We can call a function by using the function name and the parameters enclosed between parenthesis. Here is the syntax to call the function:
functionName(param1, param2);
A function also can return a value at the end of the body. If we want to return some value from the computation we need to use the return keyword in the statement, here is the syntax to return a value:
function functionName(param1, param2){
// Function body
return param1 + param2;
}
The value can be returned to the variable sum in the function declaration, you can check on the next example:
var sum = functionName(param1, param2);
Functions Scope
Each function creates a new scope in JavaScript, scope determines the visibility of these variables(you can go back and read more about variables here). Variables that are defined inside a function are not accessible from outside the function.
Functions are very important for writing clean and good structured code.
Next part: JavaScript 101: Scope and Closures.
Tweet