Skip to content

2.1 Functions

What is a function?

Task 1: Our friend Ali is again here. He wants us to greet him whenever he wants.

console.log("Hello Ali");

Right! However, you did not do anything regarding the task part whenever he wants.

Task 2: Read this code, and check the result.

function greetAli(){
  console.log("Hello Ali");
}

greetAli(); // Ali wants us to greet him
greetAli(); // Ali wants us to greet him
greetAli(); // Ali wants us to greet him
greetAli(); // Ali wants us to greet him

The result is as follows:

Hello Ali
Hello Ali
Hello Ali
Hello Ali

Let's think of this task again:

  1. Ali wants us to greet him whenever he wants. If he says: greet me now, we should greet him at the same time.
  2. We can put this greeting message in a block of code, that has a name. Whenever Ali wants a greeting, we call this block of code by the block name.
  3. To create such a block of code in JavaScript, we need the keyword function. We give this function a name, which is "greetAli"
  4. Whenever Ali wants a greeting, we call our function by its name. Then, Ali's message appears in the console.

Task 3: Read this code, and check the result.

function greetOla(){
  console.log("Hello Ola");
}

greetOla(); // Ola wants us to greet her
greetOla(); // Ola wants us to greet her
greetOla(); // Ola wants us to greet her
greetOla(); // Ola wants us to greet her
greetOla(); // Ola wants us to greet her
greetOla(); // Ola wants us to greet her

The result is as follows:

Hello Ola
Hello Ola
Hello Ola
Hello Ola
Hello Ola
Hello Ola

We used the function way to greet Ola. We do not want her to get upset with us.

How to create a function?

  1. Use the keyword function to define a new function.
  2. Give your function a name, any name you like. For instance; greetOla.
  3. Open and close parentheses ().
  4. Type an opening curly bracket {.
  5. Write the statements you want to perform, whenever you call this function. For instance; console.log("Hello");
  6. Type a closed curly bracket }.

How to call a function?

  1. Type the function name. For instance; greetOla.
  2. Type an open and closed parentheses ().

Task 4: Count from 1 to 10, whenever Sanad asks you to do it.

function countTo10(){
  for(var i=1; i<=10; i++){
    console.log(i);
  }
}

// Sanad ask you to count now
countTo10()

The result is as follows:

1
2
3
4
5
6
7
8
9
10

Task 5: Display the following sentences in the console:

  1. "Hello there"
  2. "Welcome to our website!"
  3. "We are glad to have you with us."
  4. "Here is the content of our website."
  5. "Hello there"
  6. "Welcome to our website!"
  7. "We are glad to have you with us."
console.log("Hello there");
console.log("Welcome to our website!");
console.log("We are glad to have you with us.");
console.log("Here is the content of our website.");
console.log("Hello there");
console.log("Welcome to our website!");
console.log("We are glad to have you with us.");

The result is as follows:

Hello there
Welcome to our website!
We are glad to have you with us.
Here is the content of our website.
Hello there
Welcome to our website!
We are glad to have you with us.

Wait a minute! There is much repetition in the task 5 code. Now, we know the function concept, and we can implement it to avoid this code repetition.

Do not Repeat Yourself!

Do not Repeat Yourself (DRY) is a programming principle. DRY means that the programmer should not write the same code over and over again. Instead, he/she should find ways to reduce the amount of repetition in his/her code. For instance; he/she can use loops, and functions to avoid repetition.

Task 6: Re-do task 5, and implement DRY principle.

function greeting(){
  console.log("Hello there");
  console.log("Welcome to our website!");
  console.log("We are glad to have you with us.");
}

greeting();
console.log("Here is the content of our website.");
greeting();

You can see the same result:

Hello there
Welcome to our website!
We are glad to have you with us.
Here is the content of our website.
Hello there
Welcome to our website!
We are glad to have you with us.

Why use functions?

You can use functions whenever you want to re-use a block of code over and over again.

Task 7: Only logged users can like posts and add comments. A user wants to like a post, and add a comment.

1- Display "Let's see if you are logged in" in the console.

2- Then check if the user is logged in.

3- Display "The user wants to like a post", and check if he/she is logged in.

4- Display "The user wants to add a comment", and check if this user is logged in.

Assume that the user is logged in. Hint: follow the DRY principle.

var userLoggedIn = true;

function isLoggedIn(){
  if(userLoggedIn){
    console.log("He is logged in.")
  }else{
    console.log("He is not logged in.");
  }
}

console.log("Let's see if you are logged in");
isLoggedIn();
console.log("The user wants to like a post");
isLoggedIn();
console.log("The user wants to add a comment");
isLoggedIn();

The result is as follows:

Let's see if you are logged in
He is logged in.
The user wants to like a post
He is logged in.
The user wants to add a comment
He is logged in.

Task 8: Re-do task 7. Assume that the user is not logged in.

var userLoggedIn = false;

function isLoggedIn(){
  if(userLoggedIn){
    console.log("He is logged in.")
  }else{
    console.log("He is not logged in.");
  }
}

console.log("Let's see if you are logged in");
isLoggedIn();
console.log("The user wants to like a post");
isLoggedIn();
console.log("The user wants to add a comment");
isLoggedIn();

The result is as follows:

Let's see if you are logged in
He is not logged in.
The user wants to like a post
He is not logged in.
The user wants to add a comment
He is not logged in.

Return Statement

Task 9: Read the following code, and try to understand it.

var userLoggedIn = false;

function isLoggedIn(){
  if(userLoggedIn){
    return "He is logged in.";
  }else{
    return "He is not logged in.";
  }
}

var isLoggedInReturned = isLoggedIn();
console.log(isLoggedInReturned);

The result is: He is not logged in.

Let's investigate this code:

  1. We declared a variable called userLoggedIn, and we assigned false to this variable.
  2. We created a function called isLoggedIn.
  3. isLoggedIn function checks whether userLoggedIn is true, or false.
  4. If userLoggedIn is true, the function returns "He is logged in".
  5. If userLoggedIn is false, the function returns "He is not logged in".
  6. Then, we created a new variable with the name isLoggedInReturned.
  7. We assigned the value returned from isLoggedIn function to isLoggedInReturned.
  8. We displayed the value of isLoggedInReturned in the console.

Well! What is this return?

Instead of displaying the code result inside the function, we can specify the value returned from the function using the return statement.

The value returned from the function is the value that our function results. We get this return value when we call the function.

Task 10: Read this code, and try to understand it.

var userLoggedIn = false;

function isLoggedIn(){
  if(userLoggedIn){
    return "He is logged in.";
  }else{
    return "He is not logged in.";
  }
}

isLoggedIn();

Nothing is displayed in the console. Why?! Our function returns a value, but it does not display it in the console. If you want to display the function return value somewhere, you can store this return value in a variable, then display this variable value in the console, as we did in task 9.

Task 11: Create a function that returns 2 added to a given number, and display the result in the console.

var num = 2;
function add2(){
  return 2 + num;
}

var numPlus2 = add2();
console.log(numPlus2);

The result is: 4.

Task 12: Create a function that returns "You are not allowed here.", and display the result in the console.

function accessDenied(){
  return "You are not allowed here.";
}

console.log(accessDenied());

The result is: You are not allowed here.

Task 13: Create a function that returns "You can access this page.", and display the result in the console.

function accessGranted(){
  return "You can access this page.";
}

console.log(accessGranted());

The result is: You can access this page.

Task 14: Create a function that checks if the user is blocked or not. If the user is blocked, return "You are not allowed here"; otherwise, return "You can access this page."

var userBlocked = true;

function isBlocked(){
  if(userBlocked){
    return "You are not allowed here."
  }else{
    return "You can access this page.";
  }
}

console.log(isBlocked());

The result is: You are not allowed here.

Task 15: Create a function that returns 2 added to every number from 1 to 10. Do not forget to call this function, and display the result in the console.

function add2(){
  for(var i=1; i<= 10; i++){
    return 2 + i;
  }
}
console.log(add2());

The result is: 3.

We expected to have 2 added to every number from 1 to 10. However, this did not happen. Why? Because whenever we add the return statement in our function, the function stops executing and returns the specified value in the return statement. We will re-do this task later in this lesson.

Task 16: Create a function that returns true.

function returnsTrue(){
  return true;
}

console.log(returnsTrue());

The result is : true.

Task 17: Create a function that returns 100.

function returns100(){
  return 100;
}

console.log(returns100());

The result is: 100.

Task 18: Create a function that returns null.

function returnsNull(){
  return null;
}

console.log(returnsNull());

The result is: null.

Task 19: Create a function, and do not add any statement inside this function.

function returnsNothing(){
  // Nothing here
}

console.log(returnsNothing());

The result is: undefined.

Note

