Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Loops, Arrays and Objects Tracking Data Using Objects Accessing Object Properties

Siddharth Pande
Siddharth Pande
9,046 Points

objects in javascript

what is the difference between:

var person = {
 name: "xyz",
 age: 23
}

and

const person = {
 name: "XYZ",
 age: 23
}

2 Answers

Steven Parker
Steven Parker
210,423 Points

Besides the name being uppercase in one and lowercase in the other, the main difference is the one declared with "var" has function scope and can be re-assigned later if desired.

The one declared with "const" has block scope and it cannot be reassigned (though the properties of the object can be changed).

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,676 Points

This is an interesting thing in JavaScript. If you make an object const, it means that you can’t reassign that object to another object. But you can still overwrite properties of that object. Here’s an example.

const person = {
 name: "XYZ",
 age: 23
}

const person = { someKey: someValue } 
// Uncaught TypeError: Assignment to constant variable.

person.name = ABC

// person is now { name: “ABC”, age: 23 }

If you REALLY want person to stay constant, not just the object but all of its keys and values, you can use Object.freeze()

Object.freeze(person)
person.name = Brendan

// It doesn’t throw an error, but person.name is still “ABC”
Siddharth Pande
Siddharth Pande
9,046 Points

does Java use a similar analogy for objects?

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,676 Points

Java is similar. You can make an object a constant with the final keyword. But you can still change the properties of that object. I don't know if there's something like Object.freeze() in Java, I think you might have to declare properties final inside the class of that object from inside its class definition rather than from the outside.