0

I have such variable declaration in my JavaScript method on :

var MyVariable = {
    CarMake: "Lexus",
    CarColor: "Black"
}

What I am trying to accomplish is to add some login within MyVariable declaration such as:

    var MyVariable = {
    CarMake: "Lexus",
    if (carType == "sedan") {
        NumberOfDoors: 4,
    }
    CarColor: "Black"
}

Is this possible somehow?

4 Answers 4

2

With a one-line object you can't do it. You need to assign it later. But I thnik you can create a class(ES6) and use like

class Car{
  constructor(maker, color, type){
      this.maker = maker;
      this.color = color;
      if(type === 'sedan'){
        this.numberOfDoors = 4;  
      }
  }
}

var car = new Car('Lexus','Black','sedan');
console.log(car.numberOfDoors);

Or use the function syntax

    function Car(maker, color, type){    
          this.maker = maker;
          this.color = color;
          if(type === 'sedan'){
            this.numberOfDoors = 4;  
          }   
    }

    var car = new Car('Lexus','Black','sedan');
    console.log(car.numberOfDoors);

Sign up to request clarification or add additional context in comments.

Comments

2

I suppose you could do

var MyVariable = {
  CarMake: "Lexus",
  CarColor: "Black",
  NumberOfDoors: (carType === 'sedan') ? 4 : undefined
}

which is not exactly the same, but close.


But how about

var MyVariable = {
  CarMake: "Lexus",
  CarColor: "Black"
}

if (carType === 'sedan') {
    MyVariable.NumberOfDoors = 4
}

You could wrap this into a "factory" function and then do

var MyVariable = makeCar("Lexus", "Black", "sedan") 

Comments

1

One way you could do this:

var MyVariable = {
    CarMake: "Lexus",
    CarColor: "Black"
}

if (carType == "sedan") {
    MyVariable.NumberOfDoors = 4;
}

Comments

1

You need to create your variable before and add the new attribute after :

var MyVariable = {
   CarMake: "Lexus",
   CarColor: "Black"
}

if (carType == "sedan") {
    MyVariable.NumberOfDoors = 4
}

1 Comment

I think there is syntax issue here. The colon within if-statement should be replaced with equal sign to make if a statement if I am not mistaken. Anyway, good idea. Thanks for your response!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.