FUNCTIONS | JAVASCRIPT | PROGRAMMING

JavaScript Functions, a Guide for Beginners

Understand how to use functions in your code.

Matt Connors
7 min readDec 19, 2024
Photo by Mohammad Rahmani on Unsplash

Why Learn Functions?

Functions are probably the most important part of programming after variables, allowing you to:

  • Reuse code so that you don’t repeat yourself;
  • Break your program up into smaller and more manageable pieces, increasing readability and maintainability of the project; and
  • Make debugging easier, because they isolate specific tasks.

Mastering this concept is key if you decide to pursue anything serious with programming, and is essential whether you’re creating websites, mobile apps, or games.

Today, we’ll delve into JavaScript’s functions, hopefully ensuring a solid foundation for your journey into programming.

What is a Function in JavaScript?

A function is a reusable block of code designed to perform a specific task, a block of code being merely a group of different instructions.

Functions are essentially tools that take an input, process that input, and return an output.

Imagine a plant that takes carbon dioxide and converts it into oxygen, and you can name that plant a function.

Declaring a Function

Function declaration is the process by which you define what a particular function will do.

The basic syntax is:

function functionName(parameters) {
// Code to run
return value;
}

Here are the moving parts:

  • function is the keyword used to declare the function, like how variables have let, const and var;
  • functionName is the chosen name for the function, which should be descriptive of the action that it performs;
  • parameters (optional) are the placeholders for the inputs that will be passed into the function; and
  • return (optional) is the keyword that is used to send back the output — if no return statement is made, the function returns undefined by default.

Here’s an example function that takes the parameter name and outputs the string Hello, ${name}!.

The function is called using greet("Alice") , which returns the string "Hello, Alice!". This is then printed to the console by console.log().

function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // Output: Hello, Alice!

Function Expressions

Functions don’t have to be declared, they can also be assigned to a variable.

This is called a function expression.

const greet = function(name) {
return `Hello, ${name}!`;
};
console.log(greet("Bob")); // Output: Hello, Bob!

Function expressions are often used when you need to pass functions as arguments.

Function expressions are a type of anonymous function, meaning that they themselves do not have a name.

Arrow Functions: Simpler Yet Harder

Arrow functions, which were introduced in ES6 back in 2015, represent a simpler and more concise way for declaring functions.

Syntax:

const functionName = (parameters) => expression;

Syntax Guide for Arrow Functions

  • If the function doesn’t have any parameters, you must include the parentheses:
  • const functionName = () => expression;
  • If the function only has one parameter, you can skip the parentheses:
  • const functionName = param1 => expression;
  • If the function has more than one parameter, you need to contain all of them in the parentheses:
  • const functionName = (param1, param2) => expression;

Arrow functions are usually used for short one-liners, but if you need more complexity, you can still use curly braces around the whole body like in a traditional function.

  • If you are only writing one line in the body of the function, for example if you are returning the result of an operation, you don’t need curly braces:
  • const functionName = x => 2 * x;
  • If the body has more than one line, you will need curly braces to contain all the body:
  • const functionName = (x, y) => {let z = x + y; return 2 * z};

If the arrow function returns a value and only contains a single expression, you can also skip the return keyword:

  • const square = x => x * x;

Simplifying the Greeting Function

We can now rewrite our original function in a more concise way.

// Using the traditional function syntax
function greet(name) {
return `Hello, ${name}!`;
};
console.log(greet("Meghan")); // Output: Hello, Meghan!

// Using an arrow function
const greet = (name) => `Hello, ${name}!`;
console.log(greet("Charlie")); // Output: Hello, Charlie!

// Both work the exact same here, one is just simpler to read and write.

Key Differences Between Arrow and Traditional Functions

While the biggest difference between the two is the ease of using arrow functions when writing one-liners, there is another big difference between the two:

Arrow functions don’t bind their own this keyword, which is important in object-oriented programming.

  • Traditional functions' value for this depends on how the function is called.
  • Arrow functions, however, inherit the value for this from the context surrounding them.

This isn’t vital information for now, but as you learn more about JavaScript, you will run into this a lot. For now, you should just keep in mind that arrow functions are generally easier to work with due to greater readability.

