مدونة

Share this post :

JavaScript 101: Functions

"People think that computer science is the art of geniuses but the actual reality is the opposite, just many people doing things that build on each other, like a wall of mini stones"

Understanding functions is very important and fundamental for every JavaScript developer, the concept of wrapping a piece of a program in a value that has many uses gives us a way to implement well structured and maintainable code and also enables us to code large applications with less repetition.

In this article, we will tackle the most basic things that every JavaScript developer should know, so if you’re new to JavaScript or you just have started playing around with it, this is the right place to start knowing what functions are and how to write a function.

What is a function?

A function is a block of code that performs a specific task, this code is defined once and used multiple times when invoked.

Defining a function:

In JavaScript, there are different manners to define a function:

1. Function declaration

2. Function expression

3. Arrow function expression

A Function declaration is composed of the keyword “function”, then the name of the function which will be used whenever you want to call your function to do something for you, a list of parameters in a pair of parentheses just after the function’s name (para1, …, paramN) and two curly braces that delimit the body code. let’s take a look at this example:

// function declaration
function add(a, b) {
 return a + b;
}
const result = add(3, 2);
console.log(result);
// output → 5

– function add(a, b) {…} is a function declaration that defines add function, which adds two given numbers a and b.

– The function declaration creates a variable in the current scope with the identifier equal to the function name ‘add’.  This variable holds the function object and the function code will be invoked when it is called by its name with parentheses and two given numbers (line 5).

– After being called the function add will take the values passed between the parentheses and use them to execute the body code which will return as a result 3 + 2 = 5;

The keyword “function” can be used  also to define a function inside an expression and we call that a Function expression.

A Function expression is a regular binding where the value of the binding is a function. For example, this code defines the constant multipyBy2 to refer to a function that produces the multiplication by two of a given number:

const multiplyBy2 = function(x) {
  return x * 2;
};

console.log(multiplyBy2(12));
// output → 24

The Arrow function expression is a shorter way in terms of syntax for writing function expression:

const multiplyBy2 = (x) => {
  return x * 2;
};

console.log(multiplyBy2(12));
// output → 24

Parameters and Arguments:

Parameters and Arguments are very similar, there is only a tiny difference that makes them distinguishable. Parameters are the ones used while defining a function on the other hand arguments are the values provided to the function when called to be executed.

const a = 5; 
 const b = 2;
 // function definition
 const multiply = function (a, b) {
  return a * b;
 }

In the last example, parameters are a & b while arguments are their values  5 & 2.

Invoking a function:

So we have created our function, we passed a bunch of parameters into its parentheses. The next step to start using our function is to call it by its name (just like you’re calling a person by its name!).

This operation “calling a function” is called “Invoking a function”.

To invoke a function you have to reference it by its name followed by a pair of parentheses and parameters if they exist!

Let’s take a look at an example:

First, we’ll define a function named greeting. This function will take one parameter, name. When executed, the function will log Hello plus that name back to the console:

function greeting(name){
 console.log(“Hello ” + name);
}

To invoke this function we need to call it and pass as a parameter a name, I am calling the function and make it say hello to me :3 just by passing my name as a parameter.

greeting(“Marwen”);
// output -> Hello Marwen

You can also declare a function that accepts no parameters, and invoke it by calling its name with an empty set of parentheses.

// declaring the function 
function sayHello(){
 console.log(“Hello everyone!”);
}

// invoking sayHello
   
sayHello();
// output -> Hello everyone!

Yes, I can hear the voice in your head,  you’re wondering about the difference between the functions we have been defining through the whole article some of them have the return word and the others don’t !!! Well, some functions produce values such as add, multipyBy2 and others don’t like sayHello, A return statement determines the value the function returns.

By default, every function in JavaScript returns undefined unless you specify what your function should return by using the return keyword.

let’s demonstrate this with some code:

function myfunction(){
  // the body is empty
};

myfunction();
// output -> undefined

We want our function to return a number, for example, let’s specify that by adding a return statement in the body:

function myfunction(){
   return 5;
};

console.log(myfunction());
// output → 5

The return keyword is very important because when we call a function and assign it to a variable or a constant the value returned by the function will be assigned into that variable or constant, and a function with no return keyword or with return keyword but without an expression after it,  will cause the function to return undefined.

Let’s see this example:

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

// invoke the function and save the return value to result
let result = sum(4,6);

// log result value
console.log(result);
// output → 10

The return keyword assigned the value returned by the function to whatever called the function (the variable result in our case)! , but keep in mind that if you use more than a return statement in the same function, only the first one will be executed and that’s because when control comes across such a statement, it immediately jumps out of the current function and gives the returned value to the code that called the function.

Local & Outer Variables:

In many cases our function needs additional variables to perform its task successfully, so we need to declare these variables inside our functions and use them to get the expected result. These variables declared inside the function (between the curly braces) are called local variables and they are only visible inside that function, we can’t access them or use them in any other code outside our function.

For example:

function Hello() {
  let message = "Hello, I'm JavaScript!"; // local variable

  console.log(message);
}

Hello(); // output → Hello, I'm JavaScript!

console.log( message ); // <-- Error! The variable is local to the function

But A function can access an outer variable as well:

let name = 'JavaScript';

function Hello() {
  let message = 'Hello, ' + name;
  console.log(message);
}

Hello(); // Hello, JavaScript

And it can also modify it:

let name = 'JavaScript';

function Hello() {
  name = 'GoMytech'; // changed the outer variable
  let message = 'Hello, ' + name;
  console.log(message);
}
console.log(name)  // JavaScript

Hello(); // Hello, GoMytech

console.log(name)  // GoMytech

Before the function call we logged the name and we saw “JavaScript” in the console, we invoked our function and when the code in the function body is executed it changes the variable name and logged Hello with the new name, and to prove that the modification affected the global variable we logged the name and it’s now Gomytech!

But what if  global and local variables are same-named! How will our function work?

In fact, this will not cause any problem to our function execution, because by default local variables are always prioritized and the function will look for a variable called name in the outside only if there is no local one.

let name = 'GoMyCode';

function Hello() {
  let name = "GoMyTech"; // declare a local variable

  let message = 'Hello, ' + name; // GoMyTech
  console.log(message);
}

// the function will create and use its own name
Hello();

console.log(name); // GoMyCode, unchanged, the function did not access the outer variable

Summary:

We saw how to declare a function.

● Values passed to the function are called parameters.

● A function can access outer variables and change them.

● A function can have local variables, these variables can only be accessed inside the function body.

● A function can have a return value, if it doesn’t it will return undefined.

Thanks for reading! If you have any comments or any kind of feedback don’t hesitate to ask, and if you liked this article stay tuned for the next level where we will talk more about function expression and function declaration.

Share this post :

Sign up for Newsletters