⬅ Previous Topic
Defining and Calling Functions in JavaScriptNext Topic ⮕
Arrow Functions in JavaScript⬅ Previous Topic
Defining and Calling Functions in JavaScriptNext Topic ⮕
Arrow Functions in JavaScriptIn JavaScript, a function expression is when a function is assigned to a variable. Unlike function declarations, function expressions are not hoisted, which means they are not available before the line they are defined.
Let’s look at a basic example:
const greet = function() {
console.log("Hello, world!");
};
greet(); // calling the function
Output:
Hello, world!
Here, we assigned an anonymous function (a function without a name) to the variable greet
. We can now use greet()
to execute that function.
You can also name your function inside the expression. This can be useful for debugging purposes.
const sayHello = function greetUser() {
console.log("Hello from greetUser!");
};
sayHello();
Output:
Hello from greetUser!
Even though the function is named greetUser
, you still call it using sayHello()
because greetUser
is only available inside the function body.
No. Function expressions are not hoisted like function declarations.
greet(); // Error: Cannot access 'greet' before initialization
const greet = function() {
console.log("Hi!");
};
This results in a ReferenceError because JavaScript doesn’t hoist function expressions. So you must define them before calling.
// Function Declaration
function sayHi() {
console.log("Hi from declaration");
}
// Function Expression
const sayHiAgain = function() {
console.log("Hi from expression");
};
sayHi();
sayHiAgain();
Output:
Hi from declaration Hi from expression
Key Difference: Function declarations are hoisted to the top of their scope, meaning you can call them before their definition. Function expressions are not.
function execute(fn) {
fn(); // call the passed function
}
const printMessage = function() {
console.log("This is a function expression passed as an argument.");
};
execute(printMessage);
Output:
This is a function expression passed as an argument.
function outer() {
return function() {
console.log("Returned from outer!");
};
}
const returnedFunction = outer();
returnedFunction();
Output:
Returned from outer!
Q: Can you store a function expression inside an array or object?
A: Yes! Functions in JavaScript are first-class citizens.
const arr = [
function() { console.log("First function in array"); },
function() { console.log("Second function in array"); }
];
arr[0](); // calls the first function
Output:
First function in array
⬅ Previous Topic
Defining and Calling Functions in JavaScriptNext Topic ⮕
Arrow Functions in JavaScriptYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.