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

What is a function in programming?

What is a function in programming? Example of a function in Ruby and JavaScript

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

The scope of local variables in Ruby. Examples of how variable visibility works in Ruby.

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

What is immutability and mutability?

What is immutability and mutability? A description of the term in the context of programming and ...

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

How to make an empty git commit?

How to make an empty git commit? Let's make an empty git commit. Why? Who knows, everyone has the...

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

Ruby library Gosu for creating 2D games

Ruby library Gosu for creating 2D games. Description of the library for game development in Ruby ...