How to define a function in JavaScript

Topic: JavaScript / jQuery« Prev|Next »

Answer: Use the syntax function myFunction(){}

The following example will show how to define a function in JavaScript.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="utf-8">
  • <title>Define a Function in JavaScript</title>
  • <script type="text/javascript">
  •     function myFunction(){ 
  •         alert('You have successfully defined the function!'); 
  •     }
  • </script> 
  • </head>
  • <body>
  •     <button type="button" onclick="myFunction();">Click Me</button>
  •     <p><strong>Note:</strong> The function defined is called onclick event of "Click Me" button.</p>
  • </body>
  • </html>

Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.