← homeProgramming (Програмування)

What is a function in programming?

A function is the fundamental building block of programming that defines a set of instructions or actions that are executed when it is called. Functions allow you to organize code into understandable and reusable bloc...

Table of contentsClick link to navigate to the desired location
This content has been automatically translated from Ukrainian.
A function is the fundamental building block of programming that defines a set of instructions or actions that are executed when it is called. Functions allow you to organize code into understandable and reusable blocks. Functions can take input data (arguments) and return a result.
In different programming languages, functions may have different names, such as "methods" in object-oriented programming. The term method is more commonly heard in discussions about Ruby code, while the term function is used for JS.

Characteristics of Functions

  • A function has a name by which it can be called.
  • A function can take one or more arguments – input data used to perform calculations or actions within the function.
  • It is a set of instructions that are executed when the function is called.
  • A function can return a value as a result of its execution.
Conceptually, this is a list of the main characteristics that functions have. Let's look at examples (Ruby and JS)

Example of a Function (Method) in Ruby

def sum_method(a, b)
  # Add two numbers and return the result
  a + b
end

result = sum_method(3, 4)
puts result # Will output 7

Example of a Function in JavaScript

function sumFunction(a, b) {
  // Add two numbers and return the result
  return a + b;
}

let result = sumFunction(3, 4);
console.log(result); // Will output 7

What are Functions for?

Functions allow you to reuse code and avoid duplication. For example, if you need to perform the same calculations in different places in the program, you can define a function and call it whenever needed. Functions are the foundation ^_^

🔥 More posts

All posts
Scope of a local variable in Ruby
Programming (Програмування)Jun 3, '24 16:46

Scope of a local variable in Ruby

In Ruby, a new scope for a local variable is created in several places. It is necessary to unders...

What is immutability and mutability?
Programming (Програмування)Jun 19, '24 07:48

What is immutability and mutability?

Immutability and mutability are properties of objects (in programming and other fields) that dete...

How to make an empty git commit?
Programming (Програмування)Jun 28, '24 08:33

How to make an empty git commit?

Making an empty git commit. Everyone has their own goals for this action. In my case - to trigger...

Ruby library Gosu for creating 2D games
Programming (Програмування)Jun 29, '24 08:48

Ruby library Gosu for creating 2D games

Gosu is a library for developing 2D games and graphical applications in the Ruby programming lang...