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 trialSiddharth Pande
9,046 Pointsobjects in javascript
what is the difference between:
var person = {
name: "xyz",
age: 23
}
and
const person = {
name: "XYZ",
age: 23
}
2 Answers
Steven Parker
231,236 PointsBesides 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
Front End Web Development Techdegree Graduate 84,738 PointsThis 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
9,046 Pointsdoes Java use a similar analogy for objects?
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsJava 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.