CINXE.COM
JavaScript Functions
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="keywords" content="javascript functions, methods, function, pass, passing, javascript tutorial, code, function, source, learn, method, javascript dropdown menu, rollovers, form validation, pop up windows, scripting, jscript, reference"> <meta name="Description" content="Learn how to write functions in JavaScript and how to reference them."> <link rel="canonical" href="https://www.quackit.com/javascript/tutorial/javascript_functions.cfm"> <title>JavaScript Functions</title> <script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <link rel="shortcut icon" href="/pix/favicon96.png"> <link rel="apple-touch-icon" href="/pix/apple-touch-icon.png"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Lato:ital,wght@0,400;0,700;1,400&display=swap" rel="stylesheet"> <link href="/common/css/master.45.min.css" rel="stylesheet"> <script async src="https://cdn.fuseplatform.net/publift/tags/2/3499/fuse.js"></script> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=G-Q3H025ZKLN"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-Q3H025ZKLN'); </script> </head> <body> <header class="site-header"> <div class="site-header-base"> <div class="site-logo"> <a title="Quackit Homepage" target="_top" href="/"><img src="/pix/quackit_logo_watermark.png" width="87" height="33" alt="Quackit Logo"></a> </div> <button id="site-nav-toggler" class="site-nav-toggler" aria-expanded="false" aria-controls="site-nav"> <span class="sr-only">Toggle navigation</span> ☰ </button> </div> <nav id="site-nav" class="site-nav"> <div class="site-links"> <ul> <li><a href="/"><i class="fa fa-home"></i> <span class="sr-only">Home</span></a></li> <li><a href="/html/">HTML</a></li> <li><a href="/css/">CSS</a></li> <li><a href="/scripting/">Scripting</a></li> <li><a href="/database/">Database</a></li> </ul> </div> <div class="site-search-top"> <form action="/search/" id="cse-search-box-bottom" class="site-search"> <div> <input type="hidden" name="cx" value="partner-pub-6331358926293806:98x0fk-bbgi"> <input type="hidden" name="cof" value="FORID:10"> <input type="hidden" name="ie" value="ISO-8859-1"> <input type="text" name="q" size="20" class="site-search-input"> <button type="submit" name="sa" class="site-search-button"><i class="fa fa-search"></i></button> </div> </form> </div> </nav> </header> <div class="main"> <article class="content"> <h1 class="page-title">JavaScript Functions</h1> <div class="ad ad-top"> <!-- GAM 71161633/QCKIT_quackit/article_header --> <div data-fuse="23059883623"></div> </div> <ul class="pager"> <li><a href="/javascript/tutorial/javascript_variables.cfm"><i class="fa fa-long-arrow-left" aria-hidden="true"></i> JavaScript Variables</a></li> <li><a href="/javascript/tutorial/javascript_events.cfm">JavaScript Events <i class="fa fa-long-arrow-right" aria-hidden="true"></i></a></li> </ul> <p class="lead">A function is a self-contained piece of code that returns a value. You can use JavaScript's built-in functions, or create your own.</p> <p>A function (also known as a <dfn>method</dfn>) is a self-contained piece of code that performs a particular "function", then returns a value. You can recognise a function by its format — it's a piece of descriptive text, followed by open and close brackets.</p> <p>Like this:</p> <script src="/common/js/codemirror/lib/codemirror.js"></script> <script src="/common/js/codemirror/mode/javascript/javascript.js"></script> <div class="code-only"> <textarea id="example1" autocomplete="off" spellcheck="false">function displayWelcomeMessage() {

 ...code goes here...

}</textarea> </div> <script> var exampleCode1 = CodeMirror.fromTextArea(document.getElementById("example1"), { mode: "text/javascript", tabMode: "indent", styleActiveLine: false, lineNumbers: false, lineWrapping: true, theme: "q-dark" }); </script> <p>The code that goes into a function can be as simple or as complex as you need it to be.</p> <p>Regardless of the code's complexity inside the function, when you call the function, you don't need to know anything about the code inside. All you need to know is the name of the function, and any arguments that you might need to supply.</p> <p>For example, take JavaScript's built-in <code>alert()</code> function. You can call that function from within your code without knowing how the function is written. All you need to know is what the function <em>does</em> and how to call it.</p> <h2>Parameters & Arguments</h2> <p>Sometimes there will be text in between the brackets of a function's definition. This text is known as a <dfn>parameter</dfn>. A parameter specifies that a value should be provided to the function. For example, a parameter might be called <code>FirstName</code>, which indicates that the caller should provide the value of the first name to the function (i.e. the first name of whoever the end user is).</p> <p>So we could modify the above example to include a parameter:</p> <script src="/common/js/codemirror/mode/text/javascript/text/javascript.js"></script> <div class="code-only"> <textarea id="example2" autocomplete="off" spellcheck="false">function displayWelcomeMessage(FirstName) {

 ...code goes here...

}</textarea> </div> <script> var exampleCode2 = CodeMirror.fromTextArea(document.getElementById("example2"), { mode: "text/javascript", tabMode: "indent", styleActiveLine: false, lineNumbers: false, lineWrapping: true, theme: "q-dark" }); </script> <p>An <dfn>argument</dfn> refers to the actual value passed to the function at runtime. This info could be different depending on the context in which the function is being called. For example, <code>Homer</code> could be passed as an argument to a function that has a <code>FirstName</code> parameter.</p> <div class="ad"> <!-- GAM 71161633/QCKIT_quackit/article_incontent_1 --> <div data-fuse="23059883629"></div> </div> <p>Parameters can be very handy, such as allowing your users to provide information (say via a form) that is passed to a function to process. For example, your users could enter their name into a form, and the function would take that name, do some processing, then present them with a personalised message that includes their name.</p> <p>A function doesn't actually do anything until it is called. Once it is called, it takes any arguments, then performs it's function (whatever that may be).</p> <p>So we could call the above function like this:</p> <div class="code-only"> <textarea id="example3" autocomplete="off" spellcheck="false">displayWelcomeMessage('Homer');</textarea> </div> <script> var exampleCode3 = CodeMirror.fromTextArea(document.getElementById("example3"), { mode: "text/javascript", tabMode: "indent", styleActiveLine: false, lineNumbers: false, lineWrapping: true, theme: "q-dark" }); </script> <h2>Writing a function in JavaScript</h2> <p>Here's an example of a JavaScript function.</p> <ol class="steps"> <li> <h3>Write the function</h3> <p>The first thing you need to do is write the function:</p> <script src="/common/js/codemirror/mode/htmlmixed/htmlmixed.js"></script> <script src="/common/js/codemirror/mode/css/css.js"></script> <script src="/common/js/codemirror/mode/xml/xml.js"></script> <div class="code-only"> <textarea id="example4" autocomplete="off" spellcheck="false"><script>
 function displayMessage(firstName) {
 alert("Hello " + firstName + ", hope you like JavaScript functions!");
 }
