Skip to content

2.2 Anonymous Functions

Create Anonymous Functions

Task 1: Create a function that displays "Hello" in the console.

function displayHello(){
  console.log("Hello");
}

displayHello();

The result is: Hello

Task 2: I re-wrote the code of task 1. Check it out.

var displayHello = function(){
  console.log("Hello");
};

displayHello();

The result is: Hello

Anonymous Function

We learned before that we declare a variable with a name. Then we can assign a value to this variable. For instance; var greet = "Hello"; is a variable with the name greet, and the value "Hello". In task 2, we created a variable with the name displayHello, and we assigned function to it as a value. However, this function has no name, that is why we call it an anonymous function.

Task 3: Create an anonymous function that adds two numbers together.

var addTwoNumbers = function(num1, num2){
  return num1 + num2;
}

console.log(addTwoNumbers(5, 6));
console.log(addTwoNumbers(10, 20));

The result is as follows:

11
30

Task 4: Create an anonymous function that checks if a value is true or not.

var isTrue = function(value){
  if(value === true){
    return true;
  }else{
    return false;
  }
}

console.log(isTrue(""));
console.log(isTrue("Hello"));
console.log(isTrue(true));
console.log(isTrue(null));

The result is as follows:

false
false
true
false

Task 5: Create an anonymous function that adds 123 to a given value.

var add123 = function(value){
  return (value + 123);
}

console.log(add123("Hello"));
console.log(add123("nana"));
console.log(add123(undefined));
console.log(add123(null));
console.log(add123(false));

The result is as follows:

Hello123
nana123
NaN
123
123

Well, what is happening here? What is NaN? why is null + 123 equal to 123? Why is false + 123 equal to 123? Let's answer these questions!

Type Coercion

Task 6: Create an anonymous function that converts a given value to a number. Hint: use Number(value).

var convertToNumber = function(value){
  return Number(value);
}
console.log(convertToNumber("123"));
console.log(convertToNumber(false));
console.log(convertToNumber(true));
console.log(convertToNumber("lala"));
console.log(convertToNumber(null));
console.log(convertToNumber(undefined));

The result is as follows:

123
0
1
NaN
0
NaN

Number(value)

Number(value) converts a given value to a number, if possible. If not, it returns NaN, which means Not A Number

Let's investigate the code above:

  1. Convert "123" to a number; the string "123" can be easily converted to a number. Number("123") is 123.
  2. Convert false to a number; Number(false) evaluates to 0 in JavaScript.
  3. Convert true to a number; Number(true) evaluates to 1 in JavaScript.
  4. Convert "lala" to a number; the string "lala" can not be converted to a number. Number("lala") is not a number NaN.
  5. Convert null to a number; Number(null) evaluates to 0 in JavaScript.
  6. Convert undefined to a number; undefined can not be converted to a number. Number(undefined) is not a number NaN.

Task 7: Create an anonymous function that converts a given value to a string. Hint: use String(value).

var convertToString = function(value){
  return String(value);
}
console.log(convertToString(123));
console.log(convertToString(false));
console.log(convertToString(true));
console.log(convertToString("lala"));
console.log(convertToString(null));
console.log(convertToString(undefined));

The result is as follows:

123
false
true
lala
null
undefined

String(value)

String(value) converts a given value to a string.

Let's investigate the code above:

  1. Convert 123 to a string; the number 123 can be easily converted to a string. String(123) is "123".
  2. Convert false to a string; String(false)is "false".
  3. Convert true to a string; String(true) is true.
  4. Convert "lala" to a string; String("lala") is already a string.
  5. Convert null to a string; String(null) is "null".
  6. Convert undefined to a string; String (undefined) is "undefined".

Task 8: I re-wrote the task 5 as below.

var add123 = function(value){
  var result = value + 123
  console.log(`value: ${value}, value type: ${typeof value}`);
  console.log(`${typeof value} + ${typeof 123} = ${typeof result}`);
  console.log(`${value} + 123 = ${result}`)
  console.log("..............................");
}

