JavaScript Fundamentals / Functions

Function

⌺ Functions Overview

  • A function is created using the function keyword, followed by a name and parentheses ().

  • Function names follow the same rules as variable names (letters, numbers, _, $).

  • You can add parameters inside the parentheses, separated by commas: (param1, param2, ...)

  • The code the function runs goes inside curly braces {}.

✅ Example

function name(param1, param2) {
  // code to run
}
  • Parameters → placeholders in the function definition.

  • Arguments → actual values passed when the function is called.

  • Inside a function, parameters act like local variables.


➡️ Function Declaration

A Function Declaration is the traditional way to define a function. It starts with the function keyword, followed by the function name and any parameters the function needs.

Example: Below is an example that illustrates the use of Function Declaration.

// Function declaration
function add(a, b) {
    console.log(a + b);
}

// Calling a function
add(2, 3);
5

▶️ Function Expression

Function Expression is another way to define a function. Here, the function is defined inside a variable, and the function's value (its returned value) is stored in that variable.

Example: Below is an example that illustrates the use of Function Expression.

// Function Expression
const add = function (a, b) {
      console.log(a + b);
}

// Calling function
add(2, 3);
5

🧠 Explanation:

  • function add(a, b) defines a function named add that takes two parameters.

  • console.log(a + b); prints the sum of the two arguments.

  • add(2, 3); calls the function and passes 2 and 3, so it prints 5.


🗝️ Key Differences: Function Declaration vs. Function Expression

  • Function Declaration: The function is defined and can be called anywhere in the code (even before it’s defined, due to something called "hoisting").

  • Function Expression: The function is defined as part of an expression (usually assigned to a variable), and it can only be called after the line where it’s defined.


❇️ Function Return

  • The return statement ends the function immediately.

  • Whatever value you put after return is sent back to the place where the function was called.

  • This returned value can be stored in a variable, printed, or used in another expression.

✅ Example

function myFunction(a, b) {
  // returns the product of a and b
  return a * b;
}

let x = myFunction(4, 3);
console.log(x);  // prints 12

const y = 10;
console.log(y);  // prints 10
12
10

📝 Explanation

  • myFunction(4, 3) is called with arguments 4 and 3.

  • Inside the function, it calculates 4 * 3 and hits return a * b.

  • The return keyword sends 12 back to the caller.

  • That returned value is stored in variable x, so console.log(x) shows 12.

  • After that, y is logged, printing 10.