If you call a function that has no return statement, the return value from calling this function is undefined.

undefined! why? undefined means that you have not assigned any value to the variable, right?! Since you do not return any value from this function, it makes sense that the return value is undefined.

Task 20: Check the return value of the task 2 function.

function greetAli(){
  console.log("Hello Ali");
}

var returnValue = greetAli();
console.log(returnValue);

The result is as follows:

Hello Ali
undefined

Task 21: Check the return value of the task 4 function.

function countTo10(){
  for(var i=1; i<=10; i++){
    console.log(i);
  }
}

var returnValue = countTo10();
console.log(returnValue);

The result is as follows:

1
2
3
4
5
6
7
8
9
10
undefined

Return Statement

Once you write the return statement in the function, the function stops executing and returns the specified return value.

The function return value can be a string, number, boolean, null, or anything you like.

If you do not specify the function return value, the return value is undefined.

Parameters and Arguments

Task 22: I re-wrote the code of Task 2. Read the following code, and try to understand it.

function greetSomeone(name){
  console.log("Hello " + name);
}

greetSomeone("Ali"); // Ali wants us to greet him
greetSomeone("Ali"); // Ali wants us to greet him
greetSomeone("Ali"); // Ali wants us to greet him
greetSomeone("Ali"); // Ali wants us to greet him

The result is as follows:

Hello Ali
Hello Ali
Hello Ali
Hello Ali

We extended the task 2 code. You can greet a new person by changing the value, with which you call the function.

Task 23: We can use the function created in task 22 again in task 3.

function greetSomeone(name){
  console.log("Hello " + name);
}

greetSomeone("Ola"); // Ola wants us to greet her
greetSomeone("Ola"); // Ola wants us to greet her
greetSomeone("Ola"); // Ola wants us to greet her
greetSomeone("Ola"); // Ola wants us to greet her
greetSomeone("Ola"); // Ola wants us to greet her
greetSomeone("Ola"); // Ola wants us to greet her

The result is as follows:

Hello Ola
Hello Ola
Hello Ola
Hello Ola
Hello Ola
Hello Ola

Task 24: Use task 22 function, and greet Sanad twice.

function greetSomeone(name){
  console.log("Hello " + name);
}

greetSomeone("Sanad");
greetSomeone("Sanad");

The result is as follows:

Hello Sanad
Hello Sanad

Task 25: Add 2 to the provided user number. Display the result in the console. Hint: use functions.

function add2(userNumber){
  return userNumber + 2;
}
console.log(add2(5));
console.log(add2(10));

The result is as follows:

7
12

Task 26: Re-do task 15, and display all the numbers from 1 to 10 added to 2. Hint: use task 25 function.

for(var i=1; i<=10; i++){
  console.log(add2(i));
}

The result is as follows:

3
4
5
6
7
8
9
10
11
12

Task 27: I re-wrote the code of task 8. Read it, and try to understand it.

function isLoggedIn(userLoggedIn){
  if(userLoggedIn){
    console.log("He is logged in.")
  }else{
    console.log("He is not logged in.");
  }
}

console.log("Let's see if you are logged in");
isLoggedIn(false);
console.log("The user wants to like a post");
isLoggedIn(false);
console.log("The user wants to add a comment");
isLoggedIn(false);

The result is as follows:

Let's see if you are logged in
He is not logged in.
The user wants to like a post
He is not logged in.
The user wants to add a comment
He is not logged in.

Parameters & Arguments

The thing that we pass to the function is called a parameter. In task 22, name is a parameter.

The value that we call the function with is called an argument. In task 22, "Ali" is an argument.

Task 28: Create a function that adds two numbers.

function addNumbers(num1, num2){
  return num1 + num2;
}

console.log(addNumbers(2,10));
console.log(addNumbers(8,40));
console.log(addNumbers(50,222));

The result is as follows:

12
48
272

As you can see, functions make things much easier; all that you need is to specify the variables, that you need to process inside the function. For instance; in task 28, the function requires two numbers to process; num1 and num2. When we call the function, we specify the values (arguments) that we want the function to process. For example; we want the function to add 10 to 2, so we wrote addNumbers(2,10)

Task 29: Create a function that adds four numbers together.

function addNumbers(num1, num2, num3, num4){
  return (num1 + num2 + num3 + num4);
}

console.log(addNumbers(1,2,3,4));
console.log(addNumbers(55,8,5,3));
console.log(addNumbers(546,254,20,8));

The result is as follows:

