Open In App

JavaScript function* expression

The function* is an inbuilt keyword in JavaScript which is used to define a generator function inside an expression.

Syntax:



function* [name]([param1[, param2[, ..., paramN]]]) {
statements
}

Parameters: This function accepts the following parameter as mentioned above and described below:

Example 1: Below examples illustrate the function* expression in JavaScript:






// Illustration of function* expression
// use of function* keyword
function* func() {
    yield 1;
    yield 2;
    yield 3;
    yield " - Geeks";
}
 
let obj = '';
 
// Function calling
for (const i of func()) {
    obj = obj + i;
}
 
// Output
console.log(obj);

Output
123 - Geeks

Example 2: Below examples illustrate the function* expression in JavaScript:




// Illustration of function* expression
// use of function* keyword
function* func2(y) {
    yield y * y;
};
 
function* func1() {
    for (let i = 1; i < 6; i++) {
        yield* func2(i);
    }
};
 
// Function calling
for (const x of func1()) {
 
    // Output
    console.log(x);
};

Output
1
4
9
16
25

Supported Browsers:

The browsers supported by JavaScript function* expression are listed below:


Article Tags :