Home >Web Front-end >Front-end Q&A >What is used to define functions in javascript
How to define a function in JavaScript: 1. Use the function keyword to define a named function, and the syntax is "function function name (parameter) {executed code}"; 2. Use "var x=function(name){ Code executed};" defines an anonymous function.
The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.
1. JavaScript uses the keyword function to define functions.
A function can be defined through a declaration or an expression.
Function declaration syntax:
function functionName(parameters) { 执行的代码}
The function will not be executed immediately after it is declared, but will be called when we need it.
Example:
function myFunction(a, b) { return a * b; }
Note:
Semicolons are used to separate executable JavaScript statements.
Since the function declaration is not an executable statement, it does not end with a semicolon.
2. Function expression
JavaScript functions can be defined by an expression.
Function expressions can be stored in variables:
var x = function (a, b) {return a * b};
After the function expression is stored in a variable, the variable can also be used as a function:
var x = function (a, b) {return a * b}; var z = x(4, 3);
The above function actually is an anonymous function (function has no name).
Function is stored in a variable and does not require a function name. It is usually called through the variable name.
Note: The above function ends with a semicolon because it is an execution statement.
Function() Constructor
In the above example, we learned that functions are defined through the keyword function.
Functions can also be defined through the built-in JavaScript function constructor (Function()).
var myFunction = new Function("a", "b", "return a * b"); var x = myFunction(4, 3);
The above example can be written as:
var myFunction = function (a, b) {return a * b}; var x = myFunction(4, 3);
[Related recommendations: javascript video tutorial, web front-end]
The above is the detailed content of What is used to define functions in javascript. For more information, please follow other related articles on the PHP Chinese website!