<h1>I wouldn't.</h1>
<p>Based on my experiences as a student teacher in the Australian education system, typically actual coding doesn't get taught until grades 9-10, at which point the language is typically Python because of its relatively simple syntax.</p>
<p>At the age range you're discussing, students are typically taught a visual block programming language like <a href="https://en.wikipedia.org/wiki/Scratch_%28programming_language%29" rel="nofollow noreferrer">Scratch</a> in one unit (year or semester, depending on how the school's structured their IT course), to teach them about the programming thinking (loops, Boolean logic, etc) without worrying about correct syntax, and then taught HTML and CSS in the following unit to teach them about the importance of syntax and to get them used to typing code into a computer.</p>

CC BY-SA 4.0
2019-12-22T02:50:09.460Z
Thanks. Actually, that is the path we have followed. We started with Scratch and have moved on to HTML and CSS. Now we are adding just a couple of JS tools to introduce them to JS (we have actually changed our curriculum to start JS in Minecraft Education Edition but these students have missed that). Since they have those basic concepts in place (sequences, loops, conditionals/logic, variables, etc.), we started with alerts and prompts in JavaScript. I wanted to make it a little more fun with the quiz game so I added this "function."
Bill Pratt
CC BY-SA 4.0
2019-12-21T09:38:03.777Z
2019-12-21T09:38:03.777Z
2020-06-18T08:36:57.023Z
nick012000
<p>To answer your question directly, I think it would make sense to teach the students the more complicated looping structure first, so that they maintain a good sense of what clean code looks like. Unless, of course, you're going to teach them looping later on in the same lesson and want to use this as an example of bad code, but if you're just introducing them to programming, giving bad examples right of the bad likely isn't the best way to do it.</p>

<hr>

<p>In the larger sense, I think you're approaching this lesson wrong.</p>

<p>First of all, I tend to recommend not including syntactic sugar when introducing programming for the first time, because that requires the student to understand more then they really need to. I mention this because I see you using features such as <code>foo -= bar</code> instead of <code>foo = foo - bar</code> and <code>foo === bar</code> (because the difference between <code>===</code> and <code>==</code> should be taught later on).</p>

<p>Second, you're introducing a whole lot at once. To understand the code snippets you've given, the students will need to first understand <code>if</code> / <code>else</code> statements, blocks, mutable variables, general language syntax, typing, string concatenation, and variables at the least. And most importantly, functions! Functions are very nontrivial for someone who hasn't seen programming before. You really ought to break down this lesson into the smaller pieces first, and then, once your students are able to grasp those pieces, then they can put it together into a larger project like the one you've described. But, at that point, they should already know what loops and how they work, so you won't even have this question :)</p>

<p><strong>TL;DR</strong> Re-evaluate your approach to teaching this lesson. Break down the topic into smaller building blocks and teach those smaller building blocks first.</p>

<p>Good luck with the lesson!</p>

CC BY-SA 4.0
2019-12-21T21:21:28.973Z
2019-12-21T21:21:28.973Z
thesecretmaster
<p>I apologize in advance, but I'm going to be a bit hard on you. </p>

<p>First, your goal of keeping it simple is a good one that I applaud. You are right, IMO, not to bring in advanced features too early. </p>

<p>However, this is not the sort of code I would show to a beginner. Ever. It is the kind of code that, if submitted by an early teen would be fine, but not the sort of code that a teacher should show, lest it be emulated. If this were submitted by a college first year student, as part of some project, it would be severely downgraded. </p>

<p>I think students should only ever be shown code, from instructors, that they would be proud to emulate. But I think the lessons taught in this code need to be unlearned before the student can gain a proper understanding of how to program. I would use some completely different example, even if I was only interested in syntax, which I don't think you should be. You can also teach deeper lessons, just by example, by choosing what code you present to students. </p>

<p>Let me list a bunch of criticisms of the code, that are easily corrected, but using a different framework possibly. </p>

<p>First, the function names aren't descriptive in any way of what the function does. Also, they aren't functions in the classic sense since they return nothing, but that is just an issue with how javascript is built. They are procedures (actually <em>commands</em> since they don't have arguments either). But "intention revealing names" are a really good idea so everyone should use them, and novices should see them. So, <em>askCirculatoryQuestion</em> is preferable to askQuestion1. </p>

<p>Next, the formatting is a bit sloppy. A minor issue, but, if you are only a bit sloppy it won't be easy to teach them not to be. </p>

<p>Next, your var should probably be a const. There is no intention to change it. (Note: I'm not a javascript wizard, so I hope this is possible in this context.)</p>

<p>Next, you use an identity comparison, so, in the first function neither "the circulatory" nor "circulatory system" would be accepted. This is a human factors issue and may be the main objection to the example overall. An example without such an issue could probably be easily devised. But code that frustrates uses is not what you should show beginning students. But parsing user input is a genuinely difficult problem, of course. </p>

<p>Next, you make assignment here to a global variable, which is a tool that shouldn't be in the beginner's toolbox. It is an advanced incantation suitable only for trained wizards. Such practice makes larger programs much harder to understand and debug. Even wizards use this "spell" sparingly. </p>

<p>Finally, blasting alerts from a function is likely to mislead them when you try to teach real functions (that return values). Too many students have a very hard time with the notion of "return", and think that blasting out the answer is the correct way to write a function. You are laying a trap here that can cause issues later. (Confession: I once had that misconception. It made it difficult to understand program flow.)</p>

<p>Overall, my suggestion is to show students only the sort of code you'd like to see from them, not just now, but in the future. Yes, keep it simple and yes, keep it motivating, but make it poetry. </p>

<p>The code you will get from them is probably going to be worse than the code you give to them. So, always show them something they can emulate and that any teacher would be proud to see from a student. Make it easy for them to build good habits from the start. </p>

<p>But note that your concerns are not the same as mine. I agree that it is too early at the start to stress things like the "say it once" principle and such. And an exercise in which you have them write the analog of your second function after giving them the first wouldn't be a bad idea. It reinforces some skills, which is a good thing. </p>

<p>Again, sorry to be so hard on you. </p>

<p>But lest I be entirely negative, let me also give an idea for something similar that works on more levels than syntax. I'll stick with functions and if-else as the primary lesson. </p>

<p>Show the students a function <em>maxOfTwo</em>, that returns the maximum of two arguments. The function doesn't "alert" but, instead returns the value. Then write a driver to test it and have the students execute that a few times. Note that the function needs no local values. </p>

<p>After that, work out with the students a <em>maxOfThree</em>, that has three arguments. Do this one two ways. First with nested if statements and again by employing maxOfTwo instead. Don't give this as an assignment, but work out the logic with them and then write the (poetic) code. You may want to introduce a local value, so it is a bit more sophisticated on two levels (locals and nesting). But using <em>maxOfTwo</em> twice is a truly beautiful solution that shows the power of abstraction and reduces complexity. </p>

<p>Then, you can assign <em>medianOfThree</em> to them to work on. I suggest that it might be worthwhile to have them work out the logic of it in small groups and then come up with the code. They can either write out the code individually (probably a good thing) or in their group. Then critique the code as I have done here. </p>

<hr>

<p>And don't lose track of the point that writing functions is more about <em>abstraction</em> than anything else. It makes programs easier to understand. The only code hidden by the <em>maxOfTwo</em> function is a single if-else statement. But calling the function (assuming it has a good name) makes the intent of the program immediately clear at that point, where the expanded if statement does not. This, I think, is much more important than the ability to call the function from more than one place and know that the effect is the same. Note that obfuscated code still runs correctly, but it is the understanding that separates the programmer from the machine. So, always use <em>intention revealing names</em>. </p>

CC BY-SA 4.0
2019-12-20T14:22:21.800Z
Advice is always good as I am not a pro so criticism welcomed. 

There is a lot of background not in my original post with what the students have already studied. They have learned block-based coding (Scratch) and this "function" relates to previous blocks and concepts learned in Scratch. It isn't perfect but is intended to extend the previous learning while learning a small bit of JavaScript. They have also spent a semester learning some basic HTML/CSS. We use a platform called Trinket.io as our sandbox. It has limitations but is decent.

By the way, I like idea of making code "poetry."
Bill Pratt
CC BY-SA 4.0
2019-12-20T19:17:05.850Z
If you are purely looking at introducing JavaScript the language on its own, I think this is great advice, and in general outlines standardized approaches to single language instruction. However, in this instance, I think it is important to consider that Bill is introducing JavaScript as another step in building a minimal web application. The introduction of JavaScript should be considered with a holistic view of the current project. Converting to the classical approach of using method best practice would possibly be confusing at that point to these students who are 12-14 years old.
Travis J
CC BY-SA 4.0
2019-12-20T22:24:18.553Z
@Buffy Can you expand on the "intention revealing names"? I thought that askQuestion, answer, and score would be good names since that is what they are doing. "askQuestion1()" deals with the first question and asks it. The "answer" is the answer that the user enters and the "score" is their points after answering the question. I want to understand better myself as I am self-taught and want to learn best practices.
Bill Pratt
CC BY-SA 4.0
2019-12-20T22:40:27.340Z
The function names are my main issue. The others are fine. The function names here have no semantic meaning. What is the semantic difference between the two question names? AskCirculatoryQuestion has semantic meaning.
Buffy
CC BY-SA 4.0
2019-12-20T23:05:24.447Z
@Buffy I see what you are saying now. Thanks.
Bill Pratt
CC BY-SA 4.0
2019-12-22T15:21:42.513Z
Some refactoring wouldn't hurt either -- that's a lot of copy/pasting.
Dan Mašek
CC BY-SA 4.0
2019-12-22T17:24:22.047Z
@Buffy While I agree that simple and pure functions like `maxOfTwo` or `medianOfThree` are better for learning features and syntax, having some "driver code" is equally important, showing a concrete use case where the functions are going to be called, like in the score computation of the quiz game. Being able to try out the effects of the their coding in an example application is good for motivation, even more important for younger kids.
Bergi
CC BY-SA 4.0
2019-12-22T17:27:45.730Z
@DanMašek The copy-pasting is intentional - the abstractions features necessary to reduce the duplication were not yet introduced in the lesson. (Although functions themselves are the ultimate reusability abstraction, so they could help a bit here). However I agree that repeating the code 10 times (as suggested in the OP) is definitely too much. One or two repetitions should be enough.
Bergi
CC BY-SA 4.0
2019-12-22T17:41:01.927Z
@Bergi I'd say there's still opportunities, even if all they know is parameter-less functions and variables. The score offset could be made a variable instead of writing the constant in two places. Total score could be displayed in a separate function. Although ideally, an different scenario/example would probably be more fitting, one where the different functions do different things.
Dan Mašek
CC BY-SA 4.0
2019-12-22T17:53:27.637Z
@Bergi, actually I assumed the functions would be presented in a wider context in which the names make sense.
Buffy
CC BY-SA 4.0
2019-12-20T01:31:53.463Z
2019-12-21T15:17:46.853Z
2019-12-21T15:17:46.853Z
Buffy
<p>Middle school is a great place to start teaching kids programming, and especially JavaScript. I have guest taught something similar for third graders, and it went so much better than I had expected.</p>

<p>Code structure is not important for introductions. Engagement is the most important aspect for kids, and building a game is a great way to do that.</p>

<p>At the beginner level, having them just take something, and place it in is gold. I tend to prefer having students transcribe at that level, where they are given a printout and then are walked through adding the code themselves (maybe this is what you had planned, or similar).</p>

<p>I don't really see the need for repetition at all here though, because it doesn't really benefit them much as written. What I would suggest would be to allow them to come up with their own question2, their own accepted answer, and their own score bonus. This will allow them to not only better understand which inputs correlate with which outputs or behaviors, but will also introduce a good amount of fun to the activity. </p>

<p>Introducing fun, especially at the end of an activity once the main goal was accomplished, is a great way to build engagement. Never underestimate the value of joy :)</p>

CC BY-SA 4.0
2019-12-19T18:54:01.710Z
2019-12-19T18:54:01.710Z
Travis J
<p>I think if you're teaching anyone something like programming, you should show them the elements in isolation first, and then combine them once they seem to have a grasp of what you taught them. (software's great for this, since a "statement" is a pretty generic concept)</p>

<p>I'm assuming you mean "function" in the sense of a callable function which runs a block of code and returns.</p>

<p>I think you should focus on re-usability when showing what functions are/how they work. When I was learning, the thing that got them planted in my head firmly is that you can just write some huge block of code once and get it to run at any point later with a single line.</p>

<p>I think a better example of a function would take an argument, and perform some action based on that argument.
e.g. a <code>greet(name)</code> function which prints out <code>Hello $name! Your name is $num letters long.</code> when called.</p>

<p>You could then show the function being called multiple times, with the results depending on what's passed into the function. (e.g. hard-code the string in one invocation, and pass the response from <code>prompt()</code> in another.)</p>

CC BY-SA 4.0
2019-12-20T12:07:32.453Z
2019-12-20T12:07:32.453Z
bobsburner
<p>I am teaching middle school kids (aged 11-13) some basic JavaScript and want to get some "professional" opinions.</p>

<p>I am introducing JavaScript with a simple function with a variable, a prompt, if/else, and a couple of alerts. This function (14 lines total) then repeats a series of times (say 10 times) changing the prompt and the conditional in the if/else for a total of say 140 lines. Otherwise the function remains the same. In the lesson, we will be using trinket.io to run the code in browser, and I am able to give them a partially complete piece of code to work from.</p>

<p>I know best programming is to not repeat when you can use additional variables and arguments passed through functions. I am doing that programming with a more advanced class.</p>

<p><strong>My question is this:</strong> If just introducing JavaScript and wanting to teach syntax of these basic features, is it better to have students do the repeating (that works but is not programmatically the best way to program) or is it better to teach them the "correct" way where the program is simplified but includes more code understanding than we are ready to introduce?</p>

<p>Here is the code (I repeated it once to show the differences).</p>

<pre><code>function askQuestion1()
{
  var answer = prompt ("What body system contains the heart, blood, arteries, and veins?") .toLowerCase();
   if (answer==="circulatory") {
    alert ("Correct!");
     score += 100;
     alert ("Your total score is now " +score);
  }
  else {
    alert ("Sorry, incorrect.");
     score -= 100;
     alert ("Your total score is now " +score);
  }
}
function askQuestion2()
{
  var answer = prompt ("What body system contains the brain, spinal cord, and nerves?") .toLowerCase();
 if (answer==="nervous") {
   alert ("Correct!");
    score += 200;
    alert ("Your total score is now " +score);
  }
  else {
    alert ("Sorry, incorrect.");
    score -= 200;
    alert ("Your total score is now " +score);
  }
}
</code></pre>

CC BY-SA 4.0
2019-12-19T18:29:46.913Z
Can you please include their expected education level for JavaScript and html? I am assuming that this is being run from the browser due to the use of prompt and alert, is that true?
Travis J
CC BY-SA 4.0
2019-12-19T18:41:08.417Z
@TravisJ This is all they are expected to know for this lesson. They have built an HTML page with a Jeopardy! type game using tables and the button calls this function with an onclick="" This level of class is being introduced to functions, variables, alerts, prompts, and if/else (the score formula and += and -= are only added because what good is a game without points).
Bill Pratt
CC BY-SA 4.0
2019-12-19T18:44:00.943Z
Thanks, the background makes a lot of difference for how to approach the subject.
Travis J
CC BY-SA 4.0
2019-12-19T20:44:09.273Z
Sorry, but I don't understand. Is the alternative to include a loop in a single "function"?
Buffy
CC BY-SA 4.0
2019-12-19T21:08:42.073Z
@Buffy - The correct way would be to create a producer of these questions, and then instantiate the set of question instances for use. That is way too over the top for this situation.
Travis J
CC BY-SA 4.0
2019-12-20T14:11:56.953Z
@Buffy I used the following for an advanced group:
```
let values = {
  question1: {
    btnID: 'btn1',
    questionText: "What body system contains the heart, blood, arteries, and veins?",
    correctValue: "circulatory",
    pic: 'btn1pic',
    questionValue: 100,
  },
```
```
function askQuestion(question)
{
  var answer = prompt(question.questionText);
   if (answer && answer.toLowerCase() === question.correctValue) {
    alert ("Correct!");
     score += question.questionValue;
  }
  else {
    alert ("Sorry, incorrect.");
     score -= question.questionValue;
  }
}
Bill Pratt
CC BY-SA 4.0
2019-12-20T14:34:24.503Z
I think that means you could avoid the alerts and maybe the prompts with something you write yourself to take input from a text field and write somewhere suitable in the html. That code would be pretty simple to understand yet safe to ignore at this point.
JollyJoker
CC BY-SA 4.0
2019-12-20T22:02:41.787Z
In early high school (age 15-16) we learned functions in C++...and we were using Windows 95, so compiling and debugging was a serious matter. I think your middle schoolers can handle it!
user3067860
CC BY-SA 4.0
2019-12-21T13:45:50.610Z
I'll try again: **Please don't use Javascript to teach programming**. The syntax is confusing for beginners. The language itself is a constantly-moving target. I don't even know whether terminating lines with semi-colons is even good practice these days. ES6 has added a whole load of extra confusion. It's just quite annoying in general, and gets in the way of the actual **learning**, which is the important part. I really don't know why you don't use an interactive Python interpreter. Once they know how to structure a program, the syntax is superfluous, so they can move on to JS at that point.
Aaron F
CC BY-SA 4.0
2019-12-22T15:43:29.683Z
@AaronF: Here, have some brownie points, you're 100% right.
Eric Duminil
CC BY-SA 4.0
2019-12-22T17:11:07.493Z
@AaronF The only advantage of Python I can see is that it forces even beginners to use proper indentation. But JS is a totally fine language with its C/Java-style syntax. About every modern language is under constant development, that's really not a problem. And btw, yes, it still is a standard best practice to terminate your statements (not all lines) with semicolons.
Bergi
CC BY-SA 4.0
2019-12-22T19:10:02.260Z
@Bergi: JS is simply too weird compared to Python/Java/Ruby or even C/C++. It's unlike any other programming language, and it's so weakly typed that it's easy to miss/hide/ignore bugs. There are millions of people writing Javascript even though they don't really understand it, and there are Javascript teachers who don't really understand it either. It's possible to write great pieces of software with Javascript but it requires a lot of knowledge and discipline.
Eric Duminil
<introductory-lesson><javascript><lesson-review>
What is the best way to teach JavaScript functions to middle schoolers?
# What is the best way to teach JavaScript functions to middle schoolers?

(Asked by: username_0 on 2019-12-19)

I am teaching middle school kids (aged 11-13) some basic JavaScript and want to get some "professional" opinions.
I am introducing JavaScript with a simple function with a variable, a prompt, if/else, and a couple of alerts. This function (14 lines total) then repeats a series of times (say 10 times) changing the prompt and the conditional in the if/else for a total of say 140 lines. Otherwise the function remains the same. In the lesson, we will be using trinket.io to run the code in browser, and I am able to give them a partially complete piece of code to work from.
I know best programming is to not repeat when you can use additional variables and arguments passed through functions. I am doing that programming with a more advanced class.
My question is this: If just introducing JavaScript and wanting to teach syntax of these basic features, is it better to have students do the repeating (that works but is not programmatically the best way to program) or is it better to teach them the "correct" way where the program is simplified but includes more code understanding than we are ready to introduce?
Here is the code (I repeated it once to show the differences).
function askQuestion1()
{
  var answer = prompt ("What body system contains the heart, blood, arteries, and veins?") .toLowerCase();
   if (answer==="circulatory") {
    alert ("Correct!");
     score += 100;
     alert ("Your total score is now " +score);
  }
  else {
    alert ("Sorry, incorrect.");
     score -= 100;
     alert ("Your total score is now " +score);
  }
}
function askQuestion2()
{
  var answer = prompt ("What body system contains the brain, spinal cord, and nerves?") .toLowerCase();
 if (answer==="nervous") {
   alert ("Correct!");
    score += 200;
    alert ("Your total score is now " +score);
  }
  else {
    alert ("Sorry, incorrect.");
    score -= 200;
    alert ("Your total score is now " +score);
  }
}

**Tags:** introductory-lesson, javascript, lesson-review

> **Comments:**
> **username_1**: Can you please include their expected education level for JavaScript and html? I am assuming that this is being run from the browser due to the use of prompt and alert, is that true?  
> **username_0**: @TravisJ This is all they are expected to know for this lesson. They have built an HTML page with a Jeopardy! type game using tables and the button calls this function with an onclick="" This level of class is being introduced to functions, variables, alerts, prompts, and if/else (the score formula and += and -= are only added because what good is a game without points).  
> **username_1**: Thanks, the background makes a lot of difference for how to approach the subject.  
> **username_2**: Sorry, but I don't understand. Is the alternative to include a loop in a single "function"?  
> **username_1**: @username_2 - The correct way would be to create a producer of these questions, and then instantiate the set of question instances for use. That is way too over the top for this situation.  
> **username_0**: @username_2 I used the following for an advanced group: ``` let values = {   question1: {     btnID: 'btn1',     questionText: "What body system contains the heart, blood, arteries, and veins?",     correctValue: "circulatory",     pic: 'btn1pic',     questionValue: 100,   }, ``` ``` function askQuestion(question) {   var answer = prompt(question.questionText);    if (answer && answer.toLowerCase() === question.correctValue) {     alert ("Correct!");      score += question.questionValue;   }   else {     alert ("Sorry, incorrect.");      score -= question.questionValue;   } }  
> **username_3**: I think that means you could avoid the alerts and maybe the prompts with something you write yourself to take input from a text field and write somewhere suitable in the html. That code would be pretty simple to understand yet safe to ignore at this point.  
> **username_4**: In early high school (age 15-16) we learned functions in C++...and we were using Windows 95, so compiling and debugging was a serious matter. I think your middle schoolers can handle it!  
> **username_5**: I'll try again: **Please don't use Javascript to teach programming**. The syntax is confusing for beginners. The language itself is a constantly-moving target. I don't even know whether terminating lines with semi-colons is even good practice these days. ES6 has added a whole load of extra confusion. It's just quite annoying in general, and gets in the way of the actual **learning**, which is the important part. I really don't know why you don't use an interactive Python interpreter. Once they know how to structure a program, the syntax is superfluous, so they can move on to JS at that point.  
> **username_6**: @AaronF: Here, have some brownie points, you're 100% right.  
> **username_7**: @AaronF The only advantage of Python I can see is that it forces even beginners to use proper indentation. But JS is a totally fine language with its C/Java-style syntax. About every modern language is under constant development, that's really not a problem. And btw, yes, it still is a standard best practice to terminate your statements (not all lines) with semicolons.  
> **username_6**: @username_7: JS is simply too weird compared to Python/Java/Ruby or even C/C++. It's unlike any other programming language, and it's so weakly typed that it's easy to miss/hide/ignore bugs. There are millions of people writing Javascript even though they don't really understand it, and there are Javascript teachers who don't really understand it either. It's possible to write great pieces of software with Javascript but it requires a lot of knowledge and discipline.  

---

## 5 answers

### Answer by username_2 on 2019-12-20. Score: 29

I apologize in advance, but I'm going to be a bit hard on you.

First, your goal of keeping it simple is a good one that I applaud. You are right, IMO, not to bring in advanced features too early.

However, this is not the sort of code I would show to a beginner. Ever. It is the kind of code that, if submitted by an early teen would be fine, but not the sort of code that a teacher should show, lest it be emulated. If this were submitted by a college first year student, as part of some project, it would be severely downgraded.

I think students should only ever be shown code, from instructors, that they would be proud to emulate. But I think the lessons taught in this code need to be unlearned before the student can gain a proper understanding of how to program. I would use some completely different example, even if I was only interested in syntax, which I don't think you should be. You can also teach deeper lessons, just by example, by choosing what code you present to students.

Let me list a bunch of criticisms of the code, that are easily corrected, but using a different framework possibly.

First, the function names aren't descriptive in any way of what the function does. Also, they aren't functions in the classic sense since they return nothing, but that is just an issue with how javascript is built. They are procedures (actually *commands* since they don't have arguments either). But "intention revealing names" are a really good idea so everyone should use them, and novices should see them. So, *askCirculatoryQuestion* is preferable to askQuestion1.

Next, the formatting is a bit sloppy. A minor issue, but, if you are only a bit sloppy it won't be easy to teach them not to be.

Next, your var should probably be a const. There is no intention to change it. (Note: I'm not a javascript wizard, so I hope this is possible in this context.)

Next, you use an identity comparison, so, in the first function neither "the circulatory" nor "circulatory system" would be accepted. This is a human factors issue and may be the main objection to the example overall. An example without such an issue could probably be easily devised. But code that frustrates uses is not what you should show beginning students. But parsing user input is a genuinely difficult problem, of course.

Next, you make assignment here to a global variable, which is a tool that shouldn't be in the beginner's toolbox. It is an advanced incantation suitable only for trained wizards. Such practice makes larger programs much harder to understand and debug. Even wizards use this "spell" sparingly.

Finally, blasting alerts from a function is likely to mislead them when you try to teach real functions (that return values). Too many students have a very hard time with the notion of "return", and think that blasting out the answer is the correct way to write a function. You are laying a trap here that can cause issues later. (Confession: I once had that misconception. It made it difficult to understand program flow.)

Overall, my suggestion is to show students only the sort of code you'd like to see from them, not just now, but in the future. Yes, keep it simple and yes, keep it motivating, but make it poetry.

The code you will get from them is probably going to be worse than the code you give to them. So, always show them something they can emulate and that any teacher would be proud to see from a student. Make it easy for them to build good habits from the start.

But note that your concerns are not the same as mine. I agree that it is too early at the start to stress things like the "say it once" principle and such. And an exercise in which you have them write the analog of your second function after giving them the first wouldn't be a bad idea. It reinforces some skills, which is a good thing.

Again, sorry to be so hard on you.

But lest I be entirely negative, let me also give an idea for something similar that works on more levels than syntax. I'll stick with functions and if-else as the primary lesson.

Show the students a function *maxOfTwo*, that returns the maximum of two arguments. The function doesn't "alert" but, instead returns the value. Then write a driver to test it and have the students execute that a few times. Note that the function needs no local values.

After that, work out with the students a *maxOfThree*, that has three arguments. Do this one two ways. First with nested if statements and again by employing maxOfTwo instead. Don't give this as an assignment, but work out the logic with them and then write the (poetic) code. You may want to introduce a local value, so it is a bit more sophisticated on two levels (locals and nesting). But using *maxOfTwo* twice is a truly beautiful solution that shows the power of abstraction and reduces complexity.

Then, you can assign *medianOfThree* to them to work on. I suggest that it might be worthwhile to have them work out the logic of it in small groups and then come up with the code. They can either write out the code individually (probably a good thing) or in their group. Then critique the code as I have done here.

---

And don't lose track of the point that writing functions is more about *abstraction* than anything else. It makes programs easier to understand. The only code hidden by the *maxOfTwo* function is a single if-else statement. But calling the function (assuming it has a good name) makes the intent of the program immediately clear at that point, where the expanded if statement does not. This, I think, is much more important than the ability to call the function from more than one place and know that the effect is the same. Note that obfuscated code still runs correctly, but it is the understanding that separates the programmer from the machine. So, always use *intention revealing names*.

> **Comments:**
> **username_0**: Advice is always good as I am not a pro so criticism welcomed.   There is a lot of background not in my original post with what the students have already studied. They have learned block-based coding (Scratch) and this "function" relates to previous blocks and concepts learned in Scratch. It isn't perfect but is intended to extend the previous learning while learning a small bit of JavaScript. They have also spent a semester learning some basic HTML/CSS. We use a platform called Trinket.io as our sandbox. It has limitations but is decent.  By the way, I like idea of making code "poetry."  
> **username_1**: If you are purely looking at introducing JavaScript the language on its own, I think this is great advice, and in general outlines standardized approaches to single language instruction. However, in this instance, I think it is important to consider that Bill is introducing JavaScript as another step in building a minimal web application. The introduction of JavaScript should be considered with a holistic view of the current project. Converting to the classical approach of using method best practice would possibly be confusing at that point to these students who are 12-14 years old.  
> **username_0**: @username_2 Can you expand on the "intention revealing names"? I thought that askQuestion, answer, and score would be good names since that is what they are doing. "askQuestion1()" deals with the first question and asks it. The "answer" is the answer that the user enters and the "score" is their points after answering the question. I want to understand better myself as I am self-taught and want to learn best practices.  
> **username_2**: The function names are my main issue. The others are fine. The function names here have no semantic meaning. What is the semantic difference between the two question names? AskCirculatoryQuestion has semantic meaning.  
> **username_0**: @username_2 I see what you are saying now. Thanks.  
> **username_10**: Some refactoring wouldn't hurt either -- that's a lot of copy/pasting.  
> **username_7**: @username_2 While I agree that simple and pure functions like `maxOfTwo` or `medianOfThree` are better for learning features and syntax, having some "driver code" is equally important, showing a concrete use case where the functions are going to be called, like in the score computation of the quiz game. Being able to try out the effects of the their coding in an example application is good for motivation, even more important for younger kids.  
> **username_7**: @DanMašek The copy-pasting is intentional - the abstractions features necessary to reduce the duplication were not yet introduced in the lesson. (Although functions themselves are the ultimate reusability abstraction, so they could help a bit here). However I agree that repeating the code 10 times (as suggested in the OP) is definitely too much. One or two repetitions should be enough.  
> **username_10**: @username_7 I'd say there's still opportunities, even if all they know is parameter-less functions and variables. The score offset could be made a variable instead of writing the constant in two places. Total score could be displayed in a separate function. Although ideally, an different scenario/example would probably be more fitting, one where the different functions do different things.  
> **username_2**: @username_7, actually I assumed the functions would be presented in a wider context in which the names make sense.  

---

### Answer by username_1 on 2019-12-19. Score: 5

Middle school is a great place to start teaching kids programming, and especially JavaScript. I have guest taught something similar for third graders, and it went so much better than I had expected.

Code structure is not important for introductions. Engagement is the most important aspect for kids, and building a game is a great way to do that.

At the beginner level, having them just take something, and place it in is gold. I tend to prefer having students transcribe at that level, where they are given a printout and then are walked through adding the code themselves (maybe this is what you had planned, or similar).

I don't really see the need for repetition at all here though, because it doesn't really benefit them much as written. What I would suggest would be to allow them to come up with their own question2, their own accepted answer, and their own score bonus. This will allow them to not only better understand which inputs correlate with which outputs or behaviors, but will also introduce a good amount of fun to the activity.

Introducing fun, especially at the end of an activity once the main goal was accomplished, is a great way to build engagement. Never underestimate the value of joy :)


---

### Answer by username_11 on 2019-12-20. Score: 2

I think if you're teaching anyone something like programming, you should show them the elements in isolation first, and then combine them once they seem to have a grasp of what you taught them. (software's great for this, since a "statement" is a pretty generic concept)

I'm assuming you mean "function" in the sense of a callable function which runs a block of code and returns.

I think you should focus on re-usability when showing what functions are/how they work. When I was learning, the thing that got them planted in my head firmly is that you can just write some huge block of code once and get it to run at any point later with a single line.

I think a better example of a function would take an argument, and perform some action based on that argument.
e.g. a `greet(name)` function which prints out `Hello $name! Your name is $num letters long.` when called.

You could then show the function being called multiple times, with the results depending on what's passed into the function. (e.g. hard-code the string in one invocation, and pass the response from `prompt()` in another.)


---

### Answer by username_8 on 2019-12-21. Score: 1

# I wouldn't.

Based on my experiences as a student teacher in the Australian education system, typically actual coding doesn't get taught until grades 9-10, at which point the language is typically Python because of its relatively simple syntax.

At the age range you're discussing, students are typically taught a visual block programming language like [Scratch](https://en.wikipedia.org/wiki/Scratch_%28programming_language%29) in one unit (year or semester, depending on how the school's structured their IT course), to teach them about the programming thinking (loops, Boolean logic, etc) without worrying about correct syntax, and then taught HTML and CSS in the following unit to teach them about the importance of syntax and to get them used to typing code into a computer.

