0

Faulty Code

import tttt_data from "@/data/tttt.json";


export class TTT {

    getTTT() {
        return tttt_data.dersler;
    }

    getTTT(lesson) {
        return tttt_data.dersler[lesson];
    }

    getTTT(lesson, subject) {
        return tttt_data.dersler[lesson][subject];
    }
}

Error Code in Console

 getTTT(lesson, subject) {
> 15 |         return tttt_data.dersler[lesson][subject];
     |                                         ^       
  16 |     }
  17 | }

Starting Code

  const tttt = new TTT();
  const dersler = Object.keys(tttt.getTTTT());
  console.log(dersler);

When I not give an argument to the function, I want it to run without arguments. but the argument awaits. It does not work like in Java.

1
  • How should the methods know what lesson key to use if you don't pass it? Commented Jun 20, 2024 at 15:20

1 Answer 1

2

Javascript is not Java. It does not have function overloading. Instead functions may be called with more or fewer arguments than declared.

For example:

function x (a) {
    return `it is ${a}`;
}


x(); // this is leagal and will return `it is undefined`
x('hello'); // also legal
x('hello', 'world'); // also legal

What you want instead is to check if the arguments are passed to the function:

export class TTT {
    getTTT(lesson, subject) {
        if (lesson === undefined && subject === undefined) {
            return tttt_data.dersler;
        }
        else if (subject === undefined) {
            return tttt_data.dersler[lesson];
        }
        else {
            return tttt_data.dersler[lesson][subject];
        }
    }
}

alternatively you can use the built-in arguments keyword:

export class TTT {
    getTTT() {
        switch (arguments.length) {
            case 0:
                return tttt_data.dersler;
            case 1:
                return tttt_data.dersler[arguments[0]];
            case 2:
                return tttt_data.dersler[arguments[0]][arguments[1]];
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.