Let's talk about the definition and basic use of JavaScript functions
This article brings you relevant knowledge about javascript, which mainly organizes issues related to the definition and basic use of functions, including definitions with function statements, function calls, and undefined Let’s take a look at the actual parameters and so on. I hope it will be helpful to everyone.

[Related recommendations: javascript video tutorial, web front-end】
1. Define with function statements
Let’s give an example first. The function of this function is to return the sum of array elements;
function sumArray(arr) {
var sum = 0;
for(var i = 0,aLength = arr.length;i <p>Keyword <code>function</code>There is a space after it, <code>sumArray </code> is the name of the function, and its naming convention is the same as that of variable names: <strong> can only contain letters, numbers, underscores, and dollar signs, and cannot start with a number or be a keyword. </strong></p><p>The parameters in brackets are also called <strong>formal parameters</strong>. Only the parameter name is required. Parameters can be <code>0</code>, <code>1</code> or more, separated by <code>, </code>, <code>{}</code> is included in the middle <strong>Function body</strong>. Contains one or more statements. The function body is used to implement the function of the function. </p><p>Keyword<code>return</code> is followed by the <strong>return value</strong> of the function. The function can also have no return value. After the function is finished running, <code>return</code> this sentence will exit the operation, <code>return</code>The following statement <strong> will no longer run</strong>. The return value is the output of the function. </p><p>For a function defined in this way, <strong>the function can be called both before and after the function definition</strong>, as long as the function and the statement calling the function are in the same source file. </p><h2 id="Use-expression-definition">2. Use expression definition </h2><p> Define a function in the form of an expression, which is to use an assignment expression <strong> to assign the function to a variable </strong>. This is actually to see the function as into a variable. At this time, the function can have a name or no name. The function without a name is called <strong>anonymous function</strong>. </p>
- With name;
var funct = function getMax(a,b) {
return a>b?a:b; };//注意这后面的分号不能少,因为我们定义的是一个变量!
and are defined with function statementsThe difference is that they can only be defined after the function definition statementCall this function, and when calling, you can only use the variable name funct, but not the function name getMax, such as:
var funct = function getMax(a,b) {
return a>b?a:b;
};
console.log(funct(1,2));//输出2
- Anonymous function;
The so-called anonymous function is the keywordfunctionfollowed directly by the parameter list:
var funct = function(a,b) {
return a>b?a:b; };
This function has no name, it is assigned to the variablefunct, so it is called an anonymous function. Similarly, can only call this function after this statement.
var funct = function(a,b) {
return a>b?a:b; }; console.log(funct(1,2));//输出2
Summary: Defining a function with an expression is ready for use. Once defined, the function can only be called after this statement
3 .Function calling
In the fourth training, we once introduced that objects can have their own methods, and of course these are also functions. The call of this function is slightly different from the functions defined in the previous two levels.
//函数的定义:求三个数的最大值
function max(a,b,c) {
if(a > b) {
if(a > c)
return a;
else
return c;
}
else {
if(b > c)
return b;
else
return c;
}
}
//调用该函数
var result = max(1,2,3);//result为3
console.log(result);//输出3
When calling a function, you need to pass in the same number of specific values as the formal parameters. The above function has 3 parameters, so when calling the following, pass in 3 specific values, 1 is passed to parameter a, 2 is passed to parameter b, 3 Pass parameter c. The return value of the function is passed to the variable result through the assignment symbol =. If there is no return keyword in the function body, undefined will be returned.
Call the function defined in the object:
var ob = {
id:1,
getMax:function(a,b) {
return a>b?a:b;
} }; var result = ob.getMax(2,1);//result值为2 var result1 = ob["getMax"](2,1);//result1的值也是2
The difference from the above is that to locate the function here, you need to use the object name. Function name or Object name ["function name"], the others are the same.
4. Undefined actual parameters
In most programming languages, the number and type of actual parameters passed in when calling a function will be checked, and JavaScriptBoth does not check the type of actual parameters, nor does it check the number of actual parameters. The actual parameters in JavaScript will match the formal parameters in order from left to right, for example:
function myFunction(a,b,c) {
console.log(a);
console.log(b);
console.log(c); } myFunction(1,2,3);
actual parameters1Incoming formal parameters a, actual parameters 2 Incoming formal parameters b, Incoming actual parameters 3 Incoming formal parameters c. When the number of actual parameters is less than the formal parameters, the value undefined will be passed to the right formal parameter. For example:
function myFunction(a,b,c) {
console.log(a);
console.log(b);
console.log(c); } myFunction(1,2);
actual parameter1pass in formal parametera,actual parameter2pass in formal parameterb,undefinedIncoming formal parametersc. If you only want to pass data to the parameters on the right, you can pass undefined to the first few actual parameters. For example:
function myFunction(a,b,c){ console.log(a); console.log(b); console.log(c); } myFunction(undefined,1,2);
The above two methods are not rigorous enough. The best practice is to set a default value for formal parameters that may be passed in an undefined value. like:
function getSum(a,b,c) {
if(c === undefined)
c = 0;
console.log(a+b+c); } myFunction(1,2);
5.实参对象
JavaScript一切都是对象,实参也是一个对象,有一个专门的名字arguments,这个对象可以看成一个数组(类数组,不是真的数组),实参从左到右分别是arguments[0]、arguments[1]...,arguments.length表示实参的个数。
//求参数的和 function getSum() {
var aLength = arguments.length;
var sum = 0;
for(var i = 0;i <p>这里的形参直接省略,使用<code>arguments[i]</code>表示。</p><h2 id="对象作为参数">6.对象作为参数</h2><p>复杂的函数通常多达十几个参数,尽管<code>JavaScript</code>不做参数个数和类型的检查,但是调用时实参的顺序不能乱。开发人员需要检查每一个实参和形参的对应关系,这样效率很低。一种很好的解决方案是使用对象作为参数,函数会根据对象的<strong>属性名</strong>操作参数。</p><pre class="brush:php;toolbar:false">function myFunction(obj) {
console.log(obj.name);
obj.number++;
return obj.number; } myObj = {name:"myObj",number:34}; myFunction(myObj);//输出myObj console.log(myObj.number);//输出357.函数对象作为另一个函数的参数
一个函数(为方便行文,称为a函数)可以作为另外一个函数(称为b函数)的参数,b函数最终可以返回一个具体的值。
从原理上来说,b函数在自己的函数体内调用了a函数,所以需要把a函数的名字作为实际参数传递给b函数。如下:
//求最大值 function getMax(a,b) {
return a>b?a:b; } //求最小值 function getMin(a,b) {
return a<b></b><p>我们把<code>a</code>函数的名字(<code>getMax</code>或者<code>getMin</code>)传给<code>b</code>函数(<code>getM()</code>),然后在<code>b</code>函数内部调用传入的<code>a</code>函数,得到相关的结果。</p><p>【相关推荐:<a href="//m.sbmmt.com/course/list/17.html" target="_blank" textvalue="javascript视频教程">javascript视频教程</a>、<a href="//m.sbmmt.com/course/list/1.html" target="_blank">web前端</a>】</p>The above is the detailed content of Let's talk about the definition and basic use of JavaScript functions. For more information, please follow other related articles on the PHP Chinese website!
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AMThis article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base
JavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AMJavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.
The Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AMThe latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools







