DEV Community

Allison Kim
Allison Kim

Posted on • Edited on

First blog post...ever {object pointers}

Hello! Warm welcome to my very first blog post as an aspiring software developer - where I'm currently learning to code at the Flatiron School. I aim to use this blog to track my growth and progress in the coding world.

Full disclosure: I probably know about as much of coding as a brand-new driver knows what's under the hood of her car. I simply know how to get from point A to point B -- make the code do what I want it to -- but nothing on how to make the car use gas more efficiently or what parts it's even using at all.

To get an idea of where I'm at, one thing I realized most recently - that was a big stepping stone for me - is the ability to assign a variable to an already-defined object (as a pointer) in order to make modifications to said object in a different scope.

To illustrate:

let variable = {}; /* first, globally defining an empty object to
be used later */

/* The "parent function" that defines an object in it's own
scope and calls the function passed in as an argument to modify
said object */
function parentFunction(functionName) {
    const dataObj = {
        key1: "I want to change this value.",
        key2: "I want to keep this value.",
    };

    variable = dataObj; /* re-assigning (or pointing) our empty
object to the defined object */

    functionName(variable); /* calling the callback function and
passing our variable to be updated */

    console.log(dataObj); /* this is just to see what's in our
defined object after the callback function's been called */
};

//Callback function that changes a value of an object
function callbackFunction(object) {
    object.key1 = "This value has been changed.";
};

parentFunction(callbackFunction); //invoking the parent function
Enter fullscreen mode Exit fullscreen mode

Then, in our console log, we'll see our defined-object has been updated to:

{
  key1: 'This value has been changed.',
  key2: 'I want to keep this value.'
}
Enter fullscreen mode Exit fullscreen mode

Note: the argument that was passed into the callback function was the variable variable and not the actual dataObj. Yet the changes persisted on the dataObj, because variable acts as a pointer instead of a separate object. This was a breakthrough for me as the thought came to my head as I was trying to fall asleep one random night. Hope it can be of use to any new developers that come across this!

Also, quick note on another trick I learned:
To replace the space character in a string with another character, simply use:

string.replace(/\s/g,"<add character you want to replace with>")
Enter fullscreen mode Exit fullscreen mode

Thanks for reading!

Top comments (1)

Collapse
 
andrewbaisden profile image
Andrew Baisden

Welcome to the community it's great to have you here 👍