Skip to main content

Command Palette

Search for a command to run...

JavaScript Functions

Updated
•2 min read•View as Markdown
S

CSE Under grad. || Trying to be a better developer each day || Consistency is the key

Introduction

Functions are basicly reusable blocks of code that save us from writing the same logic over and over again.

Think of them like little helpers: you give them some input, they do something usefull, and hand you back a result (or just do a side effect). Almost every JavaScript program needs them!There are two main ways to create functions: function declaration and function expression.Function Declaration looks like this:

javascript

function add(a, b) {
  return a + b;
}

Super clean and straighforward. You can even call it before you write it in the file:

javascript

console.log(add(5, 3));     // 8 (it works!)
function add(a, b) { return a + b; }

This magic is becuase of hoisting. JavaScript kinda moves function declarations to the top of their scope during creation phase — so they’re ready to go from the start.Function Expression is different. You create a function and assign it to a variable:

javascript

const multiply = function(x, y) {
  return x * y;
};

Or the cooler arrow version:

javascript

const multiply = (x, y) => x * y;

Now try calling it before that line:

javascript

console.log(multiply(4, 7));   // Error: Cannot access 'multiply' before initialization
const multiply = (x, y) => x * y;

It breaks! Only the variable gets hoisted (if using var), but the function part stays put. So expressions aren’t avalible until code actually reaches them.Quick side-by-side comparison

  • Declaration → fully hoisted → call it from anywhere in scope

  • Expression → not hoisted (the function bit) → define before use

  • Declaration → starts with function keyword

  • Expression → usually assigned to const/let/var (or in callbacks)

When should you use which? I usualy pick declarations for regular helper functions at the top — they feel more readable and I like calling them anywhere.
I go for expressions when:

  • Its a one-time thing (IIFEs, event handlers)

  • I want const (so nobody reassigns it)

  • Arrow functions in .map() or React stuff

Quick test I did for the assignment

// Declaration
function multiplyDecl(a, b) {
  return a * b;
}

// Expression
const multiplyExpr = function(a, b) {
  return a * b;
};

console.log(multiplyDecl(6, 4));    // 24
console.log(multiplyExpr(6, 4));    // 24

Both do the same after they’re defined — but only declaration survives being called too early.