Why it is output undifined?

Issue

So, I making toy-programming language on JS
and I met one trouble…
namely in labels. According to my idea, everything that comes after the label is entered into the object and later runs when necessary
code:

var OBJcode = {}
labels = {}
code = `zhopa: i am string
i am string
i am string
i am string`
CodeLine = code.split("\n")
for (var i = 0; i < CodeLine.length; i++) {
  runCode = CodeLine[i].split(" ")
  OBJcode[i] = runCode

  label = runCode[0]
  instruction = CodeLine[1]
  src = runCode[2]
  dst = runCode[3]
  if (`${dst}` == "undefined") {
    dst = src
    src = instruction
    instruction = label
  }
  if (label.endsWith(":")) labels[label.slice(0, -1)] += CodeLine[i + 1].split(" ").join(" ")
}
console.log(code)
console.log(OBJcode)
console.log(labels)

output:

zhopa: i am string
i am string
i am string
i am string {
  '0': ['zhopa:', 'i', 'am', 'string'],
  '1': ['i', 'am', 'string'],
  '2': ['i', 'am', 'string'],
  '3': ['i', 'am', 'string']
} {
  zhopa: 'undefinedi am string'
}

And how to add next lines to labels[label]?

most likely the problem is at 21:56

Solution

The first time you do

labels[label.slice(0, -1)] += CodeLine[i + 1].split(" ").join(" ")

the labels object is empty, so labels[label.slice(0, -1)] is undefined. When you concatenate to this, it converts the undefined value to the string "undefined", and then CodeLine[i + 1].split(" ").join(" ") is appended to this. So you get undefined at the beginning of the result.

You need to check if the object property exists or not before concatenating.

var OBJcode = {}
labels = {}
code = `zhopa: i am string
i am string
i am string
i am string`
CodeLine = code.split("\n")
for (var i = 0; i < CodeLine.length; i++) {
  runCode = CodeLine[i].split(" ")
  OBJcode[i] = runCode

  label = runCode[0]
  instruction = CodeLine[1]
  src = runCode[2]
  dst = runCode[3]
  if (`${dst}` == "undefined") {
    dst = src
    src = instruction
    instruction = label
  }
  if (label.endsWith(":")) {
    let key = label.slice(0, -1);
    let value = CodeLine[i + 1].split(" ").join(" ");
    if (labels[key]) {
      labels[key] += value;
    } else {
      labels[key] = value;
    }
  }
}
console.log(code)
console.log(OBJcode)
console.log(labels)

Answered By – Barmar

Answer Checked By – Candace Johnson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.