0

"Modify the car-painting example so that the car is painted with your favorite color if you have one; otherwise it is painted w/ the color of your garage (if the color is known); otherwise it is painted red." Car-painting example: car.color = favoriteColor || "black";

How or what do I need to do to make my script work?

car.color = favoriteColor || "red";
if (car.color = favoriteColor ){ 
    alert("your car is " + favoriteColor);

} else if (car.color = garageColor){
    alert("your car is " + garageColor);

} else {
    car.color = "red";
}
usuallystuck
  • 165
  • 2
  • 11

3 Answers3

1

This is the correct answer to your question:

See my comments to get a better understanding of how this works.

if (favoriteColor) {
  car.color = favoriteColor; // If you have a favorite color, choose the favorite color.
} else if (garageColor) {
  car.color = garageColor;   // If the garage color is known, choose the garage color.
} else {
  car.color = 'red';         // Otherwise, choose the color 'red'.
}

alert('Your car is: ' + car.color);

Try it Online!

Related Question (for further insight):

https://softwareengineering.stackexchange.com/q/289475

Alternative Method:

As another possibility, you can write a conditional (ternary) operation to compact all of the logic into a single statement.

alert('Your car is: ' + (car.color = favoriteColor ? favoriteColor : garageColor ? garageColor : 'red'));
Grant Miller
  • 27,532
  • 16
  • 147
  • 165
0

It just looks like you need to use double equals signs in your if statement. Use == when checking for equality. Try this:

car.color = favoriteColor || "red";
if (car.color == favoriteColor ){ 
    alert("your car is " + favoriteColor);

} else if (car.color == garageColor){
    alert("your car is " + garageColor);

} else {
    car.color = "red";
}
amg-argh
  • 196
  • 5
0

Hope this code will be useful

function _showFavColor(getColor){
 var favoriteColor = 'red';
 var garageColor  ="blue";   
 var carColor = getColor;

if (carColor == favoriteColor ){ 
    alert("your car is " + favoriteColor);

} else if (carColor == garageColor){
    alert("your car is " + garageColor);

} else {
    carColor = "red";
}
}
_showFavColor('red');
_showFavColor('blue');

jsfiddle

Also take a note on how eqality check is done in js. You can follow this links or google it Which equals operator (== vs ===) should be used in JavaScript comparisons?.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness

Also if you use car.color and if dont create the car object it will throw an error

 'Uncaught SyntaxError: Unexpected token . '
Community
  • 1
  • 1
brk
  • 48,835
  • 10
  • 56
  • 78