xxxxxxxxxx
// add function with params x, y
function add(x,y){
return x+y; // return function params
}
// let result equal add with value 5, 6
let result = add(5,6);
// log to the console result
console.log(result)
xxxxxxxxxx
function greet(name) {
function displayName() {
console.log('Hi' + ' ' + name);
}
// returning a function
return displayName;
}
const g1 = greet('John');
console.log(g1); // returns the function definition
g1(); // calling the function
xxxxxxxxxx
function square(x) {
return x * x;
}
const demo = square(3);
// demo will equal 9
xxxxxxxxxx
function test()
{
return function x()
{
return "xxxxxxxx"
}
}
console.log(test())
//[Function: x()]
console.log(test()())
//xxxxxxxx
xxxxxxxxxx
/* The return statement ends a function immediately at the
point where it is called. */
function counter() {
for (var count = 1; count < 5 ; count++) {
console.log(count + 'A');
if (count === 3) return; // ends entire counter function
console.log(count + 'B');
}
console.log(count + 'C'); // never appears
}
counter();
// 1A
// 1B
// 2A
// 2B
// 3A
xxxxxxxxxx
An Example of a return function
function add15(number) {
let newNumber = number + 15;
return newNumber;
}
let fifteen = add15(5);
console.log(fifteen);
xxxxxxxxxx
// program to add two numbers
// declaring a function
function add(a, b) {
return a + b;
}
// take input from the user
let number1 = parseFloat(prompt("Enter first number: "));
let number2 = parseFloat(prompt("Enter second number: "));
// calling function
let result = add(number1,number2);
// display the result
console.log("The sum is " + result);
xxxxxxxxxx
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
xxxxxxxxxx
//The return statement ends function execution,
//and specifies a value to be returned to the function caller.
function getRectArea(width, height) {
if (width > 0 && height > 0) {
return width * height;
}
return 0;
}
console.log(getRectArea(3, 4));
// expected output: 12
console.log(getRectArea(-3, 4));
// expected output: 0