This article was originally published at JavaScript functions
Function in programming is one of the most basic elements. It is a set of statements that perform some activity to get the result. In lots of cases, the action is performed using the data which are provided as input. The statements in the function are executed every time the function is invoked.
Functions are used to avoid repeating the same code. The idea is to gather tasks that are executed more than ones into a function and then call the function wherever you want to run that code.
Taking into consideration that function is such an important concept in Javascript I’m going to take a look at:
- defining a function,
- calling a function,
- return statement,
- parameters and arguments,
- arrow functions,
- self-invoking functions.
* To check the code execution open the console in the browser and try to execute the code ( if you are using Google Chrome right-click on the page and select Investigate)
Defining a function
We may define functions in two different ways.
Defining a function as a function declaration always starts with the function keyword. Then we set the name of the function, followed by parameters in the parenthesis or empty parenthesis if there are no parameters needed. Next, the statement comes closed in curly braces ({}). Let’s take a look at a code example:
function sayHi(name) {
return 'Hi'+name;
}
In the example above the function, the name is sayHi, and the parameter is (name). It’s also worth to know that function defined by declaration can be used before its defined because it is hoisted.
The other way to define a function is known as a function expression. This way, it’s possible to define a named and anonymous function as well. Also, hoisting doesn’t work in this case, so the function has to be defined first, and then it can be used. Most functions created with this method are assigned to a variable. Let’s take a look at the code example:
var sayHi = function (name) {
return 'Hi' + name;
}
In the example above function is assigned to variable sayHi, but the function itself doesn’t have a name, so we may call this function anonymous.
Calling a function
Now we know how we can define a function in Javascript with two methods, let’s find out how we can execute this function. Instead of calling the function, we may say invoke the function, which is the term for the process of execution.
So, how to call or invoke the function?
To call the function from the previous example, we have to start from the name of the function followed with parenthesis with parameters:
function sayHi(name) {
return 'Hi' + name;
}
sayHi('Peter');
In the code above we can see the name of the function sayHi followed by the expected parameter (Peter). Now the function should start and return Hi Peter string.
Return
In the example above, our function returned a string with the parameter. Every function needs to return a result if there isn’t any return statement defined the function will return undefined. Let’s check it on an example:
// With return
function calc(a, b) {
return a + b;
}
calc(1, 4) // returns 5
// Without return
function calc(a, b) {
a + b;
}
calc(1, 4) // returns undefined
In the example above the first function returns the result of math operation, and the other one doesn’t have the return statement, which means it will return undefined.
Parameters and arguments
Parameters and arguments are very ofter used alternately, but there is a difference between those two. Parameters are these names which we put into the parenthesis when defining a function, for example:
function name(param1, param2, param3) {
// statement
}
In the example above parameters are param1, param2, and param3. And in this case, there are no arguments yet.
Arguments are the values which are brought into the function by params. It’s what we put inside the function while invoking. Let’s see the example:
name('Mark', 'Peter', 'Kate');
In the example above the function from the previous example is called with the arguments now, and our arguments are param1 = Mark, param2 = Peter, param3 = Kate.
There is one more thing worth to say if we are on the parameters and arguments topic. Sometimes it happens we are not sure how many arguments we are going to pass to our function. Then we may use argument object and then pass as many arguments as we need. Let’s take a look at how it works in real examples:
// Define a function with one param
function calc(num) {
return 2 * num;
}
// Invoke the function with more params
calc(10, 5, 2);
In the example above, we defined a function with one parameter num and invoked it with more three arguments. Now the function will recognize num as the first passed an argument, but we can treat the param as an array-like object:
// Define a function with one param assuming it's an object
function calc(num) {
return 2 * num[0] * num[1];
}
// Invoke the function with more params
calc(10, 5, 2);
In this case, we defined a function with a parameter, which is going to be an object, and now we can use all the passed arguments. The function will do the following calculation according to the example above 2*10*5, taking a first and second argument.
Arrow functions
In ES6 arrow functions (=>) were introduced. An arrow function is mainly the shorter syntax for declaring function expression. It also pases the context so we can avoid binding. Let’s take a look at the code example:
sayHi = (name) => {
// statement
}
In the code example above, we defined an arrow function sayHi with name parameter without using the function keyword. In fact, having only one parameter, you can skip parentheses.
Self-invoking functions
There is also one type of functions in Javascript, the self-invoking functions. These are anonymous functions that are invoked immediately after completion of the definition. The self-invoking function is placed inside an additional parenthesis and with extra pair of parenthesis at the end. Let’s take a look at the code:
(function (num1, num2) {
return num1 + num2;
})();
In the example above, you can see that the self-invoking function is a normal anonymous function with an additional two pairs of parentheses.
Conclusion
In this article, I went through essential things about functions like defining functions using two different methods and invoking functions. I also explained the difference between parameters and arguments and described the usage of the arguments object. Besides, I went through arrow functions and self-invoking functions.
I hope this article will be useful to you. Try to create your own functions and play with different methods of defining and invoking.
Have fun with coding!
Thank you for reading,
Anna from Duomly
Top comments (20)
This statement is incorrect. Though arrow function can be used for this purpose, its primary purpose is sharing context (this) with parent scope, which makes such functions ideal for passing as arguments to when calling function that can then execute it.
Prior to arrow functions introduction we would have to bind a function context when passing it as argument, as context would be lost otherwise.
The over simplification of what arrow functions are is really concerning for an article with such an audacious title.
There’s no mention of the fact that this within an arrow function will always try to find the nearest defined this at that scope.
No mention of the fact that bind is still there and you can still bind arrow functions for achieving some sort of currying approach.
Also there’s no mention that the keyword arguments will behave just like the keyword this, and not like a regular function.
And last but not least, there’s no mention of some of the nicest things about the arrow functions which is the possibility of not using the return keyword
I vouch for a more humble name for the article.
Thanks for pointing that. You are right. I should mention this :)
Hi,
I agree with you, but I believe you may achieve the same result (I.e. use a closure for making sure the returned function gets invoked a single time) without the need of an IIFE, right?
Also, regarding the article, one more important thing about the arrow function is that it has a lexical ‘this’ bound to it’s parent scope.
IIFE is just that - a function that is invoked right after its definition.
Closure is the way JavaScript (the engine and the scope manager) handles the scope of variables, i.e. it detects whether the execution context of the function that gets returned has a reference to a variable defined in its parent scope.
Even if the garbage collector should have taken care of the parent scope (i.e. remove the references from the memory), due to the fact that the returned function also has reference to the same variable, it "closes" upon that variable, thus we have a closure.
Given your first example (the one with placing an order), I wrote a small repl that exemplifies a non-IIFE function that takes advantage of closure.
repl.it/@danielbokor/closure-example
tl;dr any function may take advantage of closures within JS, not just the ones that are an IIFE
Fwiw the pattern of using iife's in js to call pseudo-methods without separately instantiating an object using "new" is so clean to me. I'm a huge fan of the revealing module pattern. Your pattern is interesting. One thing that drives me nuts is I've yet to find an es6 pattern that matches the revealing module pattern in terms of being self contained and simplistic. Module exports are wacky to me, having to create a new file for each "object" and exporting functions individually in order to namespace them. And static methods in a class dont have access to constructor properties. The revealing module pattern hit on all of this...And if I wanted to put a bunch of iife's in one file and make said functionality available globally - yet namespaced - I could. To me it's like we went backwards with these es6 imports...it's become more procedural. just a gripe.
I agree with you, using the IIFE has a single execution context thus there is a single closure.
My point was that closure may exist without the need of using an IIFE.
Also, you are right: we both know how to use closure ;)
This post gave me a quick reminder of what I already knew in javascript. You have to believe that see it from your point of view. Refreshes the brain
you could continue this article with objects that have functions (methods) and how to use them.
also, didn;t you stop a function's run by using "return;" ? or im thinking of the functions that work on the DOM?
Stopping a function from running is when you return false; Returning false stops the function from executing further.
Well simplified. I appreciate the explanation
Is duomly.com is free to learn courses ? if yes ? why ? are the courses are in depth or just introduction?
Part of courses is free, and part is paid, some is for beginners and some is more advanced :)
thanks a lot,
i have always find that Self-invoking functions are complicated
Shouldn't we call the self-invoked function with the appropriate arguments?
Great article!
Thanks for the post; outbound link to your article needs attention.