🔮 Sanity Create is here. Writing is reinvented. Try now, no developer setup

Modifying a string value via a callback in JavaScript

8 replies
Last updated: Jun 16, 2020
Hi! I'm struggling with some javascript. Can someone who knows more about JS confirm the following?
I'm trying to modify the value of a string via a callback, but I think my efforts are futile.

var object = {
  item: {
    content: ""
  collection: []

function preprocess(callback) {
// ...

preprocess(({ collection, content }) => {
    content = "new content"
    collection = ["new-item-1", "new-item-2", "new-item3"];

// => "new content"
Is there a way to make this work?
Jun 16, 2020, 6:20 PM
It looks like you’re not passing in
anywhere for it to be modified.
Jun 16, 2020, 6:32 PM
Object would be passed inside the function.
So something like

function preprocess(callback) {
  callback({collection: object.collection, content: object.item.content})

This is a simplified example.
Jun 16, 2020, 6:40 PM
I don’t think that will work. You’re expecting
to be a “reference” to the
but when you destructure args likes that you will get a “copy” of the arg (not a reference).
If you modify that variable you are only modifying your local copy — not the original
Jun 16, 2020, 7:14 PM
see here
Jun 16, 2020, 7:14 PM
never gets modified
Jun 16, 2020, 7:14 PM
but if you handle the whole
in your function you can modify
(because you haven’t destructured it in the function signature
Jun 16, 2020, 7:15 PM
Hey, thanks. I understand now that I have to pass the object through. This clarifies my thinking that you can only modify an object that is passed through a callback.
Jun 16, 2020, 9:04 PM
For my use case I cannot pass the object through, but I have some alternative ideas.
Jun 16, 2020, 9:07 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?