JavaScript building blocks

JavaScript building blocks

JavaScript building blocks

Functions are an essential building block in JavaScript. They allow you to organize your code and reuse parts of it.

What are functions?

Functions are blocks of code that perform a specific task. They allow you to store a piece of code that does a single job inside a defined block, and then call that code whenever you need it using a single short command, rather than typing out the same code multiple times.

Functions have several benefits:

  • Reusability: The same code can be reused multiple times.

  • Modularity: Breaks down large programs into smaller, manageable chunks.

  • Information hiding: Functions encapsulate implementation details.

  • Code maintenance: Changes need to be made in only one place.

The basic syntax for a function is:

function name(parameters) {
  // Function body 


  • name is the function name

  • parameters are optional input values, separated by commas

  • The function body contains the code to be executed

Functions are invoked by calling the function name, followed by parentheses:


You can pass arguments to the function inside the parentheses:

name(arg1, arg2);

These arguments are mapped to the function parameters.

Functions can return values using the return keyword:

function multiply(a, b) {
  return a * b; 

const result = multiply(2, 3); // 6

Other concepts

Other important concepts related to functions are:

  • Function scope: Variables declared inside a function are only accessible within that function.

  • Default parameters: Parameters with default values, e.g. function(a = 1)

  • Arrow functions: A shorter syntax for defining functions, e.g. (a) => a * a

  • Anonymous functions: Functions without a name, often used as arguments to other functions.

Functions are an essential JavaScript building block. Along with variables, conditionals, and loops, they allow you to build complex logic and applications.

Hope this summary helps explain the basics of functions in JavaScript! Let me know if you have any other questions.