Javascript Function

If you have been into programming for a while then you must have come across functions. So there might be a little possibility that you would be very well aware about functions. But I would like to share the knowledge that I have of Functions. So here it goes hear me out-

Well if you ask me about functions then I would say that functions is one of my favorite topics in programming because they not only help us in writing clean, and efficient code but also because Functions are a piece of code that enable us to call that block of code anywhere in the program thus refraining to not write that block of code again in the same program.
If you did not understand what functions are then you just need to have some patience and keep reading.

What is a function in JavaScript?

A javascript function is a block of code designed to perform a particular task and can be reused multiple times. Functions can take input through parameters and return a value to the caller. Functions are a fundamental part of the language and are used for various purposes, such as performing calculations, manipulating data, and interacting with other code.

In other words, a function groups a number of program statements in a single unit to perform a particular task.

A function can be reused. — it can be executed as many times as you desire in a program which removes the need for code repetition. This is known as modular coding. Since each function performs a particular task, functions can also be used in code grouping — breaking down a large program into smaller pieces of code that are based on the task they perform. They are either predefined or user-defined (custom code).

Function declarations

We define a function by using the function keyword, which is followed by a unique name of the function, a list of parameters (that could be empty or optional), and a statement block surrounded by curly braces that contain their associated code.

Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

  • Function is a keyword that precedes the actual code. It is a statement identifier. This is why a function is said to be self-contained.

  • Name is the name of the function to be executed on the parameters. It is user-defined and must be an action word.

  • ( ) is the grouping operator which is a pair of parentheses and it is what envelopes the arguments that are to be run in the program.

  • { } is the block that houses the code itself. It is the real definition of a function and is used to group statements.

<mark>Note:- </mark> All the function names must be unique. Function names also should not conflict with reserved words which JavaScript uses itself. For example, you cannot define a function named while. You should not define two functions with the same named display in the program

<mark>Note:</mark> JavaScript is case-sensitive. You must write the function keyword in lowercase letters.

Difference between Parameters and Arguments:-

Argument - These are the values that we pass while calling the function and these act as the actual value that the variable would contain that we have declared while declaring or defining the functions.

Parameter - These are the variables that are use to store values that we have passed as argument while calling the function. These variables are declared while declaring the function.

Calling a function in JavaScript:-

The code inside the function will execute when we call the function. Calling a function is known as invoking a function in JavaScript.

To call a function in JavaScript, you simply need to use its name followed by a list of arguments in parentheses.

function sum(a,b){
    var total = a+b;
    console.log(total);
}
sum(5,10);

output:- 11

The Return Keyword:-

It is use to store/save value so that we can use it in the future.

When the return keyword is encountered, function execution stops and the value is returned and no next line is ever executed.
We can use the return statement inside a function when we need to return a value from a function. It returns a computed value to the function caller.

function add(a,b) {
    return a+b;
}
let total = add(5,6);
console.log(total);

output:- 11

The function also returns undefined by default when the return keyword is provided without a value. This makes it an empty return:

function add() {
    value * 2
    return
}

console.log(add(3,5))
// undefined

Type of declaring a function in JavaScript:-

Regular function

Anonymous function

Function expression

Arrow function

Immediately invoked function expression

Nested function

Regular function:-

In regular JavaScript functions, argument keywords can be used to access the passed arguments when the function is invoked.

The function declaration matches for cases when a regular function is needed. Regular means that you declare the function once and later invoke it in many different places. This is the basic scenario:

function sum(a, b) {
  return a + b;
}
sum(5, 6);           // => 11

Anonymous function:-

An anonymous function in JavaScript is a type of function that doesn’t have a name after the function keyword.

The term ‘anonymous’ means something that is unknown or has no identity. When we create an anonymous function, we declare it with no identifier after the function keyword. This function is declared only once because and cannot be recalled without an identifier. The only way it can be recalled is to assign the function to a variable so that the variable name can be invoked in our code.

Anonymous functions are also sometimes called as lambda functions in JavaScript.

Syntax:-

function() {
    // Function Body
 }

Don’t forget to add ending (;) semicolon after the anonymous functions in JavaScript.

We can also use an anonymous function as an argument for another function.

Example:-

let y = function () {  
    console.log('This is an anonymous function');  
};  
y();

Function Expression:-

A function can be declared using a function expression. It is declared quite differently from the general syntax because it uses a variable to denote the name of the function. This variable comes before the keyword function.

