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);
Tosbs
  • 3
  • 2
  • 2
    read about function scope in javascript (basically variables defined within function are only visible inside that function) – mic4ael Aug 19 '16 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. – Alex Johnson Aug 19 '16 at 16:37
  • http://stackoverflow.com/documentation/javascript/480/scope#t=201608182147440316607 – Heretic Monkey Aug 19 '16 at 16:37
  • 2
    "do" is a JavaScript reserved word. I'd suggest to use other name. – Danny Fardy Jhonston Bermúdez Aug 19 '16 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)]` – sagivasan Aug 19 '16 at 16:46

4 Answers4

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);
Akshay
  • 815
  • 7
  • 16
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());
Thalaivar
  • 23,282
  • 5
  • 60
  • 71
  • 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. – Heretic Monkey Aug 19 '16 at 16:40
  • @MikeMcCaughan: some typos... and invalids.. changed... – Thalaivar Aug 19 '16 at 16:43
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);
philmtd
  • 65
  • 1
  • 6
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)});
randominstanceOfLivingThing
  • 16,873
  • 13
  • 49
  • 72