Click here to Skip to main content
15,886,788 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am learning JavaScript. And this is an object that has two properties; 'color' & 'machine' and one method named 'particulars'

JavaScript
Car = {
  color: 'Red',
  machine: 12,
  particulars: function() {
   return console.log(this.color);
   return  console.log(this.machine);
  }
}
Car.particulars();

Actually, I want to remove the 'undefined' value that comes in the output of this code when you run the above code, without the return statements.

What I have tried:

I have added two return statements against each console log, as it came into my learning that when you explicitly return anything from a function then it will return that thing otherwise in JavaScript, it will give you undefined as a value as its implicit or default behavior but here it doesn't prints the value for machine property just color.
I want to run this code that it prints both the values of color and machine with no undefined to be seen in the output

Thank you!!
Posted
Updated 18-Jul-23 6:26am
Comments
[no name] 1-Jun-23 15:14pm    
For starters, you can "never" have 2 or more "unconditional" returns; only the first ever gets executed.
Member 15627495 2-Jun-23 2:48am    
as you tag your topic OOP, use the 'Class' statement for your car Class.
add one or more constructors , 'getters' and 'setters' too.

as it is, your code is missing few lines.

class car = {
  constructor(){
    this.color = 'Red';
    this.machine = 12;
  }

  function particulars(){

   console.log(this.color);
   console.log(this.machine);

  }
}

var audi = new car();
audi.particulars();



JS is low typed, and that grant coders to go through all types very easily.
Integers can be fetch as an array, or as a string with indexes.

coders can write 'mixed arrays' combining datas, functions, objects with self vars in.
the code you write is not a 'Class' as await, but you write a 'mixed array'.

It's not a fault, by the JS reliability between types, you can go far with 'mixed arrays', it's a really powerful use.
and that works well !
Member 10601191 18-Jul-23 8:49am    
@Richard Deeming,have removed my entry. afaics the user is using a class function, but always happy to learn when mistaken.

1 solution

try the following.

JavaScript
Car = {
  color: 'Red',
  machine: 12,
  particulars: function() {
   return console.log(this.color, this.machine);
  }
}
Car.particulars();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900