Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

169
Views
Beginner questions - Variables inside and outside of functions

I am pretty new to Javascript and have a beginner question in regards to declaring and accessing variables. Why does the console.log show me that the textContent of "text" has been changed when it hasn't? I can get the function to work if I instead of declaring "text" OUTSIDE of the function declare it inside - then the actual textContent change

let text = document.querySelector("#text").textContent

function changeText() {
  text = "Goodbye"
}

changeText()
console.log(text)
<p id="text">Hi</p>

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

This assignment:

let text = document.querySelector("#text").textContent

stores a copy of the value of document.querySelector("#text").textContent in text. The is no explicit or implicit connection between text and document.querySelector("#text").textContent. You know have two places that happen to contain the same value.

You then proceed update one of the places to contain a different value:

text = "Goodbye"

This has no effect on the other place whatsoever.

This is also isn't specific to the DOM. That's the case with variables and/or properties in general. Here are some more examples:

var a = 1;
var b = a;
a = 2;
console.log('a:', a, 'b:', b);
b = 3;
console.log('a:', a, 'b:', b);

var a = {content: 1};
var b = a.content;
a.content = 2;
console.log('a:', a, 'b:', b);
b = 3;
console.log('a:', a, 'b:', b);

The technical term for this is pass-by-value: If you assign/pass a memory location A (variable, property, etc) to memory location B, then B is assigned a copy of the value of A, not a reference or pointer to A.

See also Is JavaScript a pass-by-reference or pass-by-value language?

about 4 years ago · Juan Pablo Isaza Report

0

When you initialize your text variable at the top you’re setting its value to “Hi” (because that’s the textContent of your element) but it’s a copy of the value, completely independent of the DOM element. Changing one has no effect on the other.

So when you then update it (via text = “Goodbye”) you’re just changing the value of the variable, not the DOM element.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!