Support Online
Skip to main content

Defining a Function in JavaScript

Login

Functions are blocks of code that perform a specific operation or return a value.
Defined by programmers, can be used over and over again. In this way, programs become both more modular and more efficient.

In this lesson, we will learn how to define functions in JavaScript in different ways, how to call them and how to use parameters.

Function Definition

In JavaScript, functions are defined (or declared) with the keyword function.
Below you can see the basic function syntax:

function fonksiyonAdi(parametre1, parametre2) {
// Çalıştırılacak kodlar buraya yazılır
}

The function declaration begins with the keyword function, followed by the name of the function.
Function names follow the same rules as variable names: they can contain letters, numbers, underscores (_), and dollar signs ($).
Generally, camelCase writing style is preferred.

The function name is followed by brackets. These parentheses are used to pass parameters to the function (parameters are optional).
The codes to run the function are written in curly brackets {}; just like for or if.

Our First Example

Let's define a simple function that prints a greeting message to the console:

function selamVer() {
console.log("Merhaba! JavaScript öğreniyoruz ");
}

In the example above, inside the selamVer() function Hello! There is code that prints the message "We are learning JavaScript" to the console.
But be careful, we've only defined the function — we haven't run it yet.

A function does nothing unless it is called.
To run the function, simply write its name and open and close parentheses next to it:

// Fonksiyonu çağırma
greet();

Now let's combine these steps:
We will define the function and then run it by calling it.

function selamVer() {
console.log("Merhaba! JavaScript öğreniyoruz ");
}

// Fonksiyonu çağırma
selamVer();

When we call the line selamVer();, the function runs and the program outputs Hello! We see the message We are learning JavaScript.

Output
Merhaba! JavaScript öğreniyoruz

Now our selamVer() code is inside a function, so we can reuse it as much as we want.

We can also make the code more dynamic by adding parameters to the functions.

Function Parameters

In our script.js file, we created a simple function that prints Hello, World! to the console.
We can make this function more flexible and useful by using parameters.

Parameters are values ​​entered into functions and act as local variables within the function.

For example, when a user logs into an application, he just says “Hello, World!” We may want to greet him/her by name instead of writing.

To do this, we will add a parameter called name to our function. This parameter will represent the name of the person to greet.

// Özel selamlama fonksiyonunu başlat
function selamVer(name) {
console.log(`Merhaba, ${name}!`);
}

The name of our function is GiveHello and we now have a single parameter in parentheses.
Parameter names follow the same rules as variable names.

Inside the function, instead of a fixed text "Merhaba! JavaScript öğreniyoruz", we have a template literal (template string) that we use as a parameter.
This parameter acts like a local variable here.

Notice that we have not defined the name parameter anywhere outside the function.
We assign a value to this parameter when calling the function.

For example, let's say our user's name is Ali. We send this name as an argument when calling the function.
Argument is the actual value passed to the function. Here the argument is the string "Ali".

// "Sammy" argümanıyla greet fonksiyonunu çağır
selamVer("Ali");

// Çıktı:
Merhaba, Ali!

The "Ali" value is transferred to the name parameter of the function.
Now whenever name is used within the function it will represent the value "Ali".

// Özel selamlama fonksiyonunu başlat
function selamVer(name) {
console.log(`Merhaba, ${name}!`);
}

// "Ali" argümanıyla greet fonksiyonunu çağır
selamVer("Sammy");

When we run the above program, we will get the following output.

// Çıktı:
Merhaba, Ali!

Now we have an example of how a function can be reused.
In real life, this function would pull the name from a database instead of taking it directly as an argument.

In addition to parameters, variables can also be defined within functions.
These variables are called local variables and exist only within the function block in which they are defined.

Variable scope determines the accessibility of a variable:

  • Variables defined within the function cannot be accessed from outside**.
  • However, these variables can be created and used again each time the function is run.

Returning Values

More than one parameter can be used in a function.
This way, we can send multiple values ​​to the function and return a result.

For example, let's write a function that finds the sum of two numbers. These numbers will be represented by the parameters x and y.

// Toplama fonksiyonunu başlat
function add(x, y) {
return x + y;
}

// Fonksiyonu çağır ve toplamı bul
add(7, 4); // 11

In the above program, we defined a function with parameters x and y and then sent the values 7 and 4 to this function.
When we run the program, the sum of these numbers will be returned as output:

// Çıktı:
11

In this example, when the values ​​7 and 4 were passed to function add(), the program returned 16.

When the return keyword is used, the function stops executing and the result of the expression is returned.
The browser can display this value on the console, but this is not the same as printing it to the screen with console.log().

When the function is called, the returned value is used exactly where the function was called.
You can immediately use this value in other operations or assign it to a variable.


Function Expressions

In the previous section, we used function declaration to take the sum of two numbers and return the value.
But we can define functions not only by declaration, but also as an expression by assigning them to a variable.

For example, we can assign the same function add to a variable and store the result directly in the variable sum.

// add fonksiyonunu sum sabitine ata
const sum = function add(x, y) {
return x + y;
}

// Fonksiyonu çağır ve toplamı bul
sum(20, 5); // 25
Output
25

Now our constant sum has become a function.
To make this even shorter, we can make it anonymous function (anonymous function).

Currently our function is called add, but it is not mandatory to name the function when using function expression.
Often the name is omitted entirely.

// Fonksiyonu sum sabitine ata (anonim fonksiyon)
const sum = function(x, y) {
return x + y;
}

// Fonksiyonu çağır ve toplamı bul
sum(100, 3);
Output
// 103

In this example, the function name add has been removed and the function has been made anonymous.

A function expression with a name can be especially useful during debugging.
But most of the time in practice this name is left unused.


Arrow Functions

So far we have seen defining functions with the keyword function.
But with ECMAScript 6 (ES6), a more shorter and modern way of defining functions came: arrow functions.

The Arrow function syntax is indicated by the sign => (equals = followed by greater than >).

Arrow functions are always anonymous and operate as a type of function expression.

Let's write a function that finds the product of two numbers with a simple example:

// Çarpma fonksiyonunu tanımla (arrow function)
const multiply = (x, y) => {
return x * y;
}

// Fonksiyonu çağır ve çarpımı bul
multiply(30, 4); // 120
Output
120

Here, we use the => symbol instead of the function keyword and define a function with it.
In basic usage, it works similarly to regular function expressions, but there are some advanced differences (which you can learn about later under the heading Arrow Functions).

If there is only one parameter, it is not necessary to use parentheses.
For example, we can remove the parentheses in a function that simply takes a single number and squares it:

// Kare alma fonksiyonunu tanımla (arrow function)
const square = x => {
return x * x;
}

// Fonksiyonu çağır ve sonucu bul
square(8);
Output
64

Note: If the function has no parameters, it is mandatory to use empty brackets () in the arrow function.

In these examples, the function consists of just one expression return.
Thanks to arrow functions, we can shorten the syntax even further.

If the function is a single line, we can remove both the curly brackets and the return statement.

// Kare alma fonksiyonunu tanımla (tek satır arrow function)
const square = x => x * x;

// Fonksiyonu çağır ve sonucu bul
square(10);
Output
100

These three different syntaxes (function declaration, function expression and arrow function) all produce the same output.

Which one you use usually depends on personal preference or the coding standards of your team.


Result

In this lesson we learned:

  • Function declarations
  • Function expressions
  • return value from functions
  • Assigning functions to variables
  • Arrow functions

Functions are blocks of code that return a value or perform an action.
Thanks to these features, our programs become more scalable and modular.