-1

I was taking a Udemy course, here is my code for an exercise that I was doing. Faker is a package downloaded from the NPM library

var faker = require("faker");

console.log("+++++++++++++++++++");
console.log("Welcome to my shop!");
console.log("+++++++++++++++++++");
var data = faker.commerce.productName();

data.forEach(function(print){
    console.log(data);
});

I was expecting the code to iterate over every item in the variable "data" and print the result, however this is the result I get

+++++++++++++++++++
Welcome to my shop!
+++++++++++++++++++
/home/ubuntu/workspace/node_practice/demo_app/app.js:8
data.forEach(function(print){
     ^

TypeError: data.forEach is not a function
    at Object.<anonymous> (/home/ubuntu/workspace/node_practice/demo_app/app.js:8:6)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:504:3

I am using Cloud9 ide, why am I getting this error?

Robert Mennell
  • 1,954
  • 11
  • 24
Rudhraksh
  • 27
  • 5

1 Answers1

1

You should read the faker documentation.

https://cdn.rawgit.com/Marak/faker.js/master/examples/browser/index.html#commerce

faker.commerce.productName() is a string. Those don't have a prototype.forEach()

If you'd like to generate a set of names you can use Array.from() with faker like so:

let products = Array
  .from({length: 100})
  .map(faker.commerce.productName)

You now have an Array of 100 product name

Robert Mennell
  • 1,954
  • 11
  • 24