|
| 1 | +/* |
| 2 | +Primitive values: |
| 3 | +
|
| 4 | +These are the most basic values one can think of, which includes, undefined, null, boolean, string, and numbers. Primitive values are passed by value in javascript |
| 5 | +
|
| 6 | +Whereas all objects (including functions) are passed by reference in javascript. |
| 7 | +*/ |
| 8 | + |
| 9 | +/* |
| 10 | +Javascript pass by reference: |
| 11 | +In Pass by Reference, a function is called by directly passing the reference/address of the variable as the argument. Changing the argument inside the function affects the variable passed from outside the function. In Javascript objects and arrays are passed by reference. |
| 12 | +*/ |
| 13 | + |
| 14 | +//javascript pass by reference |
| 15 | +function callByReference(varObj) { |
| 16 | + console.log('Inside Call by Reference Method') |
| 17 | + |
| 18 | + varObj.a = 100 |
| 19 | + |
| 20 | + console.log(varObj) |
| 21 | +} |
| 22 | + |
| 23 | +let myObj = { |
| 24 | + a: 1, |
| 25 | +} |
| 26 | + |
| 27 | +console.log('Before Call by Reference Method') |
| 28 | + |
| 29 | +console.log({ myObj }) // { myObj: { a: 1 } } |
| 30 | + |
| 31 | +callByReference(myObj) |
| 32 | + |
| 33 | +console.log('After Call by Reference Method') |
| 34 | + |
| 35 | +console.log({ myObj }) // { myObj: { a: 100 } } |
| 36 | + |
| 37 | +/* |
| 38 | +
|
| 39 | +In javascript pass by value, the function is called by directly passing the value of the variable as the argument. Therefore, even changing the argument inside the function doesn’t affect the variable passed from outside the function. |
| 40 | +
|
| 41 | +It is important to note that in javascript, all function arguments are always passed by value. That is, JavaScript copies the values of the passing variables into arguments inside of the function. |
| 42 | +*/ |
| 43 | + |
| 44 | +//javascript pass by value |
| 45 | +function square(x) { |
| 46 | + x = x * x |
| 47 | + |
| 48 | + return x |
| 49 | +} |
| 50 | + |
| 51 | +var y = 10 |
| 52 | + |
| 53 | +var result = square(y) |
| 54 | + |
| 55 | +console.log(y) // 10 -- no change |
| 56 | +console.log(result) // 100 |
| 57 | + |
| 58 | +// |
| 59 | +const arr = [1, 2, 3, 4] |
| 60 | + |
| 61 | +const updateArr = (arr, newValue) => arr.push(newValue) // Will mutate original array |
| 62 | +const updateArrWithoutMut = (arr, newValue) => [...arr].push(newValue) // Will not mutate original array |
| 63 | + |
| 64 | +console.log({ arr }) |
| 65 | + |
| 66 | +// updateArr(arr, 10) |
| 67 | +updateArrWithoutMut(arr, 10) |
| 68 | + |
| 69 | +console.log({ arr }) |
0 commit comments