Suppose we have a function that takes a number as a parameter:
function func(localNum) {
console.log(localNum);
}
Let there be the variable num
outside the function:
function func(localNum) {
console.log(localNum);
}
let num = 1; // the external global variable
Let's invoke our function, passing it
the variable num
as a parameter:
function func(localNum) {
console.log(localNum);
}
let num = 1;
func(num); // call the function with a parameter, shows 1
It turns out that both the localNum
variable (function parameter) and the
num
variable (as an external
variable) will be available inside
the function:
function func(localNum) {
console.log(num); // shows 1
console.log(localNum); // shows 1
}
let num = 1;
func(num);
The variable localNum
itself will
be a local variable of the function and
will not be accessible from outside:
function func(localNum) {
}
let num = 1;
func(num); // call the function with a parameter
console.log(localNum); // will throw an error
Since the variable localNum
is local,
no changes to it will change anything outside:
function func(localNum) {
localNum = 2; // it doesn't change anything outside
}
let num = 1;
func(num);
If you change the variable num
(global)
inside, then the changes will appear outside:
function func(localNum) {
num = 2;
}
let num = 1;
func(num);
console.log(num); // shows 2
However, if inside the function we declare
the variable num
through let
,
then we will thus create the local variable
num
that does not affect the external
variable in any way:
function func(localNum) {
let num = 2; // declare with let
}
let num = 1;
func(num);
console.log(num); // shows 1 - nothing has changed
Determine what will be output to the console without running the code:
function func(localNum) {
console.log(localNum);
}
func(1);
Determine what will be output to the console without running the code:
function func(localNum) {
console.log(localNum);
}
let num = 1;
func(num);
Determine what will be output to the console without running the code:
function func(localNum) {
console.log(localNum);
}
let num = 1;
func(num);
num = 2;
Determine what will be output to the console without running the code:
let num = 1;
function func(localNum) {
console.log(localNum);
}
num = 2;
func(num);
Determine what will be output to the console without running the code:
function func(localNum) {
localNum = 2;
}
let num = 1;
func(num);
console.log(num);
Determine what will be output to the console without running the code:
function func(localNum) {
num = 2;
}
let num = 1;
func(num);
console.log(num);
Determine what will be output to the console without running the code:
function func(localNum) {
let num = 2;
}
let num = 1;
func(num);
console.log(num);