You misunderstand how functions work. You do not write a function that adds 2 and 3 and returns 5. You must write a function that adds x
and y
and returns the result. I only use x
and y
as an example, it does not matter how you call them in your function.
In this example I write a function that multiplies x
and y
:
function multiply(x, y) {
var product = x * y;
return product;
}
x
and y
are parameters of multiply. Parameters are always variables like x
, never literal values like 2
. What use would a function have if it could only add 2 and 3 and no other numbers? If we use placeholders instead of numbers, we can add any number to any other number.
Now I can use that function and give it actual numbers: var test = multiply(2, 3);
test
is now 5
.
How to write a function:
You try to define a function like this: Function sum = function(2,3) {...};
, which is wrong.
There are two ways to define a function, either:
function sum(a, b) {
// some code
}
or
var sum = function(a, b) {
// some more code
};
Note that the second variants ends with a semicolon, while the first does not.
Where to use the semicolon
I find this hard to explain, but I will try. I think there are two basic rules:
-
Don’t end a { }
block with ;
Example:
function test() { // do something... }
-
End everything else with ;
Example:
var myNumber = 42;
A bit of a corner case is this already explained function definition:
var sum = function(p, q) { // do something... };
This is an anonymous function, because it does not have a name. It is assigned to the variable sum, but that is not the same as writing function sum(p, q)
. Anonymous functions don’t count as blocks when it comes to semicolons, so you should still add one at the end of the line.