Function Declaration & Expression

·

2 min read

Function Declaration & Expression

What is a Function?

Function-

  • is a block of code that encapsulates with self contained behavior.
  • is a set of organized instructions towards specific functionality.
  • code inside it runs only when it needed.
  • creates reusable code.

Declaration-

  • Declaration is declared when function created means we can call function before it is defined.
    function name (param1, param2) {
             code block.....
            }

it includes-

  • Function keyword
  • Function Name
  • Parameters -Functions takes input from here and param act as local placeholder variables for value which pass into function as an input at the time of function invocation.
  • Code block -Main body with code statement.

Lets call a function-

    function greeting(name) {
  console.log("Hello " + name + "!");
}
greeting("Arif");

o/p->    Hello Arif!

It has-

  • name -> parameter ->placeholder
  • Arif -> argument ->value at the invocation time

Expression-

  • Created function and assigned it to variable, it does not have name means we must define function before we call it.
    const name= function(firstName){
  return "Hello "+ firstName
}
console.log(name("Arif"))

Here-

  • We have taken a variable to store the function.
  • So to call this function we will use variable name-

    name("Arif")

so both can be written as below-

function declaration(){
  return "a declaration function"
}

let functionExp=function(){
  return "a function expression"
}

Few differences between declaration and expression-

  • Declarations are hoisted means we can call a function before it is defined but Expressions are not hoisted.
  • In Declaration we have to wait until entire script has been parsed while in Expression we can use function immediately after defined.
  • Declaration can't be used as an argument to another function while Expression can be used.
  • Declaration can't anonymous while Expression can be anonymous.
  • Declaration code is more readable.
  • Expression code is more flexible as assign to different variable. We can use same function in different place.