In JavaScript, a function has the type “function”. The [typeof] operator for a function returns the string [“function”], making functions a special data type, different from objects, numbers, strings, and other types.
function myFunc() {
return 'hello';
}
console.log(typeof myFunc); // 'function'
console.log(typeof function() {}); // 'function'A function in JavaScript is a special data type that you can “touch with your hands”, like a gift box that can be opened (called) at any time! 🎁
Functions in JavaScript have a special [“function”] type that distinguishes them from all other data types:
function greet() {
return 'Hello!';
}
const arrowFunc = () => 'Hello!';
const obj = {
method() { return 'Hello!'; }
};
console.log(typeof greet); // 'function'
console.log(typeof arrowFunc); // 'function'
console.log(typeof obj.method); // 'function'// Function can be a variable value
const myFunction = function() {
return 'result';
};
console.log(typeof myFunction); // 'function'
// Function can be passed as an argument
function execute(func) {
return func();
}
execute(myFunction); // 'result'function myFunc() {}
// Function is an object!
console.log(myFunc instanceof Object); // true
console.log(typeof myFunc); // 'function'
// Function can have properties
myFunc.customProperty = 'value';
console.log(myFunc.customProperty); // 'value'// Function can be:
// 1. Assigned to a variable
const func1 = function() {};
// 2. Passed as an argument
function callFunc(fn) { fn(); }
// 3. Returned from another function
function createFunc() {
return function() { return 'created'; };
}
// 4. Stored in an array
const funcs = [function() { return 1; }, function() { return 2; }];function processData(data, callback) {
// Check that callback is a function
if (typeof callback === 'function') {
return callback(data);
}
throw new Error('Callback must be a function');
}function apiCall(url, successCallback, errorCallback) {
if (typeof successCallback !== 'function') {
throw new Error('successCallback must be a function');
}
if (typeof errorCallback !== 'function') {
throw new Error('errorCallback must be a function');
}
// ... API call logic
}// ❌ Error — thinking function is a regular object
const obj = {};
const func = function() {};
console.log(typeof obj); // 'object'
console.log(typeof func); // 'function' (special type!)// ❌ Error — not checking type
function bad(data, callback) {
return callback(data); // May error if callback is not a function
}
// ✅ Correctly — check type
function good(data, callback) {
if (typeof callback === 'function') {
return callback(data);
}
return data;
}Understanding function type helps properly work with functions as values and avoid errors when passing them as arguments! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