# Function Basics

Course: [JavaScript](https://www.devtutorials.ai/learn/javascript) · Section: Functions
Source: https://www.devtutorials.ai/learn/javascript/functions/function-basics

> What a function is and why it helps, declaring and calling functions, parameters, arguments and default values, return versus console.log, and function hoisting.

## What Is a Function?

**Function** = a named block of code you can run again and again.

- **Define** it once: give the code a name.
- **Call** it many times: `formatPrice(349)`.
- Give it inputs (**parameters**) and get back an answer (**return**).

**Simple lesson:** a function is a small machine. Values go in, an answer comes out.

### A Real-World Example

A shop shows prices in 50 places: cards, cart, bill and emails.
One function `formatPrice(349)` gives `"₹349.00"` everywhere.
To change the format later, you edit one function, not 50 lines.

<figure className="ts-fig">
  <svg viewBox="0 0 560 160" role="img" aria-label="The number 349 goes into a machine called formatPrice and comes out as the text rupee 349.00." width="100%">
    <rect x="0" y="0" width="560" height="160" rx="12" fill="#f8fafc" stroke="#e2e8f0" />
    <rect x="200" y="40" width="160" height="70" rx="12" fill="#1e3a8a" />
    <text x="280" y="72" textAnchor="middle" fontSize="14" fill="#ffffff">formatPrice</text>
    <text x="280" y="94" textAnchor="middle" fontSize="11" fill="#bfdbfe">(price)</text>
    <text x="60" y="80" fontSize="16" fontFamily="monospace" fill="#1e40af">349<animate attributeName="x" values="40;170;170" keyTimes="0;0.45;1" dur="3s" repeatCount="indefinite" /></text>
    <text x="390" y="80" fontSize="16" fontFamily="monospace" fill="#166534">"₹349.00"<animate attributeName="opacity" values="0;0;1" keyTimes="0;0.55;1" dur="3s" repeatCount="indefinite" /></text>
    <text x="280" y="140" textAnchor="middle" fontSize="12" fill="#475569">Input goes in, the return value comes out.</text>
  </svg>
  <figcaption>A function turns its input into an answer, the same way every time.</figcaption>
</figure>

One box below fails on purpose to show hoisting. Its title says so.

## What You Will Learn

1. Why functions help.
2. How to declare and call a function.
3. Parameters, arguments and default values.
4. `return`, and how it differs from `console.log()`.
5. Hoisting: calling a function before its line.

## Introduction to Functions

Without a function, you repeat yourself:

```js runnable title="The same greeting written out twice, with no function"
console.log("Hello, Asha! Your cart is ready.");
console.log("Hello, Ravi! Your cart is ready.");
```

With a function, you write the work once and change only the name:

```js runnable title="One function, called twice with different names"
function greet(name) {
  console.log(`Hello, ${name}! Your cart is ready.`);
}
greet("Asha");
greet("Ravi");
```

Expected output:

```text
Hello, Asha! Your cart is ready.
Hello, Ravi! Your cart is ready.
```

## Function Declaration (Statement)

```js
function name(parameter1, parameter2) {
  // the work
  return answer;
}
```

- `function` keyword, then a name, then `( )` and `{ }`.
- Defining does **not** run it. Calling `name(...)` runs it.

```js runnable title="A declaration defines the function, and a call runs it"
function showBanner() {
  console.log("Festival sale: 20% off");
}
console.log("Before the call");
showBanner();
showBanner();
```

Expected output:

```text
Before the call
Festival sale: 20% off
Festival sale: 20% off
```

## Parameters vs Arguments

- **Parameter** = the name in the definition: `function total(price, qty)`.
- **Argument** = the real value in the call: `total(249, 2)`.
- They match by **position**: first to first, second to second.

```js runnable title="Two parameters, filled by two arguments in the same order"
function lineTotal(price, quantity) {
  return price * quantity;
}
console.log(lineTotal(249, 2));
console.log(lineTotal(60, 5));
```

Expected output:

```text
498
300
```

A missing argument is `undefined`. A **default value** fills the gap:

```js runnable title="A missing argument is undefined, unless the parameter has a default"
function noDefault(name) {
  return "Hi " + name;
}
function withDefault(name = "guest") {
  return "Hi " + name;
}
console.log(noDefault());
console.log(withDefault());
console.log(withDefault("Meena"));
```

Expected output:

```text
Hi undefined
Hi guest
Hi Meena
```

## Return Statement

- `console.log()` **shows** a value on the screen. The program cannot use it.
- `return` **gives back** a value. The program can store and reuse it.
- A function with no `return` gives back `undefined`.

```js runnable title="Printing an answer compared with returning it"
function printTax(price) {
  console.log(price * 0.18);
}
function getTax(price) {
  return price * 0.18;
}
const a = printTax(100);
const b = getTax(100);
console.log("a:", a);
console.log("b:", b, "| total:", 100 + b);
```

Expected output:

```text
18
a: undefined
b: 18 | total: 118
```

`return` also **stops** the function at once. Lines after it never run:

```js runnable title="return leaves the function as soon as it runs"
function deliveryFee(total) {
  if (total >= 499) return 0;
  return 40;
  console.log("never printed");
}
console.log(deliveryFee(620), deliveryFee(150));
```

Expected output:

```text
0 40
```

## Function Hoisting

**Hoisting** = JavaScript reads function declarations before running other code.
So you can call a declared function above its line.

```js runnable title="Calling a function above the line that declares it"
console.log(formatPrice(349));

function formatPrice(price) {
  return "₹" + price.toFixed(2);
}
```

Expected output:

```text
₹349.00
```

A function stored in a `const` is **not** ready early. Calling it first is an error:

```js runnable expect-error title="The same call fails when the function is stored in a const"
console.log(formatPrice(349));

const formatPrice = function (price) {
  return "₹" + price.toFixed(2);
};
```

## Functions on a Web Page

One `formatPrice` function serves every row and the total. Change the format once (try `"Rs. "`), and the whole cart changes.

```js runnable preview="cart" title="One formatPrice function used all over a cart"
function formatPrice(price) {
  return "₹" + price.toFixed(2);
}

let total = 0;

function addToCart(name, price) {
  const li = document.createElement("li");
  li.textContent = `${name} — ${formatPrice(price)}`;
  document.querySelector("#cart").append(li);
  total += price;
}

addToCart("Notebook", 60);
addToCart("Steel bottle", 299);
addToCart("Pencil box", 120);
document.querySelector("#total").textContent = formatPrice(total);
console.log("Total shown:", formatPrice(total));
```

**Easy way to remember:** `console.log` **talks** to you. `return` **hands** the value to your code.

## TL;DR

- Define with `function name(params) { ... }`, run with `name(args)`.
- Parameters are names; arguments are the real values, matched by position.
- `name = "guest"` gives a default for a missing argument.
- `return` gives back a value and ends the function. No `return` means `undefined`.
- Declarations are hoisted; functions stored in `const` are not.

## Try this

In the **Return Statement** example, change `getTax` to use `console.log` instead of `return`. Now `total` becomes `NaN`, because `100 + undefined` is not a number.

## Check Yourself

## Common mistakes

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| Printing instead of returning | `console.log` gives the value back | Only `return` does | The result is `undefined` |
| `greet` without `()` | Naming it runs it | `greet()` runs it | Nothing happens |
| Arguments in the wrong order | They match by name | They match by position | Price and quantity swap |
| Code after `return` | It still runs | `return` ends the function | The line is skipped |
| Calling a `const` function early | All functions are hoisted | Only declarations are | `ReferenceError: Cannot access 'formatPrice' before initialization` |

## Quick reference

<div className="tscroll">

| Syntax | Meaning |
|---|---|
| `function name(a, b) { ... }` | a function declaration with two parameters |
| `name(1, 2)` | call the function, passing two arguments |
| `name` | the function itself, not a call |
| `function name(a = 10) { ... }` | a parameter with a default value, used when the argument is missing |
| `return value;` | hand `value` back to the caller and end the function |
| function without `return` | the call gives back `undefined` |
| declaration called above its line | works, because declarations are hoisted |

</div>

## Exercises

## What to Remember

- A function is named, reusable code.
- Inputs come in through parameters; the answer goes out with `return`.
- Write it once, call it everywhere.

Next: **Types of Functions**. Arrow functions, callbacks, functions that return functions, and more.