add123("Hello");
add123("nana");
add123(undefined);
add123(null);
add123(false);

The result is as follows:

value: Hello, value type: string
string + number = string
Hello + 123 = Hello123
..............................
value: nana, value type: string
string + number = string
nana + 123 = nana123
..............................
value: undefined, value type: undefined
undefined + number = number
undefined + 123 = NaN
..............................
value: null, value type: object
object + number = number
null + 123 = 123
..............................
value: false, value type: boolean
boolean + number = number
false + 123 = 123

First, do not worry about the way I wrote my sentences using console.log, I will explain that later. Just try to analyze the results.

As you can see, whenever I add a string to anything, the other thing gets converted to a string implicitly.

"Hello" is a string
123 is a number
string + number =  string + (String(number))
Then, "Hello" + 123 = "Hello" + "123" = "Hello123

"nana" is a string
123 is a number
string + number =  string + (String(number))
Then, "nana" + 123 = "nana" + "123" = "nana123"

Notice that, when you add null or false to a number, JavaScript converts null and false to zero.

null is an object(but it evaluates to zero)
null + 123 = 0 + 123 = 123

false is a boolean
123 is a number
boolean + number = Number(boolean) + number
Then, false + 123 = 0 + 123 = 123

Notice that, when you add true to a number, JavaScript converts true to one.

true is a boolean
123 is a number
boolean + number = Number(boolean) + number
Then, true + 123 = 1 + 123 = 124

What about undefined? Again undefined means the value has not been assigned yet. It is not possible to convert undefined to number. Number(undefined) is NaN.

undefined is undefined
123 is a number
undefined + 123 = NaN

Task 9: Write an anonymous function that checks the type of NaN.

var typeofNaN = function(){
  console.log(typeof NaN);
}

typeofNaN();

The result is: number

Task 10: Write an anonymous function that checks if a given value is NaN. Hint: use isNaN().

var isNotANumber = function(value){
  console.log(isNaN(value));
}

isNotANumber(5);
isNotANumber(null);
isNotANumber(NaN);
isNotANumber(undefined);
isNotANumber(false);

The result is as follows:

false
false
true
true
false

What is NaN?

NaN represents not a number value in JavaScript. The type of NaN is a number. You can check if the value is NaN using isNaN(value)

Task 11: Create an anonymous function that adds 456 to a given value.

var add456 = function(value){return (value + 456);}

console.log(add456("Hello"));
console.log(add456("nana"));
console.log(add456(undefined));
console.log(add456(null));
console.log(add456(false));

The result is as follows:

Hello456
nana456
NaN
456
456

Why Use Anonymous Functions?

Task 12: Create an anonymous function that displays "Hi, I am a great washing machine, I will clean your clothes now." in the console.

var washingMachine = function(){
  console.log("Hi, I am a great washing machine, I will clean your clothes now.");
}

Task 13: Create an anonymous function that displays "Hi, I am set on the extra cleaning mode now" in the console.

var extraCleaningMode = function(){
  console.log("Hi, I am set on the extra cleaning mode now");
}

Task 14: Create an anonymous function that displays "Hi, I am set on the extra extra cleaning mode now" in the console.

var extraCleaningMode = function(){
  console.log("Hi, I am set on the extra extra cleaning mode now");
}

Task 15: Create a regular function that simulates the work of the washing machine. It takes the mode the washing machine is set on. If the mode is equal to 1, it returns the function created in task 12. If the mode is equal to 2, it returns the function created in task 13. If the mode is equal to 3, it returns the function created in task 14. The default mode is 1.

function washClothes(mode){
  if(mode === 2){
    return function(){
     console.log("Hi, I am set on the extra cleaning mode now.");
   }
  }else if(mode == 3){
    return function(){
      console.log("Hi, I am set on the extra extra cleaning mode now.");
    }
  }else{
    return function(){
      console.log("Hi, I am a great washing machine, I will clean your clothes now.");
    }
  }
}

washClothes(1)();
washClothes(2)();
washClothes(3)();
washClothes()();

