for an object say : let a = {name: 'xyz'}
when we create a function to change name property for example :
let chN = function (object) {
object.name = 'qwerty';
}
Why is it not necessary to add the “return” keyword to change object property?
for an object say : let a = {name: 'xyz'}
when we create a function to change name property for example :
let chN = function (object) {
object.name = 'qwerty';
}
Why is it not necessary to add the “return” keyword to change object property?
Because if you don’t, the function implicitly returns undefined.
Hey, Actually you are dealing with object(in your case a) which is a reference type.
When you pass object a to function then a reference is created(object variable in your case) so you are directly modifying object a. So No need to return anything.
A function takes some input, does some work, generates some output. In your case, you take an object, mutate it (eg directly change the value inside that object), and the function returns undefined
. The work this function does is called a side effect: it does something other than just returning a value. You don’t need to return
because you don’t care what the return value is. The function updates something in your system outside of the function.
As another example:
function logSomething(thing) {
console.log(thing);
}
And another:
function addSomeTextToAnHTMLElement(elementId, text) {
document.getElementById(elementId).innerText = text;
}
Side effects & state make code more complicated and harder to test, but you can’t actually do anything interesting (eg make stuff appear on a computer screen) without them
As a comparison, a function that might have no side effects (and has to return a value):
function chN (object, newName) {
return Object.assign({}, object, {name: newName });
}
This takes the input object and returns a copy of it with the name changed to whatever you say. Note it returns the entire object. As long as you give it the same input, it is guaranteed* to give you the same output with no side effects.
chN({name: 'xyz'}, 'qwerty')
// returns a brand new object like `{name: 'qwerty'}
chN({name: 'xyz'}, 'qwerty')
// another brand new object
* sort of, JS is bit freeform here and there are many ways around it