JS रेस्ट पैरामीटर्स
In this page:
function functionName(first, ...rest) {
// rest is an array of the remaining arguments
}
Rest Parameters क्या हैं
Rest parameters spread जैसा ही ... syntax इस्तेमाल करते हैं पर उल्टी दिशा में, function के अंदर कितने भी बचे हुए arguments को एक असली single array में इकट्ठा करते हुए।
उदाहरण: What Are Rest Parameters
function showArgs(...args) {
console.log(args); // a real array
}
showArgs(1, 2, 3);
Calculations में Rest
एक आम इस्तेमाल sum(...numbers) जैसा function लिखना है जो कितने भी arguments स्वीकार करता है और उन्हें साथ में reduce करता है, बिना पहले से यह जाने कि कितनी values पास होंगी।
उदाहरण: Rest in Calculations
// Define the function `sum` taking `...numbers`
// Define the function `sum` taking `...numbers`
function sum(...numbers) {
// Return `numbers.reduce((total, n) => total + n, 0)` from this function
// Return `numbers.reduce((total, n) => total + n, 0)` from this function
return numbers.reduce((total, n) => total + n, 0);
}
// Print `sum(1, 2, 3, 4)` to the console
// Print `sum(1, 2, 3, 4)` to the console
console.log(sum(1, 2, 3, 4));
Rest और Array Destructuring
किसी array को destructure करते समय, [first, ...rest] जैसा एक rest element पहली value को अलग से capture करता है और बाकी सब कुछ rest नाम की एक नई array में इकट्ठा कर देता है, जो किसी list के पहले element को बाकी list से अलग करने के लिए काम आता है।
उदाहरण: Rest and Array Destructuring
const [first, ...rest] = [1, 2, 3, 4];
console.log(first, rest);
Rest और Object Destructuring
किसी object को destructure करते समय भी यही pattern काम करता है, जहाँ {id, ...details} id को अलग से निकालता है और बाकी हर property को एक नए details object में इकट्ठा कर देता है, जो किसी record के एक खास field को बाकी से अलग करने के लिए उपयोगी है।
उदाहरण: Rest and Object Destructuring
const { id, ...details } = { id: 1, name: "Sam", age: 30 };
console.log(id, details);
Rest के नियम
किसी function की parameter list में rest parameter को आखिरी parameter होना चाहिए, क्योंकि JavaScript को यह जानना ज़रूरी है कि fixed parameters कहाँ खत्म होते हैं और open-ended collection कहाँ से शुरू होता है।
उदाहरण: Rest Rules
function log(first, ...rest) {
console.log(first, rest);
}
log(1, 2, 3);
// function log(...rest, last) {} // SyntaxError: rest must be last
- rest parameter को पहले या बीच में रखना, जैसे
function f(...a, b), जो एकSyntaxErrorहै; यह आखिरी होना चाहिए। - rest को spread से confuse करना, क्योंकि rest किसी parameter list में values को एक array में collect करता है और spread उन्हें किसी call पर expand करता है।
- किसी function में एक से ज़्यादा rest parameter इस्तेमाल करना, जो एक
SyntaxErrorहै।
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: