Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

143
Views
JavaScript for Loop - Error Code "item not defined"

I am a bit stuck here because I can't figure out why this does not work. When i try to run the code then it says "ReferenceError: item is not defined" - but I thought that by writing "let item" I am defining it. Any idea what the problem is here ?

  • i know the code looks a bit more complicated than necessary but i need to do it like that.
class Graph {
  constructor() {
    this.nodes = new Set();
    this.edges = new Set();
  }

  add(m,n){
   let e = new Edge (m,n)
   var allEdges = new Set();
   for (let item of this.edges){ 
     allEdges.add(item.startpoint.nodeName,item.endpoint.nodeName)
   };
   if (allEdges.has(e.startpoint.nodeName,e.endpoint.nodeName)){ 
     console.log("first OCL Constraint")
   } else if(allEdges.has(e.endpoint.nodeName,e.startpoint.nodeName){    
     console.log("second OCL Constraint")}
   else { 
     this.edges.add(item.startpoint.nodeName,item.endpoint.nodeName)};
   }
};

class Edge {
  constructor(startpoint,endpoint) {
    this.startpoint = startpoint;
    this.endpoint = endpoint;
  }
};

class Node {
  constructor(nodeName) {
    this.nodeName = nodeName
  }
};

node1 = new Node (1);
node2 = new Node (2);
node3 = new Node (3);
node4 = new Node (4);
node5 = new Node (5);
myTestGraph = new Graph();

myTestGraph.add(node1,node2);
myTestGraph.add(node2,node1);
myTestGraph.add(node3,node4);

Thanks in advance :)

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The problem seems to be in the last "else", where you reference the "item" out of its scope (you declare let item inside the for block) I think the correct code for the add() method is:

add(m,n){
   let item;
   let e = new Edge(m,n);
   var allEdges = new Set();
   for (item of this.edges){allEdges.add(item.startpoint.nodeName,item.endpoint.nodeName)};
   if (allEdges.has(e.startpoint.nodeName,e.endpoint.nodeName)){console.log("first OCL Constraint")}
   else if(allEdges.has(e.endpoint.nodeName,e.startpoint.nodeName)){console.log("second OCL Constraint")}
   else {this.edges.add(item.startpoint.nodeName,item.endpoint.nodeName)};
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!