Javascript functions

What is a function?

A function is a set of reusable blocks of code that, in JavaScript, are function-driven or called by other code.

Function is one of the core of the JavaScript language, the basic syntax is as follows:

function functionName(arg0, arg1, ...) {


  1. Use the function keyword to define a function
  2. function keyword followed by a function name
  3. Function name is followed by a pair of parentheses, arg0, arg1 said that the function parameters, parameters separated by, the number of parameters can be 0-25 (0 means no parameters). In the absence of parameters, () brackets can not be omitted, more than 25 parameters, will be ignored by JavaScript
  4. {} Is the function body, which is the function to achieve the function statement


      <script type="text/javascript">
      function hello(name) {
          document.write((name + ", welcome!");
      <input type="button" onclick="hello('John')" value="Submit" />

Run the example, click the OK button on the page, the output:

John, welcome!


In fact, above is example of event-driven, from the user's mouse click event to call the hello() function to execute the code within the function.

For more information about event-driven and details, see the "JavaScript event" section.

JavaScript function naming

Usually, we recommend that the name of the function use a small hump naming, and the function name can roughly describe the function or features appropriate. Small hump naming is the first character in lowercase, followed by the first letter of other words, the following are some examples of function naming:

function changeName() {
    // ...
function getAgeByInput() {
    // ...

There are also a lot of people use the underscore to split the word in the function name, such as change_name, which is also possible, the actual implementation of the project in accordance with specific norms.

Particularly, the function preceded by a _ symbol (such as _getName), which is conventionally a private method representing a class (object).

Variable within a JavaScript function

If a variable is declared within the body of the function, the variable can only be accessed in the function. This allows you to use variables with the same name in different functions.

If a variable is declared outside of a function, all functions on the Web page can access the variable.

Copyright 2014-2017 by All Rights Reserved.