Pass By Value vs. By Reference In JavaScript


So I’m building a little app in JavaScript and a piece of the code that I thought was simple, didn’t want to cooperate. I proceed to dig into WHY this was happening and came across one of those features of JavaScript that I felt could use a little explanation here.

JavaScript values are passed by value, not by reference.

This is one of those features of JavaScript you don’t see getting too much attention.

For example if you have an input and you then select it like so:

var input = document.querySelector(‘input’);

Plus:

var finalScore = 7;

var finalScoreDisplay = document.querySelector(‘#finalScoreDisplay’);

Then you do:

var userFinalScore = input.value;
var userFinalNumber = Number(userFinalScore);

And you also have:

input.addEventListener(‘change’, function(){
finalScore = userFinalNumber;
finalScoreDisplay.textContent = finalScore;
});

Weird things start happening when you start putting DOM (Document Object Model) representations of HTML elements, while accessing their properties, and then trying to put that into variables. They don’t seem to work anymore. It’s as if the value gets overwritten, AND/OR the variable’s not actually getting assigned the value. Or at least the value you intended to assign it.

This would be because the variable is getting assigned a reference to the location of the object, as a value. As opposed to the variable getting assigned the value of the object’s property itself.

Interesting.

By the way if you see something else going on here I might like to know about, let me know! Comment, email, smoke signal, it’s all fine. I’d appreciate it.

And now, back to coding.

Love & Peace,

Danielle