Functions
EasyFunctions are reusable blocks of code. JavaScript has three ways to create them: function declarations, function expressions, and arrow functions. Functions are "first-class" in JS, meaning they're values you can pass around.
Interactive Visualization
Code
1function greet(name) {2 return "Hello, " + name3}45const result = greet("Alice")6console.log(result)
Call Stack
global()
locals:greet: fn
this:window
Console Output
No output yet
Step 1/6Function greet is defined. It exists in memory but has not been called yet.
Key Insight:Every function call creates a new execution context (frame) that is pushed onto the call stack. When the function returns, the context is destroyed and popped off.
Key Points
- Function declarations are hoisted (can call before definition)
- Function expressions are NOT hoisted
- Arrow functions have shorter syntax and no own "this"
- Functions can return values or undefined by default
- Parameters can have default values
Code Examples
Function Declaration
// Can call before definition (hoisting!) greet("Alice"); // "Hello, Alice" function greet(name) { return "Hello, " + name; } // Parameters and return function add(a, b) { return a + b; // returns the sum } add(2, 3); // 5
Function declarations are hoisted to the top
Function Expression
// Stored in a variable const greet = function(name) { return "Hello, " + name; }; // NOT hoisted - can't call before this line greet("Bob"); // "Hello, Bob" // Can be anonymous or named const factorial = function fact(n) { return n <= 1 ? 1 : n * fact(n - 1); };
Function expressions are NOT hoisted
Arrow Functions
// Full syntax const add = (a, b) => { return a + b; }; // Short syntax (implicit return) const add2 = (a, b) => a + b; // Single parameter (no parens needed) const double = x => x * 2; // No parameters const sayHi = () => "Hello!"; // Arrow functions have no own 'this'
Arrow functions are concise and inherit this from parent scope
Default Parameters
function greet(name = "World") { return "Hello, " + name; } greet(); // "Hello, World" greet("Alice"); // "Hello, Alice" // Works with arrow functions too const greet2 = (name = "World") => "Hello, " + name;
Default values are used when argument is undefined
Common Mistakes
- Forgetting to return a value (function returns undefined)
- Using arrow functions when you need your own "this"
- Not understanding hoisting differences between declaration and expression
Interview Tips
- Know when to use each function type
- Explain the "this" difference with arrow functions
- Be able to convert between function syntaxes