</script></textarea> </div> <script> var exampleCode4 = CodeMirror.fromTextArea(document.getElementById("example4"), { mode: "htmlmixed", tabMode: "indent", styleActiveLine: false, lineNumbers: false, lineWrapping: true, theme: "q-dark" }); </script> </li> <li> <h3>Call the function</h3> <p>Once you have written your function, you can call that function from within your HTML code. Here, when the user clicks the button, it runs the function. In this case, we use the <code>onclick</code> event handler to call the function.</p> <div class="code-only"> <textarea id="example5" autocomplete="off" spellcheck="false"><form>
 First name:
 <input type="input" name="yourName">
 <input
 type="button"
 onclick="displayMessage(form.yourName.value);"
 value="Display Message">
</form></textarea> </div> <script> var exampleCode5 = CodeMirror.fromTextArea(document.getElementById("example5"), { mode: "htmlmixed", tabMode: "indent", styleActiveLine: false, lineNumbers: false, lineWrapping: true, theme: "q-dark" }); </script> </li> </ol> <p>Here they are combined:</p> <script src="/common/js/codemirror/mode/htmlmixed/htmlmixed.js"></script> <div class="code-only"> <textarea id="example6" autocomplete="off" spellcheck="false"><script>
function displayMessage(firstName) {
 alert("Hello " + firstName + ", hope you like JavaScript functions!");
}
</script>
<form>
 First name:
 <input type="input" name="yourName">
 <input
 type="button"
 onclick="displayMessage(form.yourName.value);"
 value="Display Message">
