JS Functions
In this page:
function functionName(parameter1, parameter2) {
// body
return value;
}
functionName(argument1, argument2);
Function Declaration
Function declaration function keyword से code का एक नामित, पुन: उपयोग योग्य block परिभाषित करता है, जिसे फिर उस नाम से कहीं भी बुलाया जा सकता है जहाँ वह scope में हो।
उदाहरण: Function Declaration
// Define the function `greetUser` with no parameters
// Define the function `greetUser` with no parameters
function greetUser() {
// Print "Hello!" to the console
// Print "Hello!" to the console
console.log("Hello!");
}
// Call `greetUser()`
// Call `greetUser()`
greetUser();
Parameters और Arguments
Parameters function की परिभाषा में सूचीबद्ध नामित placeholders हैं, जबकि arguments वे असली values हैं जो function बुलाते समय दिए जाते हैं, parameters बताते हैं कि function क्या उम्मीद करता है, arguments उसे उपलब्ध कराते हैं।
उदाहरण: Parameters and Arguments
function add(a, b) {
console.log(a + b);
}
add(2, 3); // 2 and 3 are arguments
Return Values
return keyword किसी value को function से बाहर उसे बुलाने वाले तक भेजता है, और जैसे ही return चलता है, function तुरंत execute होना बंद कर देता है और उसके बाद के code को छोड़ देता है।
उदाहरण: Return Values
// Define the function `square` taking `n`
// Define the function `square` taking `n`
function square(n) {
// Return `n * n` from this function
// Return `n * n` from this function
return n * n;
}
// Print `square(4)` to the console
// Print `square(4)` to the console
console.log(square(4));
Default Parameters
Default parameters आपको function की परिभाषा में ही एक बैकअप value देने देते हैं, जो अपने-आप तब इस्तेमाल होता है जब बुलाने वाला उस parameter के लिए कोई argument न दे।
उदाहरण: Default Parameters
// Define the function `greet` taking `name`
// Define the function `greet` taking `name`
function greet(name = "Guest") {
// Print `Hello, ${name}!` to the console
// Print `Hello, ${name}!` to the console
console.log(`Hello, ${name}!`);
}
// Call `greet()`
// Call `greet()`
greet();
// Call `greet("Amit")`
// Call `greet("Amit")`
greet("Amit");
Function Expressions और Hoisting
Function expression किसी function को स्वतंत्र नाम देने की बजाय variable के अंदर रखता है, और function declarations के विपरीत, जो hoist होते हैं और अपने scope में कहीं भी बुलाए जा सकते हैं, function expressions केवल उस line के बाद उपयोग हो सकते हैं जहाँ वे परिभाषित हैं।
उदाहरण: Function Expressions and Hoisting
// Declare the constant `sayHi`, set to `function () {`
// Declare the constant `sayHi`, set to `function () {`
const sayHi = function () {
// Print "Hi!" to the console
// Print "Hi!" to the console
console.log("Hi!");
};
// Call `sayHi()`
// Call `sayHi()`
sayHi();
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: