What is Function in JavaScript?

What is Function in JavaScript?

Functions are the bread and butter of JavaScript programming.

Functions are one of the main parts of computer programs. They are widely used and are one of JavaScript's fundamental building blocks. It gives us a way to structure larger programs, reduce repetition, associate names with subprograms, and isolate these subprograms from each other.

In this blog, we'll go over the definition of functions and why they are so important.

So, let's get started!

What is a Function in JavaScript?

A function is a block of code that encapsulates one isolated, self-contained behavior for the computer to perform.

Functions are a set of organized instructions that correspond to a certain task a user wants to implement in their program to achieve a single desired outcome.

The code inside a function runs only when it is needed, meaning only when it is called.

Functions make the code reusable. Instead of copying, pasting, and repeating the same code throughout different parts of your program, you can write that code only in one place using a function. This helps a lot when you want to implement changes to your program or debug and try to fix an error. Instead of looking for the different parts where your code could be, you only have to look at one particular place which makes your code more readable.

How to declare a Function?

The general syntax for creating a function in JavaScript is shown as follows:

function name(parameter1,parameter2,...) {
    // the code statements to be executed
}

Let's break it down:

A function definition (also called a function declaration, or function statement) consists of the function keyword, followed by:

  • The name of the function. Function names in JavaScript are case sensitive and a convention and best practice are to use camelCase.

  • A list of parameters to the function, enclosed in parentheses and separated by commas. Parameters act as local placeholder variables for the values that will be passed into the function as inputs when the function is called. They are entirely optional.

  • The JavaScript statements that define the function, enclosed in curly brackets, {...}. This is where the parameters to the function are processed.

How to declare and call a simple function in JavaScript?

function greeting() {
console.log("Hello! How are you?");
}

We created a simple function named greeting above. It is a very basic one. It doesn't take any inputs. It just prints Hello! How are you? to the console.

Defining a function in and of itself doesn't run the code inside the function's body. For the code to be executed, and to see that message in the console, the function has to be called. This is also known as a function invocation.

To call a function that doesn't accept inputs, you just write the function's name followed by parentheses and a semicolon at the end.

greeting();

//output: Hello! How are you?

How to declare and call the function with parameters in JavaScript?

We can modify the previous example to take inputs. We'll do this with parameters this time.

function greeting(name) {
  console.log("Hello " + name + " !" );
}

The function named greeting now accepts one parameter, name. That string is being concatenated (+) with the string Hello and an exclamation mark at the end.

When calling functions that accept parameters, you need to pass arguments in.

Arguments are values that you supply when calling the function and they correspond with the parameters that have been passed in the function's declaration line.

For example:

greeting("Harshita");

//output: Hello Harshita!

The argument is the value Harshita and you can think of it as name = "Harshita". Here, name the parameter, is the placeholder variable, and Harshita is the value you pass in when you call the function.

Functions can accept more than one parameter and can also return data to the user of the program.

For example:

function addition(number1, number2) {
      return number1 + number2;
}

The above code created a function named addition that takes in two parameters – number1 and number2, separated by a comma.

The same way functions have inputs, they also have outputs.

The function returns its output as the sum of number1 and number2. This means that it processes the two parameters, does the requested calculation, and returns the end value as a result back to the user.

When the function is called, two arguments have to be passed in since it accepts two parameters.

For example:

addition(15,25);

// Output: 40

Each time the function is called, you can pass in different arguments.

For example:

addition(7,4);
// output: 11

addition(66,33);
// output: 99

What is Variable scope in JavaScript functions?

Variable scope refers to how visible variables are to different parts of the program.

A variable defined outside and before a function block has a global scope and can be accessed from inside a function.

For example:

// The following variable is defined in the global scope
const num = 7;

// This function is defined in the global scope
function myFunc() {
  console.log(num);
}

// Access the variable with a global scope from anywhere in the program
console.log(num);
// Output: 7

// Call the function with the variable with global scope
myFunc();
//Output: 7

But if that variable was defined inside the function, it would have local scope and it would be limited and visible only in the function where it was defined. You cannot access it from outside the function.

For example:

/* This function is defined in the local scope */
function myFunc() {
   /* The following variable is defined in the local scope */
  const num = 7;
  console.log(num);
}

/* Try to access the variable with local scope from outside the function scope */
console.log(num);
/* Output: Uncaught ReferenceError: num is not defined */

/* Call the function with the variable defined inside the function */
myFunc();
/* Output: 7 */

What are Function Expressions?

Functions can also be created by a Function expression. These functions are created inside an expression instead of being created with a function declaration as you've seen so far. Such a function can be anonymous; it does not have to have a name.

For example:

const name = function(firstName) {
  return 'Hello ' + firstName ;
  }

Here, we use the variable name to store the function.

To call the function, you use the variable name as shown below:

console.log(name("Harshita"));
/* Output: Hello Harshita */

The variables in anonymous functions can be used as values to other variables too.

For example:

const name = function(firstName) {
  return "Hello " + firstName ;
  }

const myName = name("Harshita");
console.log(myName);
// Output: Hello Harshita

What is the difference between a Named function and an Anonymous function?

// named function
function name(firstName) {
    console.log("Hello " + firstName);
 }

name("Harshita");

// anonymous function
const name = function(firstName) {
  return "Hello " + firstName ;
  }
 console.log(name("Harshita"));

Reference:

I have used the following as the references for this blog.

  1. MDN docs
  2. Eloquent JavaScript

Conclusion:

And there you have it! This marks the end of our introduction to JavaScript functions and some of the ways you can create them.

If you want to learn more, arrow functions are a new and more efficient way to create functions in JavaScript and they were introduced with ES6.

Don’t forget to like, follow & share if you enjoyed it! Thank you for reading, and keep coding. :)

Connect with me on Twitter and LinkedIn.