The parameters are essentially passed to function by value - so if the code within the body of a function assigns a completely new value to a parameter that was passed to the function, the change is not reflected globally or in the code which called that function.
function changeValueIntoC(value) {
value = "C"
}
let myValue = "A"
console.log(myValue) // A
changeValueIntoC(myValue)
console.log(myValue) // A
// The value won't change because the parameters are passed to function by value
When objects or arrays are passed, they are passed by reference.
function addNameToObj(obj) {
obj.name = 'HI This is your name.'
}
const cat = {
gender: 'boy',
cute: true,
age: 4
}
console.log(cat) // {gender: "boy", cute: true, age: 4}
addNameToObj(cat)
console.log(cat) // {gender: "boy", cute: true, age: 4, name: "MeowMeow"}
function pushValueIntoArray(arr) {
arr.push('new value')
}
const myArray = [1, 2, 3, 4]
console.log(myArray) // [1, 2, 3, 4]
pushValueIntoArray(myArray)
console.log(myArray) // [1, 2, 3, 4, "new value"]
Javascript do hoisting
let a = 1
console.log(a)
function test1() {
a = 3
change(a)
console.log(a)
}
function change() {
console.log(a)
a = 4
}
test1()
console.log(a)
// 1 - line 3
// 3 - line 13
// 4 - line 8
// 4 - line 20