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

282
Views
Javascript new keyword difference in output

Why do I get 2 different output when I run in Chrome -> DevTools -> Sources and when I run in JSFiddle.

The code which I run is as follows

function foo() {
    this.baz = "baz"
    console.log(this.bar + " " + baz);
}

var bar = "bar";
var baz = new foo();
console.log(baz.baz)

Output in chrome

undefined [object Object]
baz

Output in JSFiddle

"undefined undefined"
"baz"

Essentially chrome is telling me that baz is an object of type {baz:"baz"} but jsFiddle tells me it is undefined.

enter image description here enter image description here

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

0

Are you sure you did not run the same code on chrome twice?

The first time baz is clearly undefined, but if you paste the same code again it has the value you already defined (var baz = new foo();).

about 4 years ago · Juan Pablo Isaza Report

0

When a standard page with that code on it is run the result is undefined undefined and then baz.

Inside the function, baz refers to the outer variable named baz, which is the instance that's being created (but hasn't been created yet - it'll be created after the foo function returns the instance). So, at that moment, it should be undefined.

But, the console is not like a standard webpage; it'll save previous values assigned to variables when you run it again. You must have run the code more than once - in which case, it's like doing

function foo() {
    this.baz = "baz"
    console.log(this.bar + " " + baz);
}

var bar = "bar";
var baz = new foo();
console.log(baz.baz)

// you probably cleared the console manually at this point
// before running it again

function foo() {
    this.baz = "baz"
    console.log(this.bar + " " + baz);
}

var bar = "bar";
var baz = new foo();
console.log(baz.baz)

so the [object Object] you see is from a previous run's instance.

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!