JavaScript Functions: How to Create Functions in JavaScript

JavaScript Functions

In this guide, you will learn how JavaScript functions work and why they matter. Each section shows what you need to know with examples that help you see how to use them in real code.

Understand the Function of JavaScript

A function is a block of code. You name it once. You can use it again and again. A function runs only when you call it. It helps you organize your code into reusable steps.

Functions keep your code clean. They help you not to repeat the same steps. You write once and reuse.

They help you find problems. Also, they help you work with others. One person writes a function. Another person can use it.

Here is the syntax:

function functionName() {
  // Here your block of code
}

The functionName refers to the name you use to call the function. It has three main parts:

  • functionName is the name of the code block. You use it to invoke the function.
  • () – These are the parentheses where you define the function’s parameters. A function can take one or more parameters, like this: (param1, param2, param3).
  • {} – These curly braces contain the body of the function. This is where you write the code that runs when the function is called.

Here is a quick example:

function helloFunction () {
  return "Hello flatcoding visitors";
}

The function name is helloFunction and it returns the result "Hello flatcoding visitors".

Function Structure

Functions can be hoisted, which means you can call them before they are defined in the code. Named functions are also reusable, as you can call them multiple times by their name.

Parameters vs Arguments in JavaScript Functions

A parameter is a name you write inside the function. It acts like a placeholder. An argument is the real value you give when you call the function.

For example:

function showAge(age) {  
  console.log("Age:", age);
}

showAge(30); 

Output:

Age: 30

This code defines a function showAge that prints the word “Age:” followed by the given number. It runs the function with 30, so it prints Age: 30.

Return Values

You use return to send a result back. Once JavaScript sees return, it stops.

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

let total = add(4, 6);

console.log(total); 

The result:

10

This code defines a function add that returns the sum of two numbers. It calls the function with 4 and 6 and stores the result in total. It prints 10.

Function Scope Basics

A function has its own scope. You cannot use its variables outside.

Here is an example with an error result:

function secret() {
  let code = 1234;
}

console.log(code); // This will give an error

Output:

/index.js:5
console.log(code); // This will give an error
^

ReferenceError: code is not defined

You can see all local and outer variables inside the function, but outside, you cannot access variables inside the function.

Different Ways to Create Functions in JavaScript

You can create functions in JavaScript in several ways. Each one has a different style but works for similar tasks. Here are the common ways:

Function declaration

You use the function keyword and a name.

function double(x) {
  return x * 2;
}

You can call this function before or after it appears.

Function expression

You assign a function to a variable.

let triple = function (x) {
  return x * 3;
};

You cannot call it before you define it.

Arrow Function

const greet = (name) => {
  return "Hello, " + name;
};

This shorter form works well for simple logic.

Arrow Function with Implicit Return

These use a new style.

let square = (x) => x * x;

They are shorter. They do not have their own this.

Function Constructor (not common)

const greet = new Function("name", 'return "Hello, " + name');
console.log(greet("Alice"));

Output:

Hello, Alice

This builds a function from a string, like eval. Avoid this for safety.

Method in Object

const person = {
  greet(name) {
    return "Hello, " + name;
  }
};

You place the function directly in an object. It acts like a method.

Named vs Anonymous Functions in JavaScript

A named function has a name:

function sayHi() {
  console.log("Hi");
}

An anonymous function has no name:

setTimeout(function () {
  console.log("Time's up");
}, 1000);

Use named functions when you plan to reuse them or when you want better error messages.

Use anonymous functions when you only need them once, like in callbacks.

Arrow Functions vs Regular Functions

Arrow functions skip the function keyword. You can skip the curly braces if the body is one line.

let half = x => x / 2;

Arrow functions do not bind their own this. They use the value of this from the outer scope.

Regular functions bind their own this.

let obj = {
  count: 0,
  next: function () {
    setTimeout(() => {
      this.count++;
    }, 100);
  }
};

Here, the arrow function keeps this from obj. A regular function would not.

Pass Arguments and Return Values

Functions can receive input values (called arguments) and return results with the return keyword.

Passing Arguments:

You pass arguments to a function. Just list them inside the parentheses, separated by commas:

function mix(color1, color2) {
  return color1 + " + " + color2;
}

It returns "red + blue" when you call mix("red", "blue").

Default Parameters:

You can assign default values to parameters. These defaults are used when no value is provided:

function greet(name = "Guest") {
  return "Hi, " + name;
}

It calls the greet() function to return "Hi, Guest" since no name was passed.

Rest Parameters:

You can use the rest parameter syntax if you’re unsure how many arguments might be passed. This gathers all remaining arguments into an array:

function total(...nums) {
  let sum = 0;
  for (let n of nums) sum += n;
  return sum;
}

When you call the total(1, 2, 3, 4). It returns 10.

Examples of JavaScript Functions

A simple function to flip a word:

function flip(word) {
  let result = "";
  for (let i = word.length - 1; i >= 0; i--) {
    result += word[i];
  }
  return result;
}

// flip("cake") returns "ekac"

The flip function takes a word and reverses its characters with a loop. It returns a new string with the characters in the opposite order.

Check If a Number Is Odd or Even:

function oddEven(num) {
  return num % 2 ? "Odd" : "Even";
}

The oddEven function checks if a number is odd or even. It returns “Odd” if the number has a remainder when divided by 2; otherwise, it returns “Even”.

Higher-Order Functions and Callbacks

A higher-order function takes another function as input or gives one back.

function doTwice(fn, val) {
  return fn(fn(val));
}

function add1(n) {
  return n + 1;
}

// doTwice(add1, 3) returns 5

This code defines a higher-order function doTwice that applies a given function fn to a value val two times.

It returns 5 because add1(3) is 4 when called as doTwice(add1, 3), and add1(4) is 5.

A callback is a function passed into another.

function repeatAction(times, action) {
  for (let i = 0; i < times; i++) {
    action(i);
  }
}

repeatAction(3, (i) => console.log("Step", i));

This code defines a function repeatAction that runs a given action function a specified number of times.

It prints “Step 0”, “Step 1”, and “Step 2” when called as repeatAction(3, (i) => console.log("Step", i)).

Supported Browsers for JavaScript Functions

All browsers support basic functions. Arrow functions work in:

  • Chrome 45+
  • Firefox 22+
  • Edge 12+
  • Safari 10+

Internet Explorer does not support arrow functions.

Wrapping Up

You have learned what JavaScript functions are and why they are essential for you to write organized code. You also explored how functions work and how to define and call them.

Here is a quick recap:

  • Functions are blocks of reusable code that run when called.
  • They are defined with the function keyword or newer syntax like arrow functions.
  • You can pass parameters and return values to make functions flexible and powerful.
  • Function scope means variables inside a function are private to that function.
  • There are different ways to define functions: declarations, expressions, arrow functions, methods, and even constructors.
  • Named functions are useful for reuse, while anonymous functions are ideal for short, one-time tasks.
  • Arrow functions provide a concise syntax and behave differently with this.

FAQs

Can I return more than one value from a function?

Yes. Use an object or array.
function stats(x, y) {
  return [x + y, x * y];
}

What happens if I do not return anything?

The function returns undefined.

Can a function call itself?

Yes. That is called recursion.
function countDown(n) {
  if (n === 0) return;
  console.log(n);
  countDown(n - 1);
}

Can I store a function inside an object?

Yes. That is called a method.
let cat = {
  speak: function () {
    return "Meow";
  }
};

Do all functions need a name?

No. Anonymous functions work fine in many cases.
Previous Article

Git Delete Branch: Remove Local and Remote Git Branches

Next Article

Understanding Data Types and Conversion in JavaScript

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.