The result is as follows:

Hi, I am a great washing machine, I will clean your clothes now.
Hi, I am set on the extra cleaning mode now.
Hi, I am set on the extra extra cleaning mode now.
Hi, I am a great washing machine, I will clean your clothes now.

Oh boy! we just wrote a piece of advanced code right now. Let's investigate it:

  1. We created a regular function called washClothes.
  2. washClothes takes one parameter mode.
  3. If mode is equal to 2, our regular function returns the task 13 anonymous function.
  4. If mode is equal to 3, our regular function returns the task 14 anonymous function.
  5. Otherwise, our regular function returns the task 12 anonymous function.
  6. We called our regular function by its name washClothes with argument 1.
  7. Since our function returns a function, we also need to call this returned function using ().
  8. The result is the sentence provided in task 12 function: Hi, I am a great washing machine, I will clean your clothes now.
  9. We called our regular function by its name washClothes with argument 2.
  10. Since our function returns a function, we also need to call this returned function using ().
  11. The result is the sentence provided in task 13 function: Hi, I am set on the extra cleaning mode now.
  12. We called our regular function by its name washClothes with argument 3.
  13. Since our function returns a function, we also need to call this returned function using ().
  14. The result is the sentence provided in task 14 function: Hi, I am set on the extra extra cleaning mode now.
  15. We called our regular function by its name washClothes with no argument.
  16. Since our function returns a function, we also need to call this returned function using ().
  17. The result is the sentence provided in task 12 function: Hi, I am a great washing machine, I will clean your clothes now.

A Function returns a function!

See! it is all about how you think of your code, and how do you want to solve the problem. When you want to wash your clothes in a washing machine, you put your clothes in the machine, then you press the ON button. I can think of the washing process as a function that returns clean clothes. But you may want your machine to do extra cleaning, so you press the ON button, then you would press the extra cleaning button. What you did here is you called the washing function on your clothes, the return value of this function is another function that does extra cleaning. If you want to get your clothes now, you need to call the first cleaning function, then the second extra cleaning function.

Can I use regular functions instead?

In tasks 12, 13, 14, and 15; we could return regular functions instead of anonymous functions. It is correct and valid. However, we used anonymous functions there because we only need to execute these functions here in this piece of code. We do not need to re-use them anywhere else in the code. Hence, it was better to use anonymous functions in the tasks above.

When use anonymous functions?

  1. When you need to add a function that will not be used anywhere else in the code.

Task 16: Create an anonymous function that sets allPermissions variable to "Granted". It also displays "You are allowed here." in the console.

var accessAllowed = function(){
  var allPermissions = "Granted";
  console.log("You are allowed here.");
}

Task 17: Create an anonymous function that sets allPermissions variable to "Removed". It also displays "You are not allowed here." in the console.

var accessDenied = function(){
  var allPermissions = "Removed";
  console.log("You are not allowed here.");
}

Task 18: Create a regular function that checks if the user is logged in. If yes, it returns the function created in task 16; otherwise, it returns the function created in task 17.

function isLoggedIn(userLoggedIn){
  if(userLoggedIn){
    return function(){
      var allPermissions = "Granted";
      console.log("You are allowed here.");
    }
  }else{
    return function(){
      var allPermissions = "Removed";
      console.log("You are not allowed here.");
    }
  }
}

isLoggedIn(true)();
isLoggedIn(false)();

The result is as follows:

You are allowed here.
You are not allowed here.

How does the code above work?

  1. We created a regular function called isLoggedIn.
  2. isLoggedIn takes one parameter userLoggedIn.
  3. If userLoggedIn is true, our regular function returns an anonymous function.
  4. If userLoggedIn is false, our regular function returns another anonymous function.
  5. We have already written these two anonymous functions in task 16 and task 17
  6. We called our regular function by its name isLoggedIn with argument true.
  7. Since our function returns a function, we also need to call this returned function using ().

Well! Why do not we call our anonymous function directly? So, we do not need to call it when we call the regular function.