10
71
828

Task 30: Create a function that checks if the provided value is an empty string.

function isEmpty(value){
  return (value === "");
}

console.log(isEmpty(""));
console.log(isEmpty(null));
console.log(isEmpty(undefined));
console.log(isEmpty("Hello"));

The result is as follows:

true
false
false
false

Task 31: Create a function that checks if the provided value is null, undefined, "" or false.

function isFalse(value){
  return (!value);
}

console.log(isFalse(""));
console.log(isFalse(null));
console.log(isFalse(undefined));
console.log(isFalse("Hello"));

The result is as follows:

true
true
true
false

In task 31, we wanted to know whether the provided value is false or true. If the value is false, we want to return true; otherwise, we return false. That is why we wrote !value.

Task 32: Create a function that checks if the value is true, it returns the value; otherwise, it returns false.

function validateValue(value){
  if(!value){
    return false;
  }else{
    return value;
  }
}

console.log(validateValue(""));
console.log(validateValue(null));
console.log(validateValue(undefined));
console.log(validateValue("Hello"));

The result is as follows:

false
false
false
Hello

Task 33: I re-wrote task 32 code. Read the code and try to understand it.

function validateValue(value){
  return value || !!value;
}

console.log(validateValue(""));
console.log(validateValue(null));
console.log(validateValue(undefined));
console.log(validateValue("Hello"));

The result will be:

false
false
false
Hello

Let's go back to the basics! || is the OR logical operator, it returns true if any of its conditions are true; otherwise, it returns false.

In task 33, if value is true, the JavaScript engine will not investigate further, and the function return value will be the value itself. If value is false, the JavaScript engine will look to the second condition !!value, it is false. Hence, the function return value is false.

OR || returns a value other than true/false?!

It is by design || returns the first value that is not false

Task 34: Create a function that returns true if the provided value contains "z"; otherwise returns false.

function isThereZ(value){
  return (value.indexOf("z") !== -1);
}

console.log(isThereZ("Hello everyone"));
console.log(isThereZ("zerro is here"));
console.log(isThereZ("He is going zzzzzzzzzz"));
console.log(isThereZ("Everyone is working here."));

The result is as follows:

false
true
true
false

Note

string.indexOf(character) returns -1 if the string does not contain the character.

Task 35: Create a function that checks if the password is provided. If true, return the password; otherwise, return false.

function isPasswordProvided(password){
  return password || !!password;
}

console.log(isPasswordProvided("@jksd55"));
console.log(isPasswordProvided(null));
console.log(isPasswordProvided("123"));
console.log(isPasswordProvided(undefined));
console.log(isPasswordProvided(""));

The result is as follows:

@jksd55
false
123
false
false

Task 36: Read the following code, and try to understand it.

function somethingMissing(num){
  console.log(num)
}

somethingMissing();

The result is: undefined.

What happened here? You forgot to call the function with a value. num has not been assigned any value yet. Hence, it is undefined.

Task 37: Check the following code, and try to guess the result.

function display(a, b, c, d){
  console.log(a, b, c, d);
}

display(1, 2, 3, 4);
display(6, 88);
display(77, 88, 99);
display(700);
display();

The result is as follows:

1 2 3 4
6 88 undefined undefined
77 88 99 undefined
700 undefined undefined undefined
undefined undefined undefined undefined

Remember that!

undefined is the value of anything that has not been assigned a value.

Task 38: Read the following code, and try to understand the result.

function display(a, b, c, d=1){
  console.log(a, b, c, d);
}

display(1, 2, 3, 4);
display(6, 88);
display(77, 88, 99);
display(700);
display();

The result is as follows:

1 2 3 4
6 88 undefined 1
77 88 99 1
700 undefined undefined 1
undefined undefined undefined 1

In task 38; we assigned a default value to d. If you do not call the function display with a specific d value, the default value will be displayed.

Task 39: Re-do task 38 and add a default value for c. Let this default value be 5.

function display(a, b, c=5, d=1){
  console.log(a, b, c, d);
}

display(1, 2, 3, 4);
display(6, 88);
display(77, 88, 99);
display(700);
display();

The result is as follows:

1 2 3 4
6 88 5 1
77 88 99 1
700 undefined 5 1
undefined undefined 5 1

What is a function?

A function is a block of code that can be re-used multiple times in the program.

A function may accept one parameter or more, and it processes the input parameters to produce a return value.

A function can be called by its name anywhere you want in your code.