skip to content
Dev Journal

Function

/ 2 min read

Imagine living in a village without tap water. To get water, you need to take an empty bucket, go to the well, draw water, and return home. Instead of explaining this each time, you can simply say draw water. This is similar to creating a function in programming.

Declaring Functions

A functions is a block of code that performs a task. Here’s the syntax:

function functionName (parameters) {
// Do stuff here
}
  • function is the keyword.
  • functionName is the name of your function.
  • parameters are optional variables you can pass in.

Using Functions

To use a function, write its name followed by parentheses:

// Declaring a function
function sayHello () {
// Do stuff here
console.log("Hello world!")
}
// Using a function
sayHello() // Hello world!

Tips: Use Indentation

Indent code within blocks to make it readable. Use either with 2 spaces or tabs, but stay consistent.

Parameters and Arguments

Function can take parameters, which are variables

// Declaring a function
function sayName (firstName, lastName) {
// Do stuff here
console.log("First name : " + firstName)
console.log("Last name : " + lastName)
}
// Using a function
sayName("Reza", "Augusdi")
// First name: Reza
// Last name: Augusdi

Return Statements

A function can return a value:

// Declaring a function
function add2 (num) {
// Do stuff here
return num + 2
}
// Using a function
const number = add2(8)
console.log(number) // 10s

The value returned by the function can be assigned to a variable. If no return statements is provided, the function returns undefined.

The Flow of a Function

  1. Declare the function.
  2. call the function.
  3. Evaluate any expressions.
  4. Return the result.

Hoisting

Function declared with the function keyword are hoisted, meaning you can call them before they appear in the code.

// Using a function
sayHello() // Hello world!
// Declaring a function
function sayHello () {
// Do stuff here
console.log("Hello world!")
}

Function Expressions

You can also declare functions using expressions like this:

// Declaring a function
const sayHello = function () {
console.log('This is declared with a function expression!');
};

However, function expressions are not hoisted.

“So, it’s not recommended to use declared functions before you declare them, as it can confuse you about the order of your code. Don’t rely on hoisting.”

Notes:

  1. A function is a block of code that performs a task.
  2. To call functions, add () to their name.
  3. Functions can take arguments and have return values.
  4. Declare functions before using them to avoid confusion with hoisting.

In short, functions help organize code into reusable blocks, making it easier to perform repetitive tasks efficiently.