LEARNING JAVASCRIPT - Trang 130

const

a

=

5

,

b

=

10

;

avg

(

a

,

b

);

The variables

a

and

b

here are separate, distinct variables from the arguments

a

and

b

in the function

avg

, even though they share the same name. When you call a func‐

tion, the function arguments receive the values that you pass in, not the variables

themselves. Consider the following code:

function

f

(

x

) {

console.log(

`inside f: x=

${

x

}

`

);

x

=

5

;

console.log(

`inside f: x=

${

x

}

(after assignment)`

);

}

let

x

=

3

;

console.log(

`before calling f: x=

${

x

}

`

);

f

(

x

);

console.log(

`after calling f: x=

${

x

}

`

);

If you run this example, you will see:

before calling f: x=3
inside f: x=3
inside f: x=5 (after assignment)
after calling f: x=3

The important takeaway here is that assigning a value to

x

inside the function doesn’t

affect the variable

x

that’s outside the function; that’s because they’re two distinct enti‐

ties that happen to have the same name.
Whenever we assign to an argument inside a function, there will be no effect on any

variables outside of the function. It is, however, possible to modify an object type in a

function in such a way that the object itself changes, which will be visible outside of

the function:

function

f

(

o

) {

o

.

message

=

`set in f (previous value: '

${

o

.

message

}

')`

;

}

let

o

=

{

message

:

"initial value"

};

console.log(

`before calling f: o.message="

${

o

.

message

}

"`

);

f

(

o

);

console.log(

`after calling f: o.message="

${

o

.

message

}

"`

);

This results in the following output:

before calling f: o.message="initial value"
after calling f: o.message="set in f (previous value: 'initial value')"

In this example, we see that

f

modified

o

within the function, and those changes

affected the object

o

outside of the function. This highlights the key difference

106 | Chapter 6: Functions