0

I have a an array of objects, and when I am looping over it add adding a value to a variable, the variable always has an nullin it. I know its a pretty basic question, but stuck on why it adds the null and don't know how to stop it.

(function() {
  let ds = [{
      Name: "A",
      Age: 1
    },
    {
      Name: "B",
      Age: 2
    },
    {
      Name: "C",
      Age: 3
    }
  ];
  let str = null;

  for (let i = 0; i < ds.length; i++) {
    if (ds[i].Name) {
      str += ds[i].Name + ",";
    }
  }
  console.log(str);
})();

It shows as null, A, B, C, and what I want it to show as A,B,C

2
  • 1
    Does this answer your question? JavaScript String concatenation behavior with null or undefined values Commented Jan 10, 2020 at 18:03
  • 1
    Try running null + "42". This should answer your question. Use an empty string initially, or better yet, ds.map(e => e.Name).join(",") since everything has a name or ds.filter(e => e.Name !== undefined).map(e => e.Name).join(",") if you do have undef Name keys. Commented Jan 10, 2020 at 18:06

1 Answer 1

2

The value null is stringified to "null" - ToString . if you initialize it with empty string, will work.

(function() {
  let ds = [{
      Name: "A",
      Age: 1
    },
    {
      Name: "B",
      Age: 2
    },
    {
      Name: "C",
      Age: 3
    }
  ];
  let str = "";

  for (let i = 0; i < ds.length; i++) {
    if (ds[i].Name) {
      str += ds[i].Name + ",";
    }
  }
  console.log(str);
})();

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.