For more information on this binding, I’ve left a piece from codementor.io in the Further Reading section.

Parameters and Default Values

Parameters and Arguments

Functions can have parameters, which are placeholders for input values.

Input values are called arguments.

function square(num) {
return num ** 2;
}
let x = 5;
console.log(square(x)); // Output: 25

In the example above:

  • num is the parameter; and
  • x is the argument

Default Values

You can specify a default value for any parameter so that, if no value is provided for a parameter, the function will use said default.

For example:

function greet(name="World") {
return `Hello, ${name}!`;
}
console.log(greet()); // Output: Hello, World!
console.log(greet("Jane")); // Output: Hello, Jane!

The parameter and the default don’t have to be mashed together with no spaces, but it is common practice to not leave space between the name of the parameter and the default value provided.

Practical Examples

Adding Two Numbers

A function that sums two numbers:

function sum(a, b) {
return a + b;
}
console.log(sum(3, 7)); // Output: 10

Checking if a Number is Even

A function to check whether a number is even. Will output true if the argument is even:

function isEven(num) {
return num % 2 === 0;
}
console.log(isEven(4)); // Output: true
console.log(isEven(7)); // Output: false

Converting Celsius to Fahrenheit

A function to convert temperatures:

function toFahrenheit(celsius) {
return (celsius * 9/5) + 32;
}
console.log(toFahrenheit(0)); // Output: 32

Capitalizing a String

A function to capitalize the first letter of a string (slightly more complex application, as you can see):

function capitalizeString(val) {
return String(val).charAt(0).toUpperCase() + String(val).slice(1);
}

This example was taken from StackOverflow, the link is in the Further Reading section.

Functions Inside Functions

Functions can be nested inside other functions. This is usually done to organize code and avoid ‘polluting’ the global scope with too many variables and/or irrelevant functions.

For instance:

function outerFunction(x) {
function innerFunction(y) {
return x + y;
}
return innerFunction(5);
}
console.log(outerFunction(10)); // Output: 15

Common Mistakes and How to Avoid Them

Forgetting to Use the Return Keyword

As discussed before, if no return keyword is provided and no value is explicitly returned, the function will implicitly return undefined, which could sometimes cause issues.

It is also common to simply forget to put the return keyword before the expression you want to return, which will once again return undefined.

For example:

function greet(name) {
`Hello, ${name}!`; // Missing return
}
console.log(greet("Alice")); // Output: undefined

The simplest fix is to always include the return keyword when you want to send back a result, but again, you don’t have to do this, and it rarely causes issues when omitted intentionally.

Again, this isn’t a ‘bug’ per se, just something to look out for when you are writing functions that have to return something.

Overcomplicating Functions

Each function should ideally accomplish one task and that’s it.

We often forget about this and end up writing enormous 100+ line functions.

Avoid writing large functions that do too many things which can be done separately.

If you end up with a very large function that does too much, try to break it up into smaller functions that focus on one task. This will drastically increase clarity and maintainability in some codebases.

One other massive advantage with smaller more focused functions is the increased testability, i.e., being able to test that everything works properly. This isn’t so much a concern in smaller projects, but in large projects with big codebases, it massively helps.

To wrap things up, functions form the backbone of JavaScript and enable you to write modular and efficient code.

They help by cutting down on repetition in code and allowing you to write a piece of code once and know it will work everywhere you call it.

I hope I have convinced you of the importance of functions and also taught you something about the very basics.

As for now, try to practice what you’ve learned, as the more you do it, the more natural they will feel and the more you will understand them.

Start by mastering these basics and write your own functions, trying to apply them to real-world problems.

Until next time, I wish you well on your learning journey!

As always, don’t hesitate to ask in a comment if you didn’t understand something.

Acknowledgements

The author used some AI tools in order to create this article.

AI tools used:

  • ChatGPT: Outlining and refining sentences for readability.

--

--

Matt Connors
Matt Connors

Written by Matt Connors

0 Followers

Tech enthusiast sharing science, modern history and occasionally social issues

Responses (1)