Loading
Function in JS-tutorial
In JavaScript, a function is a reusable block of code that performs a specific task. Functions help you write cleaner, more organized, and maintainable code by avoiding repetition.



Syntax:

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

  • function – The keyword to declare a function.
  • functionName – A meaningful name that describes what the function does.
  • parameters – Optional variables you pass into the function to work with.
  • {} – Curly braces enclose the function body where your logic is written.



Example:

<!DOCTYPE html>
<html>

<body>
    <script>
        function msg() {
            alert("Hello! This is a message");
        }
    </script>
    <input type="button" onclick="msg()" value="Call Function" />
</body>

</html>

Output

Uploaded Image




Why Use Functions ?

  • Reuse code instead of writing it again and again.
  • Make your code more organized and readable.
  • Accept different inputs through parameters to do flexible tasks.