A function is a reusable block of code that performs a specific task. In JavaScript, functions are actually special types of objects.
function a(b) {
console.log(b);
}
console.log(typeof a); // "function" (functions are a type of object)
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]]: ƒ ()
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.
A callback function is a function passed as an argument to another function and executed later.
// 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!
greet()
is a higher-order function.sayGoodbye
is a callback function.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()
.
console.log()
and console.dir()
:console.log()
shows function body or basic object as string.console.dir()
shows full internal properties, like a structured tree.
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.