Immediately-invoked Function Expressions

Task 19: I re-wrote the task 16 again. Check the following code.

var accessAllowed = function(){
  var allPermissions = "Granted";
  console.log("You are allowed here.");
}()

The result is: You are allowed here.

Of course, we could write accessAllowed() to call our anonymous function. However, we wanted here to run the function as soon as it is defined.

Task 20: Re-do task 17, and make sure to execute the function as soon as it is defined.

var accessDenied = function(){
  var allPermissions = "Removed";
  console.log("You are not allowed here.");
}()

The result is: You are not allowed here.

Task 21: Re-do task 18, and make sure to execute the function as soon as it is defined.

function isLoggedIn(userLoggedIn){
  if(userLoggedIn){
    return function(){
      var allPermissions = "Granted";
      console.log("You are allowed here.");
    }()
  }else{
    return function(){
      var allPermissions = "Removed";
      console.log("You are not allowed here.");
    }()
  }
}

isLoggedIn(true);
isLoggedIn(false);

The result is as follows:

You are allowed here.
You are not allowed here.

When use anonymous functions?

  1. When you need to add a function, that will not be used anywhere else in the code.
  2. When you want to execute the function as soon as it is created.

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

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

The result is: Hello

In task 22; we simply created an anonymous function, and we called it at the moment of the creation. Yes, we created an IIFE.

IIFE

IIFE stands for Immediately-invoked Function Expression. It is a way to execute functions as soon as they are defined.

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

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

The result is as follows:

Uncaught SyntaxError: Function statements require a function name

Why did this happen? If you want to create an IIFE, you need to enclose it inside (). Otherwise, you will get an error.

Task 24: Create an IIFE that sets the password to "topSecret", and displays "It is set" in the console.

(function(){
  var password = "topSecret";
  console.log("It is set");
})();

The result is: It is set

Task 25: Create an IIFE that sets the secret word to "thisIsASecertWord".

(function(){
  var secretWord = "thisIsASecertWord";
})();

Task 26: Display secretWork in task 25 in the console. Note, write the display statement outside the function.

(function(){
  var secretWord = "thisIsASecertWord";
})();
console.log(secretWord);

The result is: Uncaught ReferenceError: secretWord is not defined

Why? Whatever you write inside your IIFE is not accessible outside. We can use IIFEs to make our variables private. Private variables are those variables that are not accessible outside the function.

When use anonymous functions?

  1. When you need to add a function, that will not be used anywhere else in the code.
  2. When you want to execute the function as soon as it is created.
  3. When you use them as IIFEs, and you want to make the function variables private.

Task 27: Create an IIFE that does secret calculation on a given number. Then it adds 10 to the resultant number. Assume that: this secret calculation is: (num + 5)/10.

(function(num){
  var result = (num + 5)/10;
  console.log(result + 10);
})(50);

The result is: 15.5

Task 28: Someone tries to access the result variable in task 27. What will he/she get?

(function(num){
  var result = (num + 5)/10;
  console.log(result + 10);
})(50);
console.log(result);

He/she will get as follows:

15.5
Uncaught ReferenceError: result is not defined

Great! our result is not accessible outside the function. It is a private variable now.

Task 29: Create an IIFE that sets secretNumber variable to "1111", then return this number.

(function(){
  var secretNumber = 1111;
  return secretNumber;
})();

Task 30: Someone tries to access the secretNumber variable in task 29. What will he/she get?

(function(){
  var secretNumber = 1111;
  return secretNumber;
})();
console.log(secretNumber);

He/she will get: Uncaught ReferenceError: result is not defined

Task 31: In task 30; we want secretNumber to be accessible outside the function.

var getSecretNumber = (function(){
  var secretNumber = 1111;
  return secretNumber;
})();
console.log(getSecretNumber);

The result is: 1111

Well, what happened here?

  1. We created a new variable called getSecretNumber.
  2. The value of getSecretNumber to the return value of our IIFE, which is 1111.
  3. 1111 is displayed in the console.