Categories
JavaScript Tutorials

Anonymous Functions

As we have seen till now, the syntax of writing a function is as follows:

function print(){
  var x = 20;
  var y = 30;
  console.log(x+y);
}

print();

We use the function keyword and declare a function name(print) which is needed to call the function.

But the function name is not always mandatory. That means we can even declare a function as follows:

function(){
  var x = 20;
  var y = 30;
  console.log(x+y);
}

As the function doesn’t have a name, it is known as anonymous function. But we can’t call this function as we do for named functions. However, we can call this function if we write it as a function expression as follows:

var print = function(){
  var x = 20;
  var y = 30;
  console.log(x+y);
}

print();

We can even pass arguments as well a follows:

var print = function(x,y){
  console.log(x+y);
}

print(20,30);

Assignments

  1. Write an anonymous function which can add two numbers
  2. Write an anonymous function which can display the greatest of the three numbers passed in arguments.
  3. Write an anonymous function which can display the given arguments in ascending order
  4. Write an anonymous function which can display the factorial of a number
  5. Write an anonymous function which can to display the reverse of a given number
  6. Write an anonymous function which can check a given number is palindrome or not
  7. Write an anonymous function which can check a given number is prime number or not
  8. Write an anonymous function which can check a given number is Armstrong number or not
  9. Write an anonymous function which can return the factorial of a number to another variable
  10. Write an anonymous function to display the number of digits in the given number
  11. Write an anonymous function that returns an array of all even numbers between 1 and 20.