Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
169
rated 0 times [  176] [ 7]  / answers: 1 / hits: 36172  / 9 Years ago, sun, november 15, 2015, 12:00:00

I am playing around with JavaScript and AngularJS since a few days and I am not sure about the following:



I am working on a sample project in which a user is able to create a new car with just a few properties stored in an JS object like this:



var car = {
color: 'black',
seating: 'leather',
fuelconsumption: 'moderate'
}


The user can create a new car by clicking on an add-button. Angular then creates a new instance of a car and the user can specify the wishes for new car.



However, should I create an empty object like



var car = {}


and add the needed keys using the bound text inputs or should I do something different?



Since the properties of a new car are known a-priori I could also create an object with the needed keys and null as their values like this:



var car = {
color: null,
seating: null,
fuelconsumption: null
}


Which way would be more preferable due to e.g. best-practise?


More From » angularjs

 Answers
13

In Javascript, there is often not a need to initialize a property to null. This is because referencing a property that has not been initialized just harmlessly returns undefined which can work just as well as null. This is obviously different than some other languages (Java, C++) where properties of an object must be declared before you can reference them in any way.



What I would think might make sense in your case is to create a constructor function for creating a car object because you will presumably be creating more than one car and all possible car objects won't be known at the time you write the code. So, you create a constructor function like this:



function Car(color, seating, fuel) {
this.color = color;
this.seating = seating;
this.fuelConsumption = fuel;
}


Then, you can create a new Car object like this:



var c = new Car('black', 'leather', 'moderate');
console.log(c.color); // 'black'

[#64391] Thursday, November 12, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaley

Total Points: 141
Total Questions: 109
Total Answers: 109

Location: Burundi
Member since Sat, Aug 21, 2021
3 Years ago
;