JavaScript Function Concepts

What is a Function?

A function is a reusable block of code that performs a specific task. In JavaScript, functions are actually special types of objects.

Example:


function a(b) {
    console.log(b);
}
console.log(typeof a); // "function" (functions are a type of object)
        

Functions are Objects in JavaScript

Using console.dir(), we can inspect function internals like any object.


function a(b) {
    console.log(b);
}

console.dir(a);
        

Console Output (simplified):


ƒ a(b)
length: 1
name: "a"
prototype: {
    constructor: ƒ a(b)
}
[[Prototype]]: ƒ ()
        

Functions Can Hold Properties

We can add custom properties to a function, just like objects.


function a(b) {
    console.log(b);
}

a.userName = "Priyanshu";
a.userAge = 20;

console.dir(a);
        

Console Output:


ƒ a(b)
userName: "Priyanshu"
userAge: 20
length: 1
name: "a"
        

Conclusion: This proves functions behave like objects and can store data.

What is a Callback Function?

A callback function is a function passed as an argument to another function and executed later.

Example:


// Function that takes a callback
function greet(callback) {
    console.log("Hello!");
    callback(); // Executes the callback
}

// Callback function
function sayGoodbye() {
    console.log("Goodbye!");
}

greet(sayGoodbye);
        

Console Output:


Hello!
Goodbye!
        

Explanation:

What is console.dir()?

console.dir() is used to display an interactive, expandable list of the properties of a JavaScript object. It helps you inspect objects or functions more deeply than console.log().

Difference Between console.log() and console.dir():

Example:


function greet(name) {
    return "Hello " + name;
}

console.log(greet);  // Outputs function code
console.dir(greet);  // Shows internal structure
        

Console Output (simplified):


ƒ greet(name)
length: 1
name: "greet"
prototype: {
    constructor: ƒ greet(name)
}
[[Prototype]]: ƒ ()
        

Use console.dir() to deeply inspect any function or object in JavaScript.