Function Basics

By Syncfusion®, Inc. · Last updated

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.

formatPrice (price) 349 "₹349.00" Input goes in, the return value comes out.

A function turns its input into an answer, the same way every time.

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:

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:

One function, called twice with different names

function greet(name) {
  console.log(`Hello, ${name}! Your cart is ready.`);
}
greet("Asha");
greet("Ravi");

Expected output:

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

Function Declaration (Statement)

function name(parameter1, parameter2) {
  // the work
  return answer;
}
  • function keyword, then a name, then ( ) and { }.
  • Defining does not run it. Calling name(...) runs it.

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:

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.

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:

498
300

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

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:

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.

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:

18
a: undefined
b: 18 | total: 118

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

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:

0 40

Function Hoisting

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

Calling a function above the line that declares it

console.log(formatPrice(349));

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

Expected output:

₹349.00

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

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.

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

MistakeWrong ideaCorrect ideaWhat goes wrong
Printing instead of returningconsole.log gives the value backOnly return doesThe result is undefined
greet without ()Naming it runs itgreet() runs itNothing happens
Arguments in the wrong orderThey match by nameThey match by positionPrice and quantity swap
Code after returnIt still runsreturn ends the functionThe line is skipped
Calling a const function earlyAll functions are hoistedOnly declarations areReferenceError: Cannot access 'formatPrice' before initialization

Quick reference

SyntaxMeaning
function name(a, b) { ... }a function declaration with two parameters
name(1, 2)call the function, passing two arguments
namethe 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 returnthe call gives back undefined
declaration called above its lineworks, because declarations are hoisted

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.