Functions in JavaScript

Learn the basics of functions in JavaScript, how to define, call, return values, and understand the difference between declarations and expressions.

Loading...
Functions in JavaScript

What are Functions in JavaScript?

In JavaScript, Functions are blocks of reusable code that do a specific task.

Functions help organize code, making it easier to reuse, maintain, and understand. They allow you to break down a complex problem into smaller, more manageable tasks.

You can define a function once and use it again and again whenever needed.

For example:

function sayHello() {
  console.log("Hello!");
}

Here, sayHello is a function. When you call it using sayHello();, it will show "Hello!" in the console.


Function Declaration

Syntax:

function functionName(parameters) {
  // code to run
}

Here,

  • function: The keyword that tells JavaScript you’re creating a function.
  • functionName: The name you give your function so you can use it later. For example: sayHello, addNumbers, etc.
  • parameters (optional): Inside parentheses (), these are inputs your function can take. You can have zero, one, or more parameters separated by commas. For example: (name), (name, age).
  • Function body {}: The code inside the curly braces {} is what the function does when called. It runs this block of code every time you use the function.

Example:

function greet(name) {
  console.log("Hello, " + name + "!");
}

Here,

  • function: keyword
  • greet: function name
  • (name): one parameter called name
  • { console.log("Hello, " + name + "!"); }: code to run

javascript function syntax


Calling Functions

After defining a function, you run it by calling or invoking it. Calling a function means running the code inside it.

How to call a function?

To call a function, just write the function’s name followed by parentheses ().

For example:

function sayHello() {
  console.log("Hello!");
}
 
sayHello();

Here, sayHello(); calls the function and prints Hello! to the console.

Calling a function with parameters

If the function expects parameters (inputs), put the required inputs inside the parentheses when calling.

For example:

function greet(name) {
  console.log("Hello, " + name + "!");
}
 
greet("Shefali"); // Output: Hello, Shefali!

Here, greet("Shefali"); will print Hello, Shefali! to the console.

If you provide some other parameter, for example:

greet("Mark"); // Output: Hello, Mark!

Then this will print Hello, Mark! to the console.


Return Statements and Return Values

What is a return statement?

The return statement gives back a value from the function, so you can store it or use it somewhere else in your code.

When a function hits a return, it stops running and gives back the result.

Why use return?

The return statement is used to get an output from the function. So you can use that result elsewhere in your code.

Example:

function add(a, b) {
  return a + b;
}
 
let sum = add(2, 3);
console.log(sum); // Output: 5

Here,

  • add is a function that takes two parameters, a and b.
  • Inside the function, return a + b; returns the sum of the two numbers.
  • When you call add(2, 3), the function adds 2 and 3 and returns 5.
  • That returned value is saved in a variable called sum using let sum = add(2, 3);.
  • Then, console.log(sum); prints the value 5 on the console.

Some Important Points

  • Without return, a function returns undefined by default.
  • When a function hits a return, it stops running and gives back the result and no more code inside it runs.

Function Naming Conventions

While naming your functions, there are some points to consider so that your code is more readable.

  • Use meaningful names: The name should explain what the function does. For example: calculateTotal(), showMessage().
  • Start with a verb: Functions usually perform actions, so start names with verbs like get, set, calculate, show, update, etc. For example: fetchData(), printReport().
  • Use camelCase: Start with a lowercase letter, and capitalize each new word after that. For example: getUserName(), sendEmail().
  • Avoid spaces or special characters: Use letters, numbers, and underscore _ (though underscore is less common in JS naming). For example: process_order is less common, prefer processOrder.
  • Be consistent: Stick to one style throughout your codebase.

Function Expression

A Function Expression is when you create a function and assign it to a variable.

Example:

const sayHello = function () {
  console.log("Hello!");
};

Here, an anonymous function (a function without its own name) is stored in the variable sayHello, and you can run it by calling the variable name.

sayHello(); // Output: Hello!

Key Points of Function Expression

  • Function Expressions are not hoisted (you cannot use them before they are created).
  • These are useful when you want to pass functions as values or assign them dynamically.

Function Declaration vs Expression

Function Declaration

  • Declared using the function keyword with a name.
  • Created before the code runs.
  • Can be called anywhere in the scope, even before the declaration.

Example:

sayHello();
 
function sayHello() {
  console.log("Hello!");
}

This works because function declarations are hoisted.

Function Expression

  • The function is stored in a variable.
  • Created only when the code reaches that line (not hoisted).
  • Cannot be called before the line where it’s defined.

Example:

sayHello(); // Error: sayHello is not defined
 
const sayHello = function () {
  console.log("Hello!");
};

This causes an error if called before the expression.

Key Differences Between Function Declaration and Expression

Aspect Function Declaration Function Expression
Syntax function name() {} const name = function() {}
Hoisting Hoisted (can call before defining) Not hoisted (you must define it before calling)
Naming Must have a name Can be anonymous or named
Use case General reusable functions When you want to assign or pass functions

Why Use Functions?

  • Functions avoid rewriting the same code and makes your code reusable.
  • Break large programs into smaller, manageable pieces.
  • Functions clearly define their purpose, so it improves readability.
  • Debug and update specific parts without affecting the rest.

Support my work!