user4115586
user4115586

Reputation:

Beginner JavaScript - Car Colors

"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";
}

Upvotes: 0

Views: 754

Answers (3)

Grant Miller
Grant Miller

Reputation: 29037

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'));

Upvotes: 1

brk
brk

Reputation: 50326

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 . '

Upvotes: 0

amg-argh
amg-argh

Reputation: 196

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";
}

Upvotes: 0

Related Questions