-1

I am beginner to javascript and I want to execute below program ,

let laptop = new Object();
let priceProp = "price";
laptop.name = "Lenovo";
laptop.series = "G 5080";
laptop.generation = "4th generation";
laptop["resolution"] = "4K";
laptop[priceProp] = 40000;
console.log(laptop);
console.log("Name property :- " + laptop.name);
console.log("Resolution property :- " + laptop.resolution);
console.log("Price Of a Laptop :- " + laptop.priceProp);

Here for priceProp it gives me undefined output how can I resolve that . Thanks in advance....

Output

{
    name: 'Lenovo',
    series: 'G 5080',
    generation: '4th generation',
    resolution: '4K',
    price: 40000
}
Name property :- Lenovo
Resolution property :- 4K
Price Of a Laptop :- undefined
Thakkar Darshan
  • 350
  • 1
  • 15
  • You don't need to do `new Object`. You can create an object literal and use [computed property](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#New_notations_in_ECMAScript_2015) for `priceProp` like this: `let laptop = { name: 'Lenovo', series: 'G 5080', generation: '4th generation', resolution: '4K', [priceProp]: 40000 }` – adiga Jun 16 '20 at 04:34

3 Answers3

1

Here is a more modern and "cleaner", in my opinion, version of your code for help!

const laptop = {
    name: "Lenovo",
    series: "G 5080",
    generation: "4th Generation",
    resolution: "4K",
    price: "40000"
}

console.log(laptop);
console.log(`Laptop Name: ${laptop.name}`);
console.log(`Laptop Resolution: ${laptop.resolution}`);
console.log(`Laptop Price: ${laptop.price}`);
sno2
  • 3,274
  • 11
  • 37
0

Here I made mistake in property accessing

let laptop = new Object();
let priceProp = "price";
laptop.name = "Lenovo";
laptop.series = "G 5080";
laptop.generation = "4th generation";
laptop["resolution"] = "4K";
laptop[priceProp] = "40000";
console.log(laptop);
console.log("Name property :- " + laptop.name);
console.log("Resolution property :- " + laptop.resolution);
console.log("Price Of a Laptop :- " + laptop.price);

I was accessing the priceProp variable instead of price :):)

Thakkar Darshan
  • 350
  • 1
  • 15
0

Any of these will work:

console.log("Price Of a Laptop :- " + laptop.price);
console.log("Price Of a Laptop :- " + laptop["price"]);
console.log("Price Of a Laptop :- " + laptop[priceProp]);

See one of them in action:

let laptop = new Object();
let priceProp = "price";
laptop.name = "Lenovo";
laptop.series = "G 5080";
laptop.generation = "4th generation";
laptop["resolution"] = "4K";
laptop[priceProp] = 40000;
console.log(laptop);
console.log("Name property :- " + laptop.name);
console.log("Resolution property :- " + laptop.resolution);
console.log("Price Of a Laptop :- " + laptop[priceProp]);
Rahul Bhobe
  • 4,165
  • 4
  • 17
  • 32