The usage of return in JavaScript requires specific code examples
In JavaScript, the return statement is used to specify the value returned from a function. Not only can it be used to end the execution of a function, it can also return a value to the place where the function was called.
The return statement has the following common uses:
function add(a, b) { return a + b; } var result = add(3, 4); console.log(result); // 输出结果为7
In the above code, the add function accepts two parameters a and b, returns their sum to the place where the function is called through the return statement, and finally assigns the result Give the variable result and output it.
function greet(name) { if (!name) { return; // 如果name为空,直接结束函数的执行 } console.log("Hello, " + name + "!"); } greet("Alice"); // 输出结果为: Hello, Alice! greet(); // 由于没有传递参数,函数被提前终止,不会有任何输出
In the above code, the greet function accepts a parameter name. If the name is empty, the execution of the function is terminated early through the return statement, otherwise the greeting is printed.
function createPerson(name, age) { return { name: name, age: age }; } var person = createPerson("Bob", 25); console.log(person); // 输出结果为: { name: "Bob", age: 25 }
In the above code, the createPerson function accepts two parameters name and age, and returns an object containing these two properties through the return statement. Finally, the result is assigned to the variable person and output.
It should be noted that the return statement will only immediately end the execution of the function and return control to the place where the function was called. If there is other code after the return statement, they will not be executed.
Summary:
There are three main usage scenarios of the return statement in JavaScript: returning a value, terminating the execution of a function early and returning an object. For beginners, it is very important to understand the usage of the return statement, which can help us write more flexible and powerful functions. I hope that through the explanation and sample code of this article, readers can better understand and master the usage of return.
The above is the detailed content of Use the return keyword in JavaScript. For more information, please follow other related articles on the PHP Chinese website!