Code
Introduction
Javascript (JS)
JS functions
JS comments
JS console

Game hints
Write to console

Lesson 2 - Hello World (Javascript)

Introduction

Javascript makes up the "brains" of your Dragons. In this lesson, you'll write your first line of Javascript code. We'll cover the basics of Javascript, including how to write messages to the Javascript console.

Javascript (JS)

Go ahead and open up your Dragon A.I. code from the last lesson. As we saw in Lesson 1, your Javascript code always goes inside the <script></script> tags.

Notice how Javascript looks different from HTML:

JS functions

Find this paragraph in your code:
function run(state) { }
That is how you make a "function" in Javascript. A function is a way to organize code that does a specific task into a neat package. This function has the name "run". This function expects one argument to be passed to it called "state". Within the curly braces, you can write code to do something when this function is called. This function doesn't do anything right now, because we haven't written any code inside the curly braces (yet).

A few lines down, you'll see:
Game.register(run);
This registers your run function with the Game. When you register your run function with the game, it will be executed on every round. Thus, any code you put inside the run function will be executed on every round.

JS comments

It is always a good idea to add comments to your code. This helps you remember what a piece of code does, or describe it to whoever reads it. Comments in Javascript can look like one of the following:

// This is a comment
/* This is also a comment; but it can span many lines */

JS console

The console is where you can write text and view them in your browser. This is useful for sending messages to yourself so you can see what is going on. It is also useful for debugging some code that doesn't work.

To open the console in Chrome, press F12. Click on the "Console" tab if it's not already selected. Now that you have the console open, let's try printing something to it.

Write to console

To complete this Quest, you must print "hello" to the console. The command to do this is:
console.log("hello");
Put this inside your run function, so it looks like this:
function run(state) { console.log("hello"); }
When you play the Quest, you'll see a stream of hello scrolling by in the console. This is because your run function is called on every turn, and your run function prints "hello" to the console every time it's called.

Give the game a few seconds to detect your "hello" console message. If you did it right, a box will pop up and say "Victory!"

Cheatcode

Spoiler alert! Click to reveal full solution.
<!DOCTYPE html> <html> <body> <div id="display">hello</div> <script> function run(state) { console.log("hello"); } Game.register(run); </script> </body> </html>