Home  >  Article  >  Web Front-end  >  How to define a function in javascript

How to define a function in javascript

青灯夜游
青灯夜游Original
2021-10-19 14:46:269244browse

How to define a function in JavaScript: 1. Use the definition formula, the syntax "function function name ([parameter list]) {function body;}"; 2. Use the variable formula, the syntax "var function name = function([parameter list]){function body;}".

How to define a function in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Functions in JavaScript are similar to methods in Java. They are statement blocks that perform specific functions. There are two ways to define functions:

The difference between the two ways of defining functions: the first is called definition, and the second is called variable. In practical applications, there is no difference between the two, but there is a difference in the order in the call: the definition can be defined after the call, but the variable cannot. The example is as follows

1, the definition is

<script>
function test(age){     //先定义方法,再调用
    console.log(age);
}
test(23);
</script>

<script>
test(23);  
function test(age){     //先调用,再定义方法,不会出错
    console.log(age);
}
</script>

2. Variable expression

<script>
    var print=function(name){
        console.log(name);
    }
    print("tom");
</script>

<script>
        print("tom");       //先调用,再定义会出错。
        var print=function(name){
            console.log(name);
        }
</script>

Function parameter list and return value:

  • Function parameter list: The parameters in the function parameter list in JavaScript are not allowed to have data types; the number of function parameters can be 0~255. When there are multiple parameters, the parameters are separated by commas;

  • Function return value: The JavaScript function does not define the return value type part of the function. The JavaScript function determines the return value type based on the return return value statement in the function body; if there is no return return value statement, the function has no return value. .

Note:

When declaring a variable inside a function, if the var keyword is ignored, the variable is a global variable, as shown in the following example:

## After defining var, the twelfth line of code will Error

[Recommended learning:

javascript advanced tutorial]

The above is the detailed content of How to define a function in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn