Functions in JavaScript can be reused. The usage is as follows: Function declaration: Use the function keyword to declare, receive parameters and return results. Function expressions: declared using const, receiving parameters and returning results using arrow notation (=>). Self-invoking functions: Declared using an immediately invoked function expression (IIFE), they execute immediately when defined. Class method: A method declared in the class definition, usually used on objects.
A function in JavaScript is a block of code that can be reused and can pass parameters and return results.
There are four ways to declare functions:
function function name (parameter) {code block}
const function name = (parameter) => {code block}
(function() {code block})()
class class name { method name (parameters) { code block } }
To call a function just use its name, followed by any parameters in parentheses:
<code class="javascript">函数名(参数1, 参数2);</code>
The function can receive parameters, which are used as variables in the function body.
A function can return a value using the return
keyword.
Function declaration:
<code class="javascript">function sayHello(name) { return `Hello, ${name}!`; } const greeting = sayHello("Bob"); console.log(greeting); // 输出:"Hello, Bob!"</code>
Function expression:
<code class="javascript">const multiply = (a, b) => { return a * b; }; const product = multiply(10, 5); console.log(product); // 输出:50</code>
Since Calling function:
<code class="javascript">(function() { console.log("立即执行!"); })(); // 输出:"立即执行!"</code>
Class method:
<code class="javascript">class Person { constructor(name) { this.name = name; } greet() { console.log(`Hello, my name is ${this.name}!`); } } const person = new Person("Alice"); person.greet(); // 输出:"Hello, my name is Alice!"</code>
The above is the detailed content of How to use function in js. For more information, please follow other related articles on the PHP Chinese website!