⬅ Previous Topic
Arrow Functions in JavaScriptNext Topic ⮕
JavaScript Scope - Local, Global, Block⬅ Previous Topic
Arrow Functions in JavaScriptNext Topic ⮕
JavaScript Scope - Local, Global, BlockFunctions in JavaScript are reusable blocks of code that can take inputs and produce outputs. These inputs are called parameters when defining the function, and arguments when calling the function.
Parameters are placeholders defined in a function declaration. Think of them as variables local to the function that will hold the values you pass when calling it.
function greet(name) {
console.log("Hello, " + name + "!");
}
In the above example, name
is the parameter.
Arguments are the actual values you pass into the function when invoking it. These values get assigned to the parameters.
greet("Alice");
Hello, Alice!
Yes. You can define multiple parameters and pass corresponding arguments.
function add(a, b) {
console.log("Sum:", a + b);
}
add(5, 7);
Sum: 12
If fewer arguments are passed, the missing ones become undefined
. If more are passed, the extra ones are ignored unless handled using the arguments
object or rest parameters.
function display(a, b) {
console.log("a =", a);
console.log("b =", b);
}
display(1); // only one argument
a = 1 b = undefined
A function can also return a value using the return
keyword. This allows the function to pass a result back to where it was called.
function multiply(x, y) {
return x * y;
}
let result = multiply(4, 5);
console.log("Result:", result);
Result: 20
The return
statement ends function execution and specifies the value to be returned. If there's no return, the function returns undefined
.
function sayHi() {
console.log("Hi there!");
}
let res = sayHi();
console.log("Return value:", res);
Hi there! Return value: undefined
Question: Can a function both return a value and print a message?
Answer: Yes! You can use console.log()
for displaying messages and return
for sending back a value.
function doubleIt(n) {
console.log("Doubling", n);
return n * 2;
}
let doubled = doubleIt(10);
console.log("Doubled value is:", doubled);
Doubling 10 Doubled value is: 20
You can use return values in larger expressions or pass them to other functions.
function square(n) {
return n * n;
}
console.log("Square of 6 plus 1 is:", square(6) + 1);
Square of 6 plus 1 is: 37
Understanding parameters, arguments, and return values is fundamental to writing reusable and effective functions in JavaScript. Parameters are defined in the function, arguments are the actual values passed in, and return values give you back a result that can be used further.
⬅ Previous Topic
Arrow Functions in JavaScriptNext Topic ⮕
JavaScript Scope - Local, Global, BlockYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.