The function is invoked by calling out the variable with trailing parenthesis and semicolons:

var greet = function () {
  console.log("Welcome to Javascript");
};
greet();

This method of function declaration makes tracing bugs easy. It specifies the name of the function in the stack trace. A function declaration through the function expression method can be used both as anonymous functions and IIFE (immediately invoked function expressions).

Arrow function:-

This is a feature available in the ES6 version of JavaScript and as such has not stayed in the space for as long as the other features in the function declaration. It is generally a cleaner way of creating JavaScript functions and it is similar to the function expression. It enables us to create functions more cleanly and shortly compared to normal functions.

The syntax of an arrow function is shown below:-

let umyFunction = (parameter-list) => {
   statement(s);
}

It does not use the function keyword in its syntax. For multiple-line statements, curly brackets are used. The arrow function statement can implicitly return values. This means that the word return isn’t needed in some cases to return the value of a function. here is an example to understand the arrow function easily:-

const add = (x, y) => {
 return x + y;
}
add(1,7);
output:- 11

Immediately invoked function expressions:-

IIFE are functions that can be stated as expressions or normal declarations and use the anonymous property of the function expression to execute its code. If you want to execute a function immediately after the declaration, use IIFE. This is executed by wrapping the anonymous function in parentheses and ending it with a semicolon

(function (){ 
// Function Logic Here. 
})();

If we look at the syntax itself we have two pairs of closed parentheses, the first one contains the logic to be executed and the second one is generally what we include when we invoke a function, the second parenthesis is responsible to tell the compiler that the function expression has to be executed immediately.

(function () {
  console.log("Welcome");
})();

Nested function:-

in javascript, when we define a function inside another function, it is called nested function.

In other words, a function can also contain an inner function that executes immediately during the call time of the parent or top-level function.

JavaScript allows to nest of multiple levels of function declarations

 function parent()
   {
     var firstName = "jack"; 

     function inner()
     {
       var lastName = "jill"; 
       console.log(" My full name is  " +firstName+ " " +lastName);
     }
  
     inner();
    }
parent();

output:- My full name is jack jill

In this example, we have defined an outer function named parent(). Inside the parent() function, we have declared a local variable and inner function named inner().

Inside the body of the nested function, we have declared a local variable named lastName. When we have called parent() function, then inner() function is automatically invoked, which simply displays firstName and lastName.

Hoisting:-

With JavaScript functions, it is possible to call functions before actually writing the code for the function statement and they give a defined output. This property is called hoisting. Hoisting is the ability of a function to be invoked at the top of the script before it is declared. Since the function is hoisted at the top of the block but not initialized, it cannot be used until it has been declared. Recalling earlier examples:

greet();

function greet() {
    console.log("Welcome");
}

This is a function declaration that has been hoisted and when executed by the browser outputs welcome. greet() is invoked before it is declared. However, there’ll be no error since greet() will be stored at the heap until the greet() function is initialized.

Hoisting operates on the mechanism of scope and variables used to identify function expressions are all based on the scope of the JavaScript engine which executes before initializing a function.

Conclusion

In this tutorial, we have learned about javascript functions from basics and have mostly tried to cover every part of it to get started with function

In JavaScript programming, we can define our own functions, called user-defined functions as well as use built-in functions which is already defined in JavaScript.

A function does not execute until it is called. That is, a function will execute when “someone” invokes it.

When a function gets called, the code inside the function executes. We can call a function from other parts of the program when needed.

we have been able to explore JavaScript functions and the various ways they can be declared in a program. JavaScript functions are essential when writing JavaScript programs if you want to execute a block of code as many times as you want without having to write the same block of code repeatedly in your program. We can simply say the function is a saved algorithm given to a program to work with when called upon.

It is important to understand the various methods of declaring functions as this allows you to select the best method when declaring functions for your use case.

Choosing the proper function declaration method could optimize your code and allow you to build better architectures.

You can use any method or function type you want and all of them will give you the same results.

so if you’re comfortable with either approach, feel free to pick whichever you prefer.

kindly give me feedback on how much you like or disliked the blog and what should I improve in the comments also don't forget to give a reaction.

Let's meet in the next article.

Happy coding...................

FunctionFrontend DeveloperJavaScript
Avatar for Anjali saini

Written by Anjali saini

Hi, my name is Anjali Saini and I'm a creative front-end web developer. I have a passion for creating beautiful, user-friendly websites and applications that are both functional and visually appealing

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.