How to define a function in JavaScript?


The most common way to define a function in JavaScript is by using the “function” keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces.

Syntax

Here’s the syntax −

<script>
   <!--
   function functionname(parameter-list) {
      statements
   }
   //-->
</script>

Try the following example. It defines a function called sayHello that takes no parameters,

<script>
   <!--
   function sayHello() {
      alert("Hello World!");
   }
   //-->
</script>

Updated on: 15-Jun-2020

140 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements