The aim of this post is to introduce people quickly into the wonderful world of JavaScript functions. Functions are one of the core aspects in JavaScript.
A function is a set of statements that performs a task or calculates a value. Once you start to get your head around very basic JavaScript you will certainly need to invest some time into learning the in’s and out’s of functions. Basically, anytime you find yourself repeating code, but modifying the small parts, you could probably use a function.
The D.R.Y. (Don’t Repeat Yourself) principle is really important in programming.
The Beginning of a Function
var functionName = function( parameter ) {
code;
};
functionName();
Think of a function as having five parts:
- Declare the function using
var
, and then give it a name - Then you must use the
function
keyword to tell the computer that you are making a function - The bit in the parentheses is called the parameter. Think of it as a placeholder word that we give a specific value when we call the function
- Then write your block of reusable code between
{ }
. Every line of code in this block must end with a;
- Then we need to execute the function by calling it
If you find yourself struggling to get your head around how the function can be structured it is often handy to think about the ‘small part’ that you find yourself modifying will be the parameter. And the part that you keep repeating will be the code in the reusable block – the code inside { }
.
Hopefully you have had your “ah ha” moment already but if you haven’t then hopefully this example will push you over the edge.
Let’s say you want to print out a message to about the days weather.
console.log("Today is raining");
console.log("Today is sunny");
console.log("Today is overcast");
console.log("Today is snowing");
and so on…
The above is a perfect opportunity to create a simple function.
var todaysWeather = function( conditions ) {
console.log("Today is " + conditions);
};
todaysWeather('sunny');
Today is sunny
The function todaysWeather
takes one argument, called conditions
. The function consists of one statement that prints out todays weather to the console.
Return
So far in all the examples, none of them have used the return
statement. The return statement is commonly used inside functions. The return statement specifies the value returned by a function, which is the value of the argument values passed in when the function is invoked.
return X;
A return statement can only be used within the the body of a function. If not, a syntax error will be thrown. When the return statement is executed, the passed in expression is evaluated and returned as the value of the function. The function stops executing when the return statement is executed.
To get an idea of the return statement we could do something like this.
var timesTwo = function(number) {
return number * 2;
};
var newNumber = timesTwo(2);
console.log(newNumber);
4
Four ways to use return:
- Return the parameter
- Return a variable’s value if the variable has been declared inside the function
- If the parameter is a number, do the calculations with that parameter and you can return the value
- If the parameter is a string, use keywords like
.length
or.substring()
and you can return the value
Function Declaration or Function Expression?
If you have already been writing JavaScript you might have also come across functions written a little differently.
Maybe like this:
function addTwoNumbers(a, b) {
return a + b;
}
This syntax is called a function declaration. The function is given a name.
Or like this:
var addTwoNumbers = function(a, b) {
return a + b;
};
This syntax is called a function expression. The function is assigned to a variable. By doing this, we can call our function by using the name of the variable.
My advice is to use the the function expression syntax if you don’t understand a feature called hoisting. Hoisting is not really an appropriate topic for an introduction post, but if you have time I would highly recommend reading more about it on Angus Crolls blog.
Its also worth noting that when you assign a function to a variable (function expression) and want to call that function you need to use ()
on the end of it.
var myFunction = function() {
return "hi";
}
myFunction; // returns "function() {return "hi"};"
myFunction(); // returns "hi"
Scope
Variables that are declared inside a function with a var
statement are only available inside of the function. If you want your variable to be available anywhere in your code, declare without a var
statement and outside of your function. Doing the latter isn’t something that I would recommend unless you intended it to be in the global scope.
var functionName = function( ) {
var scopeName = 'scope';
};
functionName();
console.log( typeof scopeName );
undefined
The above logs undefined to the console because the variable ‘scopeName’ is not a global variable.
Variable scope is one of the fundamental concepts of JavaScript.
Three ways to help with variable scope:
- You should almost always declare variables with a
var
statement - Variables declared inside of a
function
using avar
statement are not available outside of that function - Variables declared without a
var
statement are always global
Going Forward
Functions are just one aspect of JavaScript but are a very important part. By no means the above covers everything that there is to know about functions, actually the complete opposite. It is just a brief overview. I encourage you to get out of your comfort zone and dive deeper.
Happy coding!
I’d say your five part of a JavaScript function is missing something fundamental.
var variableName = function functionName(parameterName) {
// Here goes the code ...
};
It’s very important to understand that function () {} is an anonymous function without a name (see the space between the language keyword function and the parentheses). It’s good style to name your function (very good for stack traces) and it’s even better style to type that space between the keyword and the parentheses.
Hi.
Thank you for this tuto, you make my day!
I will never forget that:
==> “Variables that are declared inside a function with a var statement are only available inside of the function. If you want your variable to be available anywhere in your code, declare without a var statement and outside of your function.”
Hi,
Great post!
I need to fire/deploy an image pixel/tag using if statements, what would be the best way in doing this?