Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialGreg Schudel
4,090 Pointsreference vs value in Javascript
What is the different between a reference and a value in javascript? Could someone please provide a metaphor to make things clear?
Here is an example below:
const changeColor = document.getElementById('myHeading');
const colorButton = document.querySelector('button');
const myTextInput = document.getElementById('myTextInput');
colorButton.addEventListener('click', () => {
changeColor.style.color = myTextInput.value;
});
html file:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript and the DOM</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<h1 id="myHeading">JavaScript and the DOM</h1>
<button id="changeColor" > Change Font Color </button>
<button id="changeBackgroundColor" > Change Background Color </button>
<p>Making a web page interactive</p>
<p title="label" >Things that are purple:</p>
<input type="text" id="myTextInput">
<ul>
<li>grapes</li>
<li class="error-not-purple">oranges</li>
<li>amethyst</li>
<li>lavender</li>
<li class="error-not-purple">fire trucks</li>
<li class="error-not-purple">snow</li>
<li>plums</li>
</ul>
<script src="app.js"></script>
</body>
</html>
2 Answers
Steven Parker
231,261 PointsJavaScript makes this simple: Scalar types (like numbers or strings) are always values. Complex types (like objects or arrays) are always references.
Examples:
var a = 1;
var b = a; // the VALUE of a is assigned
b = 22;
console.log(a); // a is still 1
var x = [1, 2];
var y = x; // a REFERENCE to x is assigned
y[0] = 99;
console.log(x[0]); // x[0] is now 99
Jason Anders
Treehouse Moderator 145,860 PointsHey Greg,
I'm not sure I completely understand your question, sorry. JavaScript doesn't really use references
vs values
as other languages like Swift or Java do. JavaScript always passes values and not references, and this is all I see in the example you have given.
I did find a Stack Overflow thread that kind of explains this.
I hope this helps, but if I have misunderstood your question I apologize.
Keep Coding! :)