Every line of javascript we write is called a statement, and when we write multiple statements together, we create a procedure.
An example of a procedure could be if... else
statements, which we have covered previously.
if (condition) {
console.log("Something");
} else {
console.log("Something else");
}
When we write javascript directly into a file or inside a <script>
tag - the entire file counts as one procedure, running from left to right, top to bottom - this is what we call synchronous code.
This is very useful when starting with javascript; however, as the complexity of tasks increases, this becomes unsustainable. We need to define smaller, more manageable procedures, which are what functions are. Functions are groups of useful statements that combine into re-useable procedures to which we assign a name.
Functions are crucial to writing effective javascript, and they exist to make your code make more sense to you and others.
Understanding functions is essential, but it will take time to get used to them - that will happen as you use them more and more.
Here we only introduce them. In the JavaScript 1 course, we will look at them in more depth.
We have already been using functions, console.log()
is a function and so are toLowerCase()
and toUpperCase()
.
Our first function
To use a custom function, we first need to declare it.
Declaring a function means creating it. We use the function
keyword and a name of our choice to declare it. Remember that a good function name is one that describes that task without someone needing to read the code to understand it.
// declare the function
function logWord() {
// the code we want the function to run goes here
}
Above, we’ve declared a function called logWord
.
Like other variables, functions can be called anything. Give your functions meaningful names. Functions with the name
hi
orfunction1
are not well-named functions. Here are the rules to guide you when naming a function:
- Use Descriptive Names: A function name should clearly describe what the function does. This helps other developers (and your future self) understand the purpose of the function at a glance. For example,
addTwoNumbers
is better than ‘sum’ - Use CamelCase: In JavaScript and many other programming languages, the convention is to use camelCase for function names. This means starting with a lowercase letter and capitalizing the first letter of each subsequent word e.g.
signupUser
,calculateTotalAmount
, etc. - Start with verb: Function names should start with a verb that indicates the action the function performs, as functions usually perform operations or actions e.g.
getId
,makePayment
, etc. - Avoid Special Characters: Use letters, numbers, and underscores. However, do not start a function with a number, as this is generally not allowed in most programming languages and can cause syntax errors.
- Keep It Concise: While being descriptive, try to keep the function name concise. Do not use long names, as they can be cumbersome to use and read.
Don’t be afraid to use long names for functions if you can’t think of a short one.
function logWordOneHundredTimes()
is fine, as long as that’s what it does!
The contents of a function (code that can be run) lives between the curly braces { }
. We don’t have any code in the example above (the logWord function) except a comment, so our function doesn’t do anything at the moment. We will look at the purpose of the parenthesis (round brackets) ()
a bit later.
Let’s make our function do something, log a string to the console:
function logWord() {
console.log("one");
}
The code inside the function won’t run until we call
(or execute
or invoke
*) the function.
\* In programming, similar actions or techniques often have different names, which can be confusing when different names refer to the same thing. When we mention alternative names for things, it’s because that is what they might be called in other learning materials you may read or watch.
Without calling the function, the JavaScript engine knows about it but won’t execute the code inside the function.
We call a function using its name and round brackets ()
.
// declare the function
function logWord() {
console.log("one");
}
// call the function
logWord();
Now the logWord
function will run, and one
will be logged to the console.
Notice that we don’t use the
function
keyword tocall
the function. We only use thefunction
keyword whendeclaring
the function.
Arguments
Our logWord
function isn’t very useful at the moment, as it will always just console log the word “one”
. We may as well have just written the console.log()
out directly without declaring and calling a function.
We can make the function far more useful by passing variables into it so that the code inside the function can use them.
The variables that we pass into functions are called arguments
. We place them inside the ()
.
When we call
console.log("some value");
the value we want to log is an argument passed to thelog()
function.
Let’s add an argument
called theWord
to the logWord
function:
function logWord(theWord) {
console.log("one");
}
logWord();
The code inside the function is still just logging one
, though.
We can use the variables we pass in, the arguments
, inside the function just like any other variable. Let’s pass in a value as the theWord
argument and then log that value:
function logWord(theWord) {
console.log(theWord);
}
logWord("hello");
Run the code above, and you will see hello
gets logged.
You will often hear about
parameters
. Technically, the values passed into the function are calledparameters
, and the variable names inside the()
are calledarguments
. We will call botharguments
for simplicity’s sake.
Change the value you pass in:
function logWord(theWord) {
console.log(theWord);
}
logWord(50);
Now 50
will get logged.
Whatever you pass in as the value will get logged as long as you use the argument
’s correct name.
function logWord(theWord) {
console.log(theWord);
}
logWord(true);
true
will get logged.
If we changed the code to this
function logWord(theWord) {
console.log(word);
}
logWord("hello");
We will get an error, as the argument (the variable) is called theWord
, but we are trying to log the variable word
. The variable word
doesn’t exist in this function.
Always make sure you are using the correct argument
names in your function code.
Mulitple arguments
Functions can have zero, one or more arguments. Let’s write a function with two arguments:
// declare a function with two arguments
function AddTwoNumbers(number1, number2) {
let sum = number1 + number2;
console.log(sum);
}
// call the function and pass two arguments in
AddTwoNumbers(3, 4);
// 7
Returning from a function
To return a value from inside a function, we use the keyword return
.
For example, we can return the sum
variable from the AddTwoNumbers
above like this:
function addTwoNumbers(number1, number2) {
let sum = number1 + number2;
return sum;
}
No code after a
return
keyword will run. As soon as areturn
keyword is encountered, the function will exit with the value provided.
function doubleNumber(number1) {
let double = number1 * 2;
return double; // Execution stops here
console.log("This will never run");
}
We can assign what is returned from a function to a variable like this:
let result = addTwoNumbers(3, 4);
The purpose of calling a function is ultimately to change the state
of a webpage or to perform a calculation.
When performing a calculation, the function
must respond with the result once it has finished running. Otherwise, it will not be useful.
When changing state, a return value is not always necessary - however, it is a good practice to provide one anyway.
All functions return a value, even if that value is falsy like
undefined
,null
,0
or""
.
function pureFunction(input) {
let output = input;
return output;
}
function impureFunction(input) {
window.output = input;
}
let testA = pureFunction(1);
console.log(testA === 1);
let testB = impureFunction(1);
console.log(testB === undefined);
Functions that do not explicitly set a return value are generally called “convenience methods”.
This video is an introduction to functions and includes a more practical example of using functions than simply logging variable values.
Watch on Vimeo Code from the videoFunction Definition
Understanding the various ways to define functions in JavaScript is crucial, as it helps you comprehend how your code is executed and aids in debugging. There are multiple ways to define a function in JavaScript, and for comparison, we will use the same examples.
- Anonymous Function
- Function Declaration
- Function Expression
- Arrow Function
Anonymous Function
A function without a name, often used as a callback.
setTimeout(function() {
console.log("This runs after 1 second");
}, 1000);
Function Declaration
A named function that can be called anywhere in the code. It is declared with the keyword function follow by the name of the function and then a parenthensis. All the examples above are defined as function declarations. For comparison with other ways, here is a example
sayHello(); // output: Hello
function sayHello() {
console.log('Hello')
}
Function Expression
This way a function is assigned to a variable. Usually, the variable is declared as a const
and the function does not require a name and can be anonymous especially when they are passed as a callback (function passed to another as an argument).
const sayHello = function() {
console.log('Hello')
}
sayHello()
Arrow Function
A shorter syntax for writing functions, especially useful for shorter functions and callbacks. It is can be used to improve the readability of your code.
const sayHello = () => {
console.log('Hello')
}
sayHello()
Function hositing
Function hoisting is a JavaScript behavior where function declarations are moved (“hoisted”) to the top of their scope (global or local) before the code is executed. This allows you to call a function before it is defined in the code.
There are two types of functions that behave differently with hoisting:
Function Declarations: A function declared using the function keyword is hoisted. This means you can call the function before its actual declaration in the code.
greet(); // Output: Hello, world!
function greet() {
console.log("Hello, world!");
}
In the code above, the function greet is hoisted to the top of its scope, so the JavaScript engine knows about the function even before it appears in the code.
Function Expressions: A function assigned to a variable (also called a function expression) is not hoisted. In this case, only the variable declaration is hoisted, not the function assignment. This means you cannot call the function before it is defined.
greet(); // Error: greet is not a function
const greet = function() {
console.log("Hello, world!");
};
In the code above, only the variable greet is hoisted, but it remains undefined until the function is assigned. When the function is called before the assignment, you will get an error.
Lesson Task
There are practice questions in the master branch of this repo.
There are example answers in the answers branch.
Try the exercises before checking the solutions.