Why is this function behaving differently than I expected?

Advertisements

Recently, I wrote a javascript code by referring to the Python code, but the result did not come out as expected.

Here’s the code.

const languages = ['python', 'perl', 'c', 'java'];

for (let lang of languages) {
    if(lang == "python" || "perl") {
        console.log(`${lang} need interpreter`);
    } else if (lang == "c" || "java") {
        console.log(`${lang} need compiler`);
    } else {
        console.log("Not a support language.");
    }
}

This is the python code I was referencing.

languages = ['python', 'perl', 'c', 'java']

for lang in languages:
    if lang in ['python', 'perl']:
        print("%6s need interpreter" % lang)
    elif lang in ['c', 'java']:
        print("%6s need compiler" % lang)
    else:
        print("should not reach here")

// python need interpreter
// perl need interpreter
// c need compiler
// java need compiler

I googled it but couldn’t find it. so, please help me, Thank you in advance!

>Solution :

lang == "python" || "perl"

does not do what you want. Use

lang == "python" || lang == "perl"

Leave a Reply Cancel reply