admin管理员组

文章数量:1384197

I'm learning JS on Codecademy and I'm stuck in the "switch" element part.

The instructions are: "Create your own switch statement in the editor. It can do anything you like! Make sure to include at least three cases and a default."

I always get "TypeError: undefined is not a function" I'm sure it's something dumb but I can't figure it out and I tried searching but no luck either.

And here's my code:

// Write your code below!
var console = prompt("What's your favorite console?");
switch(console) {
    case "PS4":
        console.log("It's my favorite too!");
        break;
    case 'Xone':
        console.log("Good choice!");
        break;
    case 'Wii':
        console.log("I don't really like it.");
        break;
    default:
        console.log("That's not a current gen console!");
};

I'm learning JS on Codecademy and I'm stuck in the "switch" element part.

The instructions are: "Create your own switch statement in the editor. It can do anything you like! Make sure to include at least three cases and a default."

I always get "TypeError: undefined is not a function" I'm sure it's something dumb but I can't figure it out and I tried searching but no luck either.

And here's my code:

// Write your code below!
var console = prompt("What's your favorite console?");
switch(console) {
    case "PS4":
        console.log("It's my favorite too!");
        break;
    case 'Xone':
        console.log("Good choice!");
        break;
    case 'Wii':
        console.log("I don't really like it.");
        break;
    default:
        console.log("That's not a current gen console!");
};

Share Improve this question asked Mar 16, 2015 at 21:28 SamSam 2551 gold badge5 silver badges15 bronze badges 1
  • 2 Use another variable name than console. You're whacking the default object console (that had the log method). – bloodyKnuckles Commented Mar 16, 2015 at 21:30
Add a ment  | 

3 Answers 3

Reset to default 2

You're redefining console in the first line.

console is used to, for example, print messages. The solution to your problem is to rename:

var console = ...

to a different name:

var choice = ...

Hope this helps!

The problem is you change the value of console. Then console.log returns the error. Rename the variable please...

"console" is an existing global variable in the JavaScript interpreter of every mainstream web browser. It basically refers to the browser "mand window" that can be opened with, for example, F12 in Firefox and Chrome. If you overwrite it, as you do in your original code, you'll lose access to that important object, which is not desirable in most cases. So avoid naming your own variables "console". Other variable names to avoid are "window", "Object", etc.

本文标签: javascriptquotTypeError undefined is not a functionquotStack Overflow