A Function as a Statement

A Function as a Statement

Functions are an integral part of programming. They are reusable blocks of code that can be executed whenever and wherever required. In JavaScript, functions can be defined using two types of syntax: function declaration and function expression. In this blog, we will be discussing function declaration, also known as a function statement.

Function Declaration

The syntax for declaring a function is as follows:


function functionName(parameters) {
  // code to be executed
}

The function declaration starts with the keyword "function", followed by the name of the function, then an optional list of parameters enclosed in parentheses, and finally the code block to be executed enclosed in curly braces.

Here's an example:


function greet(name) {
  console.log("Hello, " + name + "!");
}
greet("Raju");

This function takes in one parameter, "name", and logs a greeting message to the console with the value of the parameter concatenated to it. We then call this function with the argument "Raju", which produces the output "Hello, Raju!"

One thing to note here is that function declarations are hoisted to the top of their scope. This means that you can call a function before it is declared and it will still work:


greet("Raju");

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

This will produce the same output as before: "Hello, Raju!"

Conclusion

Function declarations are a powerful tool in JavaScript that allow you to write reusable code blocks. They are easy to define and use, and are hoisted to the top of their scope. Remember to always use proper syntax and naming conventions when declaring functions, and don't forget to call them with the correct arguments. Happy coding!

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe