Functions

In this article we are going to learn about Javascript functions.

In computer programming, a function is a set of instructions that performs a specific task. Functions are also known as procedures or subroutines. They are often used to perform mathematical operations, such as addition, subtraction, multiplication, and division. Functions can also be used to display information on a screen or to get input from a user. In JavaScript, every function is an Object.

Creating a function

When we create a new function, we can also say we are defining or declaring a function.

Basic syntax of a function

function function_name(parameter1, parameter2) {
// Statements (function body)
}

We declare a function using the “function” keyword, then we add the name of the function. The name of the function can be anything except the reserved Javascript keywords (e.g. this, const, let, var, prototype etc.).

After the function name we add an opening and closing parenthesis. Inside the parenthesis we can add one or more parameters, separated by comma. This is optional.

Function names are case sensitive and it is generally accepted convention to capitalize the first letter of each word, except the first one.

Example:

function sayHello() {
console.log("Hello!")
}

Executing a function

A function doesn’t do anything until we call it. Sometimes we say execute or invoke instead of call. If we want to execute the function above we need to call it. We can do it like this:

sayHello();

We use the name of the function to execute it.

Function parameters and arguments

We have already discussed that a function can take one or more parameters. We add parameters inside the parenthesis, separated with a comma.

function sayHello(firstName, lastName) {
console.log(`Hello, ${firstName} ${lastName}!`)
}

sayHello('John', 'Doe');

So, here we added two parameters to the “sayHello” function, “firstName” and “lastName”. when we call the function, we add values (arguments) to these parameters, “John” and “Doe” and we display them in the function body.

Try to call the above function without providing any arguments. In this case you will get: “Hello, undefined undefined!

To avoid this, we can add default values to parameters.

function sayHello(firstName = 'Peter', lastName = 'Smith') {
console.log(`Hello, ${firstName} ${lastName}!`)
}

sayHello();

The function return keyword

So far we used functions to display something, but this is not really their puprose. Functions are mostly used to perform some kind of task and then return a result.

The return keyword is used to return a value from the function. When a return keyword is reached, the execution of the current function stops and the value is returned to the caller.

Example:

function multiply(num1, num2) {
return num1 * num2;
}

multiply(5, 5);

So, here we have a function called “multiply” which takes two parameters, multiplies them together and returns a result. But when we call the function nothing seems to happen, nothing is shown in the console. This is completely normal. The function now returns a value for us that we can use.

let result = multiply(5, 5);

console.log(result);

Now we can print out the result.

Different ways to declare a function

  • Function declaration
  • Function expression

A function declaration is a statement that declares a function. This is the way we have been doing it so far.

A function expression is a function that is assigned to a variable.

Basic syntax of function expression

var_keyword var_name = function(params) {
// function body
}

The multiply function that we used above can be transformed into an expression like this:

let multiply = function(num1, num2) {
return num1 * num2;
}

console.log(multiply(3, 3));

Main differences between function declaration and function expression

  • function declaration has access to the “this” keyword
  • function expressions are not hoisted (can’t use it before it is declared)

Arrow functions

It’s a shorter and more modern way to write function expression.

Basic syntax

var_keyword var_name = (params) => {
// function body
}

The multiply function that we used above can be transformed into an arrow function like this:

let multiply = (num1, num2) => {
return num1 * num2;
}

console.log(multiply(3, 3));

When we have a single “return” statement in the function body, we can get rid of the “return” keyword and the curly braces.

let multiply = (num1, num2) => num1 * num2;

We can further simplify the syntax if we have only one parameter. In this case we don’t need to use the parenthesis.

let name = fname => fname;
let result = name("Bill");

console.log(`Hello, ${result}!`);

 

ChristianKovats
ChristianKovats

Christian Kovats is a London-based web designer who loves crafting innovative and user-friendly interfaces. His passion for design is only rivaled by his love for nature and hiking, often drawing inspiration from his treks through the diverse landscapes of the UK. Outside of work, Christian enjoys spending quality time with his wife and 4-year-old son. A seasoned lucid dreamer, he also spends time exploring the intricate world of dream interpretation, reflecting his ever-curious and creative mind.

ChristianKovats

Leave a reply

You must be logged in to post a comment.