Parameters of outer and inner functions in JavaScript
Let's make both the outer function and the inner function accept parameters:
function test(num) {
function func(localNum) {
console.log(localNum);
}
}
Let's pass the parameter of the external function to the call of the internal function:
function test(num) {
function func(localNum) {
console.log(localNum); // shows 1
}
func(num); //!! passes the parameter
}
test(1); // passes a number as a parameter
It turns out that the variable num
will be available in the inner function as
an external variable from the parent function
and the variable localNum
, which
is a local variable of the inner function.
Both of these variables will have the same value:
function test(num) {
function func(localNum) {
console.log(num); // shows 1
console.log(localNum); // shows 1
}
func(num);
}
test(1);
The difference between them will be as
follows: if you change the variable
num
in the inner function, it
will also change in the outer function:
function test(num) {
function func(localNum) {
num = 2; // changes the variable num
}
func(num); // passes the parameter
console.log(num); // shows 2
}
test(1); // passes a number as a parameter
And the variable localNum
will be
local. Its changes will not lead to any
changes in the external function. And the
variable localNum
itself will not
be visible outside the inner function:
function test(num) {
function func(localNum) {
localNum = 2; // changes the num variable
}
func(num); // passes the parameter
}
test(1); // passes a number as a parameter
Determine what will be output to the console without running the code:
function test(num) {
function func(localNum) {
console.log(localNum);
}
func(num);
}
test(1);
Determine what will be output to the console without running the code:
function test(num) {
function func(localNum) {
console.log(localNum);
}
func(num + 1);
}
test(1);
Determine what will be output to the console without running the code:
function test(num) {
function func(localNum) {
console.log(num);
}
func(num + 1);
}
test(1);
Determine what will be output to the console without running the code:
function test(num) {
function func(localNum) {
localNum = 2;
}
func(num);
console.log(num);
}
test(1);
Determine what will be output to the console without running the code:
function test(num) {
function func(localNum) {
localNum = 2;
}
func(num);
console.log(localNum);
}
test(1);
Determine what will be output to the console without running the code:
function test(num) {
function func(localNum) {
num = 2;
}
func(num);
console.log(num);
}
test(1);