</form></textarea> </div> <script> var exampleCode6 = CodeMirror.fromTextArea(document.getElementById("example6"), { mode: "htmlmixed", tabMode: "indent", styleActiveLine: false, lineNumbers: false, lineWrapping: true, theme: "q-dark" }); </script> <h2>Explanation of code</h2> <h3>The Function</h3> <ol class="steps"> <li><p>We started by using the <code>function</code> keyword.</p> <p>This tells the browser that a function is about to be defined.</p></li> <li><p>Then we gave the function a name, so we made up our own name called <code>displayMessage</code>.</p> <p>We specified the name of an argument (<code>firstName</code>) that will be passed in to this function.</p></li> <li><p>After the function name came a curly bracket <code>{</code>.</p> <p>This opens the function. There is also a closing bracket later, to close the function.</p></li> <li><p>In between the curly brackets we write all our code for the function.</p> <p>In this case, we use JavaScript's built in <code>alert()</code> function to pop up a message for the user.</p></li> </ol> <h3>Calling the Function</h3> <ol class="steps"> <li><p>We created an HTML form with an input field and submit button.</p></li> <li><p>We assigned a name (<code>yourName</code>) to the input field.</p></li> <li><p>We added the <code>onclick</code> event handler to the button.</p> <p>This event handler is called when the user clicks on the button (more about event handlers later). This is where we call our JavaScript function from. We pass it the value from the form's input field. We can reference this value by using <code>form.yourName.value</code>.</p> </li> </ol> <ul class="pager"> <li><a href="/javascript/tutorial/javascript_variables.cfm"><i class="fa fa-long-arrow-left" aria-hidden="true"></i> JavaScript Variables</a></li> <li><a href="/javascript/tutorial/javascript_events.cfm">JavaScript Events <i class="fa fa-long-arrow-right" aria-hidden="true"></i></a></li> </ul> </article> <div class="sidebar"> <nav> <ul> <li> <h3><a href="/javascript/tutorial/">JavaScript Tutorial</a></h3> <ul> <li><a href="/javascript/tutorial/introduction.cfm">Introduction</a></li> <li><a href="/javascript/tutorial/how_to_enable_javascript.cfm">How to Enable JavaScript</a></li> <li><a href="/javascript/tutorial/javascript_syntax.cfm">JavaScript Syntax</a></li> <li><a href="/javascript/tutorial/javascript_popup_boxes.cfm">JavaScript Popup Boxes</a></li> <li><a href="/javascript/tutorial/javascript_html.cfm">JavaScript and HTML</a></li> <li><a href="/javascript/tutorial/external_javascript_file.cfm">External JavaScript File</a></li> <li><a href="/javascript/tutorial/javascript_operators.cfm">JavaScript Operators</a></li> <li><a href="/javascript/tutorial/javascript_variables.cfm">JavaScript Variables</a></li> <li><a href="/javascript/tutorial/javascript_functions.cfm">JavaScript Functions</a></li> <li><a href="/javascript/tutorial/javascript_events.cfm">JavaScript Events</a></li> <li><a href="/javascript/tutorial/javascript_if_statements.cfm">JavaScript If Statements</a></li> <li><a href="/javascript/tutorial/javascript_switch_statement.cfm">JavaScript Switch Statements</a></li> <li><a href="/javascript/tutorial/javascript_while_loop.cfm">JavaScript While Loop</a></li> <li><a href="/javascript/tutorial/javascript_for_loop.cfm">JavaScript For Loop</a></li> <li><a href="/javascript/tutorial/javascript_try_catch.cfm">JavaScript Try Catch</a></li> <li><a href="/javascript/tutorial/javascript_escape_characters.cfm">JavaScript Escape Characters</a></li> <li><a href="/javascript/tutorial/javascript_void_0.cfm">JavaScript Void(0)</a></li> <li><a href="/javascript/tutorial/javascript_cookies.cfm">JavaScript Cookies</a></li> <li><a href="/javascript/tutorial/javascript_date_and_time.cfm">JavaScript Date and Time</a></li> <li><a href="/javascript/tutorial/javascript_arrays.cfm">JavaScript Arrays</a></li> <li><a href="/javascript/tutorial/two_dimensional_arrays.cfm">Two Dimensional Arrays</a></li> <li><a href="/javascript/tutorial/innerhtml_in_javascript.cfm">JavaScript innerHTML</a></li> <li><a href="/javascript/tutorial/unobtrusive_javascript.cfm">Unobtrusive JavaScript</a></li> <li><a href="/javascript/tutorial/javascript_summary.cfm">JavaScript Summary</a></li> </ul> </li> <li><h3>JavaScript Reference</h3> <ul> <li><a href="/javascript/examples/" title="">JavaScript Examples</a></li> <li><a href="/javascript/javascript_reserved_words.cfm" title="">JavaScript Reserved Words</a></li> <li><a href="/javascript/javascript_event_handlers.cfm" title="Introduction to the 12 JavaScript event handlers">JavaScript Event Handlers</a></li> <li><a href="/javascript/javascript_date_and_time_functions.cfm" title="Full listing of all JavaScript methods for dealing with date and time.">JavaScript Date and Time Functions</a></li> </ul> <li><h3>jQuery</h3> <ul> <li><a href="/jquery/tutorial/" title="">jQuery Tutorial</a></li> <li><a href="/jquery/examples/" title="">jQuery Examples</a></li> </ul> </li> <li><h3>JSON</h3> <ul> <li><a href="/json/tutorial/" title="Data format for exchanging data between applications and different environments.">JSON Tutorial</a></li> </ul> <li> </ul> </nav> <div class="ad ad-left"> <!-- GAM 71161633/QCKIT_quackit/article_vrec_2 --> <div data-fuse="23059511712"></div> </div> </div> <div class="ads"> <div class="ad ad-right"> <!-- GAM 71161633/QCKIT_quackit/article_vrec_1 --> <div data-fuse="23059883626"></div> </div> </div> </div> <div class="searchbox-bottom"> <form action="/search/" id="cse-search-box-bottom" class="site-search"> <div> <input type="hidden" name="cx" value="partner-pub-6331358926293806:npmuvy-i8kk"> <input type="hidden" name="cof" value="FORID:10"> <input type="hidden" name="ie" value="ISO-8859-1"> <input type="text" name="q" size="30" class="site-search-input"> <button type="submit" name="sa" class="site-search-button"><i class="fa fa-search"></i></button> </div> </form> <script src="//cse.google.com/cse/brand?form=cse-search-box-bottom&lang=en"></script> </div> <footer> <p class="about"><a href="/"><i class="fa fa-home"></i> Home</a> | <a href="/about.cfm" rel="nofollow">About</a> | <a href="/contact.cfm" rel="nofollow">Contact</a> | <a href="/terms_of_use.cfm" rel="nofollow">Terms of Use</a> | <a href="/privacy_policy.cfm" rel="nofollow">Privacy Policy</a></p> <p>© Copyright 2000 - 2024 Quackit.com </p> </footer> <script src="/common/js/spectrum/spectrum.js"></script> <script src="/common/js/lightbox2-master/dist/js/lightbox.min.js" charset="utf-8"></script> <script> $(document).ready(function(){ $( "#site-nav-toggler" ).click(function() { $( "#site-nav" ).toggle( "slow" ); }); }); </script> <script> $(function(){var a=window.location.href;$(".sidebar nav a").each(function(){a==this.href&&$(this).closest("li").addClass("selected")})}); </script> </body> </html>