0

I am coding an AI. It's not working. The browser is saying: Uncaught ReferenceError: do is not defined.

var what = ["jokes", "cats", "news", "weather", "sport"];

function start() {

    var do = what[Math.floor((Math.random() * what.length) + 1)];
}
start();
Document.write(do);
5
  • 2
    read about function scope in javascript (basically variables defined within function are only visible inside that function) Commented Aug 19, 2016 at 16:36
  • Like mic4ael said, this is an issue with "scopes" in Javascript. 'do' is defined within a function, and thus not available outside. If you initialized 'do' outside of the function, you'll be able to access it. Commented Aug 19, 2016 at 16:37
  • stackoverflow.com/documentation/javascript/480/… Commented Aug 19, 2016 at 16:37
  • 2
    "do" is a JavaScript reserved word. I'd suggest to use other name. Commented Aug 19, 2016 at 16:38
  • you should declare variable outsite function and what[Math.floor(Math.random() * what.length) + 1] here +1 always return empty. try what[Math.floor(Math.random() * what.length)] Commented Aug 19, 2016 at 16:46

4 Answers 4

0

You do variable is out of scope

var what = ["jokes", "cats", "news", "weather", "sport"];

function start() {

    var do = what[Math.floor((Math.random() * what.length) + 1)];
}
start();
Document.write(do);

You need to change your code to

var what = ["jokes", "cats", "news", "weather", "sport"];

function start(callback) {

    var do = what[Math.floor((Math.random() * what.length) + 1)];
    callback(do);
}
start(function(val) {document.write(val)});
Sign up to request clarification or add additional context in comments.

Comments

0
var what = ["jokes", "cats", "news", "weather", "sport"];
var do;
function start() {

    do = what[Math.floor((Math.random() * what.length) + 1)];
}
start();
Document.write(do);

Comments

0

Do is only present inside your function. Read about function scope :) Try this:

var what = ["jokes", "cats", "news", "weather", "sport"];
var do = undefined;
function start() {
    do = what[Math.floor((Math.random() * what.length) + 1)];
}
start();
Document.write(do);

Comments

0

do is a variable here and not a function.

var do = what[Math.floor((Math.random() * what.length) + 1)];

to create a do function, you would do something like this.

var what = ["jokes", "cats", "news", "weather", "sport"];
var do;
function start() {    
    do = function(){ return what[Math.floor((Math.random() * what.length) + 1)]};
}
start();
Document.write(do());

2 Comments

And how would this work? Pretty sure that's invalid JavaScript you got there: do = function() = {? And document.write(do) would write function() {...}, not the result of calling the function.
@MikeMcCaughan: some typos... and invalids.. changed...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.