Functions
Like every programming language, JavaScript also supports the use of functions. JavaScript functions are the main blocks of code designed to perform a particular task. Functions allow the code to be called many times without repetition.
Function Declaration
We can create functions in JavaScript using a function declaration that looks like this:
As you see in the example the function keyword goes first, followed by the name of the function, then we put a list of parameters between the parentheses and finally we place the code of the function between curly braces.
Beautified JavaScript:
function name(parameters) {
//body...
}
We can call our new function by its name: show() which executes the code of the function. As a result, we see the message two times:
function show() {
console.log('Welcome to Web!');
}
show();
show();
This example shows one of the main purposes of functions: to avoid code duplication. If we want to change the message, we just need to modify the code in the function which outputs it.
Local variables
A variable declared inside a JavaScript function is only visible inside that function. It can only be accessed from within the function.
Example of the local variable:
Outer variables
A function can also evaluate an outer variable.
Example of the outer variable:
We use an outer variable only if there is no local one. If some same-named variable is declared inside the function then the outer one is ignored.
Example of the function that uses the local variable:
Parameters
We can proceed with random data to functions using parameters. In this example, the function has two parameters: arg1 and arg2:
function show(arg1, arg2) { // arguments: arg1, ag2
console.log(arg1 + ' to ' + arg2);
}
show('Welcome', 'Web!'); // Welcome to Web! (*)
The function uses (*) when the given values are copied to local variables arg1 and arg2.
In this example, we have a variable arg1 and proceed with it to the function. Note that the function changes arg1, and the change is not seen outside, as a function always gets a copy of the value:
function sum(arg1, arg2) {
arg1 = arg1++; // change "arg1"
let sum = arg1 + arg2;
console.log(sum);
}
let arg1 = 2;
sum(arg1, 3); // result: 5
console.log(arg1); // 2
The value of "arg1" is the same, the function modified a local copy.
Default values
Parameters of functions default to undefined if a parameter is not defined. But sometimes it might be useful to set a different default value.
function show(arg1, arg2) { // arguments: arg1, ag2
console.log(arg1 + ' to ' + arg2);
}
show("Welcome", "Web");
For example, we can call the aforementioned function show(arg1, arg2) with a single argument:
show("Web"); // undefined to Web
That is not an error. This kind of a call would output "undefined to Web", but as there is no text it is supposed that text === undefined.
If we want to use a “default” in this case, we can specify it after =:
function show(arg1, arg2 = "Web!!") {
console.log(arg1 + " to " + arg2);
}
show("Welcome"); // Welcome to Web!!
So if the text parameter is not passed, it will get the value "Web!!", which is a string in this case, but it can be a more complex expression. That expression is only evaluated and assigned if the parameter is missing and this is also possible:
function show(arg1, arg2 = anyFunction()) {
//if no text given a anyFunction() only executed
// its result becomes the value of text
}
A default parameter can be evaluated every time the function is called without the corresponding parameter.
In the presented above example, anyFunction() is called every time show() is called.
Default parameters old-style
Old editions of JavaScript did not assist default parameters, that is why there are alternative ways that you can meet mostly in the old scripts.
For example, a clear check for being undefined:
Or the || (OR) operator:
function show(arg1, arg2) {
arg2 = arg2 || 'text not specified';
//if the arg2 is false, then the text gets the default value
...
}
Returning a value
A function can return a value to the calling code as the result. In this simple example a function multiplies two values:
function multiply(a, b) {
return a * b;
}
let result = multiply(2, 3);
console.log(result); // 6
We can place the directive return in any place of the function. The function stops when the execution reaches it, and the value is returned to the calling code.
There may be many incidents of return in a single function:
function checkNumber(number) {
if (number == 10) {
return true;
} else {
return false;
}
}
let number = prompt('Guess the number?', '');
if (checkNumber(number)) {
console.log('it’s true');
} else {
console.log('it’s false');
}
We can use the return directive without a value, which causes the function to exit immediately.
Example of the return without a value:
function showNumber(number) {
if (!checkNumber(number)) {
return;
}
console.log("Showing the number");
//...
}
In the presented above code, if checkNumber(number) returns false, showNumber() will not move to the alert.
When a function does not return a value, it is the same as when it returns undefined and an empty return.
function doNothing() { /* empty */ }
console.log(doNothing() === undefined); // true
For a long expression in return, it might be attractive to put it on a separate line:
return
(long + expression + or + whatever * f(x) + f(y))
But that does not work, because JavaScript accepts a semicolon after return and that will work the same as:
return;
(long + expression + or + whatever * f(x))
As you see it effectively becomes an empty return.
When we want the returned expression to wrap across multiple lines, we need to start it at the same line as a return or put the opening parentheses there like this:
return (
long + expression +
or +
whatever * f(x)
)
And it will work like we expect it to.
Naming a function
Functions are actions and their name is generally a verb. The name should be brief, accurate, describing what the function does.
It is a worldwide practice to start a function with a verbal prefix which more or less describes the action.
For example, functions that start with "show" used to show something.
Function starting with…
- "get…" – return a value,
- "create…" – create something ,
- "calc…" – calculate something and so on.
Examples of such names:
showMessage(..) // shows a message
getNumber(..) // returns the age (gets it somehow)
calcMultiply(..) // calculates a multiply and returns the result
createForm(..) // creates a form (and usually returns it)
checkPermission(..) // checks a permission, returns true/false
With the function name, we can understand what kind of work it does and what kind of value it returns.
Two independent actions usually do two functions, even if they are usually called together.
Ultrashort function names
Very often used functions sometimes have ultrashort names.
For instance, the jQuery framework defines a function with $. The Lodash library has its core function named _.
But generally functions names should be brief and descriptive.
Functions == Comments
As we mentioned above, functions should be short and do exactly one thing. But when that thing is big, maybe it is worth it to break the function into a few smaller functions.
The reason is that the separate function is not only easier to test and debug but also it is very existence is a great comment.
Let’s compare the two functions showEven(num) where each one outputs even numbers up to n.
0 Comments
CAN FEEDBACK
Emoji