Skip to content

Latest commit

 

History

History
109 lines (82 loc) · 2.36 KB

File metadata and controls

109 lines (82 loc) · 2.36 KB

First Class Functions

  • Functions are heart ♥ of Javascript.

Function statement

Below way of creating function are function statement.

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

Function Expression

Functions can be assigned to variables. Function acts like a variables.

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

Difference between function statement and expression

The difference between these is of Hoisting.

a(); // "Hello A"
b(); // TypeError
function a() {
  console.log("Hello A");
}
var b = function () {
  console.log("Hello B");
};
// Function Declaration hoists both declaration and definition while function Expression only hoists the variable declaration.

Function Declaration

Other name for function statement.

Anonymous Function

function without a name.

function () {

}// this is going to throw Syntax Error - Function Statement requires function name.
  • They don't have their own identity. So an anonymous function without code inside it results in an error.
  • Anonymous functions are used when functions are used as values eg. the code sample for function expression above.

Named Function Expression

Same as Function Expression but function has a name instead of being anonymous.

var b = function xyz() {
  console.log("b called");
};
b(); // "b called"
xyz(); // Throws ReferenceError:xyz is not defined.
// xyz function is not created in global scope. So it can't be called.

Parameters vs Arguments

var b = function (param1, param2) {
  // labels/identifiers are parameters
  console.log("b called");
};
b(arg1, arg2); // arguments - values passed inside function call

First Class Function

  • We can pass functions inside a function as arguments.
  • We can return a function.
  • These ability are altogether known as First class function.
  • Also known as First Class Citizen
  • It is programming concept available in some other languages too.
var b = function (param1) {
  console.log(param1); // prints " f() {} "
};
b(function () {});

// Other way of doing the same thing:
var b = function (param1) {
  console.log(param1);
};
function xyz() {}
b(xyz); // same thing as prev code

// we can return a function from a function:
var b = function (param1) {
  return function () {};
};
console.log(b()); //we log the entire fun within b.