Functions - Javascript

Declaring  a Function which log on console

// Declaring a function
function sayHello(){
  console.log("Say Hello!");
}

// Using the function
sayHello();

Output:

Say Hello!

 

Declaring a function which return some value

// Declaring a function
function sayHello(){
  return "Say Hello!";
}

// Using the function
console.log(sayHello());

Output:

Say Hello!

 

Supplying arguments to function

// Declaring a function
function sayHello(name){
  return "Say Hello , " + name;
}

// Using the function
console.log(sayHello());

Output:

Say Hello , undefined

Can you guess how come you got the value undefined

 

The reason is you have not passed name argument to function, now let's supply name argument

// Declaring a function
function sayHello(name){
  return "Say Hello , " + name;
}

// Using the function
console.log(sayHello("Jon Snow"));

Output:

Say Hello , Jon Snow

 

Now what if you want to make functional arguments optional, i.e even if some argument is not passed it acquire a default value.

// Declaring a function with default values
function sayHello(name="Jenny"){
  return "Say Hello , " + name;
}

// Using the function without passing argument
console.log(sayHello());

// Using the function with argument
console.log(sayHello("Mark"));

Output: 

Say Hello , Jenny
Say Hello , Mark

 

 

Defining function and assiging it to a variable

/*
As you can see we are assigning a function (it is an anonymous function)
to a variable doubleUp
*/
const doubleUp = function(x = 9) {
  return 2*x;
}

/*
Using function without providing any
argument so function will use default argument
which is 9
*/
const a = doubleUp();

/*
here we are providing an argument 3, so default argument
won't be used
*/
const b = doubleUp(3);

console.log(a);
console.log(b);

Output:

18
6

 

Immediately Invoked Function Expressions (IIFE)

When some function is declared and run at the same time it is an IIFE

// Immediately Invoked Function Expressions (IIFE)
(function(x,y){
    console.log(x + y);
})(5,7);

Output:

12

Later on in our course we will discuss more about use cases for IIFE

Methods

When we put some function inside an object it is called methods

// Methods
const methodExamples = {
  add : function(x,y){
    return x+y;
  },
  subtract : function(x,y) {
    return x-y;
  },
  multiply : function(x,y) {
    return x*y;
  },
  divide : function(x,y) {
    return x / y;
  }
}

// You can also add new mthods to object
// even after object creation
methodExamples.sqr = function(x){
  return x*x;
}


console.log(methodExamples.add(3,6));
console.log(methodExamples.subtract(10,7));
console.log(methodExamples.multiply(2,9));
console.log(methodExamples.divide(15,5));
console.log(methodExamples.sqr(7));

Output:

9
3
18
3
49