Functions in JavaScript

Functions in JavaScript

·

6 min read

i)Introduction
ii)What are functions
iii)Ways to create a function in JavaScript
iii)What is function declaration
iv)What is function expression
v)Default values
vi)return statement
v)Differences between function declaration and function expression

Introduction

Writing a function-based code comes with a lot of benefits. In this article, I will explain what functions are, how to create them using function declaration and function expression as well as the differences between them.

What are functions?

Functions are reusable blocks of code that perform a specific task. They allow us to execute a sequence of statements in several places without repetition.

How to create a function in JavaScript

There are several ways to create a function in JavaScript. In this article, I will explain how to create functions with function declaration and function expression.

What is a function declaration?

A function declaration is a separate statement or an independent block in the main code flow of a program. In other words, a function declaration is a standalone block of code.

How to create a function with function declaration
Syntax:

function functionName(parameter1, parameter2,....) {
  //function body
}

From the above syntax, to create a function

  • we write the function keyword
  • Next to the function keyword, is the functionName, which can be used to call or reference the function at a later point in the program
  • Then within the parenthesis(), is an arbitrary list of parameters separated by a comma, which holds data passed into the function.
  • Lastly, enclosed within the curly braces { }, is the function body, which can contain a sequence of statements to be executed when the function is called.

Writing this block of code doesn't execute the function. In order to execute the code within a function, we have to call or invoke the function by its name.

Like this,

functionName(argument1, argument2, .....)

Just like how you would assign values to variables, you can assign arguments to parameters. Parameters are placeholders for data within functions. When a function is called each argument gets assigned to its corresponding parameter.
parameter1 = argument1, parameter2 = argument2, ....... and so on.

Let's write a function to calculate the sum of 2 numbers

function sum(a, b) {
  //a = 1, b = 2
  console.log(a + b);
}
sum(1, 2); //3

The great thing about functions is that we can reuse them multiple times.

For instance, to calculate the sum of 2 numbers different from the previous example, we simply call the function again with different arguments.

Like this,

sum(10, 20); //30

What is a function expression?

A function expression is a function created within the context of an expression.

Let's rewrite the previous example using a function expression

let sum = function(a, b) {
  console.log(a + b);
}

sum(1, 2); //3

As we can see the function isn't a standalone block but is within an expression. In this example we created the function at the right-hand side of an assignment and assigned it to a variable, this makes it a function expression.

Default values

When a function with defined parameters is called without corresponding arguments, a value of undefined gets assigned to those parameters.

let sum = function(a, b) {
  console.log(a); //1
  console.log(b); //undefined
}

sum(1);

The function above expects two arguments, but we passed in a single argument during the function call. As we can see, the first parameter a gets the value of 1, and the second parameter b gets a value of undefined.

We can specify default values that will be used if a function is called without its respective arguments. To specify a default value, you simply add an assignment operator right next to the parameter and assign a value.

let sum = function(a, b = 5) {
  console.log(a);  //1
  console.log(b);  //5
  console.log(a + b); //6
}
sum(1);

The default value is only used if a function expects an argument, but didn't get one during the function call.

let sum = function(a, b = 5) {
  console.log(a); //1
  console.log(b); //7
  console.log(a + b); //8
}
sum(1, 7);

Return statement

When JavaScript comes across a return statement during the execution of a function, it stops and returns the value to the calling code.

A function without a return statement or with an empty return statement, returns undefined. All the previous examples we have seen doesn't have a return statement, this means they returned undefined.

We can see this clearly by calling a function and assigning the result of the function call to a variable.

Like this,

function myName(name) {
  console.log(name); //prints name to the console
}

let sayName = `My name is ${myName("Steve")}`
console.log(sayName); //My name is undefined

Let's add a return statement to our function.

function myName(name) {
  return name;
}

let sayName = `My name is ${myName("Steve")}`
console.log(sayName); //My name is Steve

Now you can see the difference right?

Differences between a function declaration and a function expression

  • How it is defined

A function declaration is created as a separate block in the main code flow while a function expression is created within the context of an expression.

  • Hoisting

A function declaration is usually raised to the top of the script and can be accessed before the point it was defined in the program. In other words, a function declaration can be accessed or referenced before the declaration.

sum(1, 2) //3

function sum(a, b) {
  return a + b;
}

This doesn't happen with function expression, a function expression can only be accessed after it is defined. An attempt to call a function expression before it is defined will result in an error.

sum(1, 2); //Uncaught ReferenceError: sum is not defined

let sum = function(a, b) {
  return a + b;
}
  • Function name

A function declaration must have a name. An error is thrown if a function declaration is created without a name

The name of a function expression may be omitted, it may be anonymous. In cases where a function expression doesn't have a name, the contextual name is used instead. A function expression with a name is referred to as Named Function Expression(NFE)

JavaScript provides a built-in function property called name which returns the name of a function. I will use it to explain how things work.

A function expression without a function name

let sum = function(a, b) {
  return a + b;
}

console.log(sum.name) //sum

Since the function expression doesn't have a name the variable name is returned when we access the name property.

A function expression with a name

let sum = function myFunc(a, b) {
  return a + b;
}

console.log(sum.name) //myFunc

Now the name property returns myFunc because we gave our function a name.

It is important to note that the function name in a function expression is internal, it is only visible within the function. Outside the block, we cannot reference or call the function using its function name, an error will be thrown.

let sum = function myFunc(a, b) {
  return a + b;
}

myFunc(1, 2); //Uncaught ReferenceError: myFunc is not defined

Note that this is peculiar to function expression, there is no internal name for function declaration

Summary

  • Functions make our program readable as it separates our code into logical sections.
  • Functions can be defined using function declaration or function expression.

References