> **Comments:**
> **username_0**: Thanks. Actually, that is the path we have followed. We started with Scratch and have moved on to HTML and CSS. Now we are adding just a couple of JS tools to introduce them to JS (we have actually changed our curriculum to start JS in Minecraft Education Edition but these students have missed that). Since they have those basic concepts in place (sequences, loops, conditionals/logic, variables, etc.), we started with alerts and prompts in JavaScript. I wanted to make it a little more fun with the quiz game so I added this "function."  

---

### Answer by username_9 on 2019-12-21. Score: 1

To answer your question directly, I think it would make sense to teach the students the more complicated looping structure first, so that they maintain a good sense of what clean code looks like. Unless, of course, you're going to teach them looping later on in the same lesson and want to use this as an example of bad code, but if you're just introducing them to programming, giving bad examples right of the bad likely isn't the best way to do it.

---

In the larger sense, I think you're approaching this lesson wrong.

First of all, I tend to recommend not including syntactic sugar when introducing programming for the first time, because that requires the student to understand more then they really need to. I mention this because I see you using features such as `foo -= bar` instead of `foo = foo - bar` and `foo === bar` (because the difference between `===` and `==` should be taught later on).

Second, you're introducing a whole lot at once. To understand the code snippets you've given, the students will need to first understand `if` / `else` statements, blocks, mutable variables, general language syntax, typing, string concatenation, and variables at the least. And most importantly, functions! Functions are very nontrivial for someone who hasn't seen programming before. You really ought to break down this lesson into the smaller pieces first, and then, once your students are able to grasp those pieces, then they can put it together into a larger project like the one you've described. But, at that point, they should already know what loops and how they work, so you won't even have this question :)

**TL;DR** Re-evaluate your approach to teaching this lesson. Break down the topic into smaller building blocks and teach those smaller building blocks first.

Good luck with the lesson!


---

