Home > Web Front-end > JS Tutorial > How to use function in js

How to use function in js

下次还敢
Release: 2024-05-06 12:09:19
Original
833 people have browsed it

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.

How to use function in js

Function in JavaScript

A function in JavaScript is a block of code that can be reused and can pass parameters and return results.

Usage

Declaring functions

There are four ways to declare functions:

  • Function declaration: function function name (parameter) {code block}
  • Function expression: const function name = (parameter) => {code block}
  • Self-calling function: (function() {code block})()
  • Class method: class class name { method name (parameters) { code block } }

Calling a function

To call a function just use its name, followed by any parameters in parentheses:

<code class="javascript">函数名(参数1, 参数2);</code>
Copy after login

Parameters

The function can receive parameters, which are used as variables in the function body.

Return value

A function can return a value using the return keyword.

Example

Function declaration:

<code class="javascript">function sayHello(name) {
  return `Hello, ${name}!`;
}

const greeting = sayHello("Bob");
console.log(greeting); // 输出:"Hello, Bob!"</code>
Copy after login

Function expression:

<code class="javascript">const multiply = (a, b) => {
  return a * b;
};

const product = multiply(10, 5);
console.log(product); // 输出:50</code>
Copy after login

Since Calling function:

<code class="javascript">(function() {
  console.log("立即执行!");
})();

// 输出:"立即执行!"</code>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template