??? javascript is mutable !!!

There goes another few hours.. :-(
Please dont spread this around and dont say I wrote this after ~20 years of programming.
But JS is kinda mutable ????


var o1,o2
function fChange(arg){
    arg.k += '-new'
    return arg
}

o1 = {k: 'v1'}
o2 = {k: 'v2'}
o2 = fChange(o1)
console.log('1A) o1=' + JSON.stringify(o1))
console.log('1B) o2=' + JSON.stringify(o2))
//---
function fChange2(arg){
    arg = $.extend(true,{},arg)
    arg.k += '-new'
    return arg
}
o1 = {k: 'v1'}
o2 = {k: 'v2'}
o2 = fChange2(o1)
console.log('2A) o1=' + JSON.stringify(o1))
console.log('2B) o2=' + JSON.stringify(o2))

Results in:


1A) o1={"k":"v1-new"}
1B) o2={"k":"v1-new"}
//---
2A) o1={"k":"v1"}
2B) o2={"k":"v1-new"}

Conclusion:
Result 1A) is utterly amazing !
And terrifying !
Is the object o1 passed in by reference ? Yes it appears so.

~Solution:
Can be seen in fChange2(). Use jquery $.extend() to make a (deep or not) value copy.

arg = $.extend(true,{},arg)

And o1 remains unmutated, as we’d want it to be. See result 2A)
Alternative, not needing jquery, is:

arg = JSON.parse(JSON.stringify(arg))

Using the JSON lib also has the advantage that you dont have to handle cases where arg is Array containing objects in which case you’d need to use arg = $.extend(true,[],arg)

Please be silent and enjoy your knowledge !

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s