Javascript, some details

← back to Creative Computing

by Allison Parrish

This tutorial alerts you to the presence of several important aspects of writing code in Javascript. In the remainder of the tutorials, I’ll be using the features and idioms contained herein, so it’s best to get familiar with them sooner rather than later!

Comments

Source code can get messy and confusing. It’s often helpful to annotate source code so that you can remember what you were thinking and doing when you wrote a particular piece of code. The easiest way to annotate source code is with a little bit of Javascript syntax: the characters //. If // occurs anywhere on a line, it will be “thrown out” before your computer tries to execute the code, along with anything that follows up to the end of the line. Here’s a sketch that demonstrates the use of comments:

► run sketch ◼ stop sketch
let xpos = 200; // x position of ellipse
let ypos = 150; // y position of ellipse
function setup() {
  createCanvas(400, 400);
  noLoop();
}
function draw() {
  background(50);
  stroke(255);
  strokeWeight(8);
  noFill();
  // smaller ellipse to the left
  ellipse(xpos - 100, ypos, 45, 45);
  // smaller ellipse to the right
  ellipse(xpos + 100, ypos, 45, 45);
  // the main attraction
  ellipse(xpos, ypos, 75, 75);
}

Comments are often used to temporarily “disable” lines of code in your program. If you wanted to run the sketch above and see what it looks like without the center ellipse, without having to delete the line entirely, you can just put // in front of the line. (This is often called “commenting it out”).

► run sketch ◼ stop sketch
let xpos = 200; // x position of ellipse
let ypos = 150; // y position of ellipse
function setup() {
  createCanvas(400, 400);
  noLoop();
}
function draw() {
  background(50);
  stroke(255);
  strokeWeight(8);
  noFill();
  // smaller ellipse to the left
  ellipse(xpos - 100, ypos, 45, 45);
  // smaller ellipse to the right
  ellipse(xpos + 100, ypos, 45, 45);
  // the main attraction
  //ellipse(xpos, ypos, 75, 75);
}

Comments are also helpful if you’re collaborating on your code with other people. They can help draw attention to particular parts of the code that might be tricky or non-obvious.

Read more about Javascript comments, including the syntax for creating comments that span multiple lines.

Formatting code

TK

Floating-point numbers

TK