0

I just started learning to program and I am watching a tutorial online and do not understand how he is using loops.

This is his example and works

<!DOCTYPE html>
<html>
<head>
  <title> Random </title>
  <link rel="stylesheet" href="style.css"/>
</head>
<body>
  <div class="container">
  </div>
  <script>
   var numbers = [33,54,76,34,2,6];
   numbers.forEach(function(number){
           document.write(number);
});

  </script>
</body>
</html>

This is mine and doesn't work

<!DOCTYPE html>
<html>
<head>
  <title> Random </title>
  <link rel="stylesheet" href="style.css"/>
</head>
<body>
  <div class="container">
  </div>
  <script>
   var foods = [pie,cake,brownie];
   foods.forEach(function(string){
    document.write(string);
});


  </script>
</body>
</html>

I have tried replacing the string value in the parenthesis with number but that doesn't work. In the correct code he uses the variable number even though the defined variable is numbers can someone please explain.

1
  • 1
    When programming JavaScript in a browser it is always a good idea to take a look at the JavaScript console window of your browser. There should appear an error like "Uncaught ReferenceError: pie is not defined". Commented Mar 22, 2017 at 18:15

2 Answers 2

4

Your issue is pie, cake, and brownie aren't in quotations.

All strings must be surrounded by either single quotes, or double quotes.

Try:

var foods = ["pie", "cake", "brownie"];
foods.forEach(function(str)) {
  document.write(str);
});

Right now, your script will interpret them as variable names. None of those variables are defined, which is why you aren't getting the output you expect.

Sign up to request clarification or add additional context in comments.

Comments

3

Put your string values in ' characters - that is:

var foods = ['pie','cake','brownie'];

On a side note using " instead of ' characters works as well.

here's a fixed version of your code on plunker

here's some information about data types in javascript

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.