0% found this document useful (0 votes)
3 views37 pages

Documentation - JavaScript ES6 - CodeHS

This document provides comprehensive documentation on JavaScript ES6, covering topics such as printing to the console, variable declaration, user input, asynchronous input, mathematical operations, functions, strings, and graphics programming. It includes examples and explanations for each topic, making it a useful resource for learning JavaScript. Additionally, it references external tutorials for further learning on specific subjects.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views37 pages

Documentation - JavaScript ES6 - CodeHS

This document provides comprehensive documentation on JavaScript ES6, covering topics such as printing to the console, variable declaration, user input, asynchronous input, mathematical operations, functions, strings, and graphics programming. It includes examples and explanations for each topic, making it a useful resource for learning JavaScript. Additionally, it references external tutorials for further learning on specific subjects.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

JavaScript Documentation
Basics
Printing to Console

// Using the [Link]() function will print the text


// to the console and create a line break

[Link]("Hello World.");
[Link]("How are you?");
// prints:
// Hello World.
// How are you?

// Concatenate strings and variables using the "+" sign

[Link]("Greetings " + "Earthling.");


// prints:
// Greetings Earthling

let species = "Martian";


[Link]("Greetings " + species);
// prints:
// Greetings Martian
[Link]("Greetings " + species + ". Welcome to Earth!");
// prints:
// Greetings Martian. Welcome to Earth!

[Link] 1/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

Variables

// Declare a variable
let myVarName;

// Declare and initialize a variable


let myVarName = 5;

// Assign value to an existing variable


myVarName = 10;

// Print a variable
[Link](myVarName);
[Link]("The value is: " + myVarName);

// If a variable isn't going to change its value, it is


// best to use the keyword 'const'

// Variables defined with const:


// * cannot be redeclared
// * cannot be reassigned
// * must be assigned a value when they are declared

// Example:
const PI = 3.141592653589793;
PI = 5; // This will give an error

User Input

// Read a string
// Strings are a series of characters - ex) Hello World
let choice = readLine("What would you like? ");

// Read an integer
// Integers are numbers without a decimal point - ex) 3
let num = readInt("Enter a number: ");

// Read a float
// Float are numbers with a decimal point - ex) 3.14
let cost = readFloat("Enter the cost: ");

// Read a boolean
// Boolean are true/false
let workIsDone = readBoolean("Did you finish your work? ");

[Link] 2/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

Asynchronous User Input

/* In addition to the blocking input methods that receive input via


popup, there are additional asynchronous input methods. readLineAsync,
readIntAsync, readFloatAsync, and readBooleanAsync are non-blocking
functions that can be used in combination with the `await` keyword to
receive input asynchronously.
*/

let name = await readLineAsync("What's your name? ");


[Link]("Nice to meet you, " + name);

To read more about asynchronous user input, see this tutorial ([Link]
input).

[Link] 3/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

Math
// Operators:
+ Addition
- Subtraction
* Multiplication
/ Division
** Exponentiation
% Modulus (Remainder)
() Parentheses (For order of operations)

// Examples
let z = x + y;
let w = x * y;

// Increment (add one)


x++

// Decrement (subtract one)


x--

// Shortcuts
x = x + y; x += y;
x = x - y; x -= y;
x = x * y; x *= y;
x = x / y; x /= y;

// Exponentiation
let squared = 5 ** 2;
[Link](squared); // prints out 25

// Modulus
let z = 14 % 4; // 14 ÷ 4 = 3 with a remainder of 2
[Link](z); // prints out 2

// Absolute value
let abs = [Link](x);

// Square root
let sqrt = [Link](x);

// Rounding
// [Link]() can be used to round numbers
const PI = 3.14;
let roundedPi = [Link](PI);
[Link](roundedPi); // prints out: 3

const GOLDEN_RATIO = 1.618;


let roundedGoldenRatio = [Link](GOLDEN_RATIO);
[Link](roundedGoldenRatio); // prints out: 2

// Floor Division
// [Link]() can be used to perform floor
// division. With floor division, only the

[Link] 4/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS
// integer portion of the quotient is returned.

// For example, 5/2 is 2.5, but with floor division,


// the result is 2 and the .5 is discarded.
let result = [Link](5/2);
[Link](result); // prints out: 2

// Geometry
// Note input is in radians, not degrees

[Link](radians); // Returns value between -1 and 1


[Link](radians); // Returns value between -1 and 1
[Link](radians); // Returns value

Random Numbers

// There are several different random methods


[Link](low, high);
[Link]();
[Link](low, high);
[Link]();

// Example rolling a dice to get a random roll


let roll = [Link](1, 6);

[Link] 5/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

Functions

// A function is a reusable block of code that


// performs a specific task when called.

// To call a function, write the function name,


// followed by parentheses:
printGreeting();

// To define what a function does, use the "function"


// keyword and put the task inside the {} brackets:
function printGreeting() {
[Link]("Hi there!");
}

// Functions can take in values, called parameters.

// The function below takes in a parameter called


// 'name' and prints it in a greeting.
function printGreeting(name) {
[Link]("Hi there " + name);
}

// To call a function that has a parameter, you need


// to include a value, or arguement, when calling it:
printGreeting("Sami");

// Functions can also return a value.

// The function below takes in a value,


// adds two to it, and returns it.
function addTwo(number) {
return number + 2;
}

[Link] 6/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

Strings

// [Link] returns the length of a string

// Example
let str = "hello";
let len = [Link]; // equals 5

// [Link](search) returns the first index of the search


// or -1 if not found. It is case sensitive.

//Examples
let str = "hello";
let pos1 = [Link]("l"); // returns 2
let pos2 = [Link]("H"); // returns -1

// [Link](start) returns a substring including the


// character at start to the end of the string

//Examples
let str = "hello";
let sub1 = [Link](1); // equals "ello"
let sub2 = [Link](3); // equals "lo"

// [Link](start, end) returns a substring including the


// character at start, but not including the character at end

//Examples
let str = "hello";
let sub1 = [Link](0,2); // equals "he"
let sub2 = [Link](1,4); // equals "ell"

To read more about string methods, see this tutorial ([Link]


javascript).

Graphics
CodeHS Library
Check out our full documentation for the CodeHS Graphics Library ([Link]

[Link] 7/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

Canvas

// returns the width of the canvas


getWidth();

// returns the height of the canvas


getHeight();

// Example returns the y coordinate of the


// center of the canvas
const CENTER_Y = getHeight() / 2;

// Example returns the x coordinate of the


// center of the canvas
const CENTER_X = getWidth() / 2;

// Removes all objects from the canvas


removeAll();

// Customizes the width and height of the canvas


setSize(width, height);

[Link] 8/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

Circles

// To make a circle
let circle = new Circle(radius);

// To set the location of the center of the circle


[Link](x, y);

// Example, red circle with 50px radius with center at (100, 200)
let circle = new Circle(50);
[Link](100, 200);
[Link]("red");

// Get the radius


[Link](); // returns 50
let curRadius = [Link](); // store in variable

// Change the radius


[Link](100);

// Get the position of the center of the circle


let x = [Link](); // x is 100
let y = [Link](); // y is 200

// Change the location of the circle


let x = getWidth() / 2;
let y = getHeight() / 2;
[Link](x, y); // circle center is in the center of the screen

// Adding to and removing from screen


add(circle); // Add to screen
remove(circle); // Remove from screen

// Move the circle dx horizontally and dy vertically


[Link](dx, dy);

[Link] 9/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

Rectangles

// To make a rectangle
let rect = new Rectangle(width, height);

// To set location of the upper left corner of rectangle


[Link](x, y);

// Example, 200x50 blue rectangle with upper left corner at (100, 200)
let rect = new Rectangle(200, 50);
[Link](100, 200);
[Link]("blue");

// Get location of the upper left corner of the rectangle


let x = [Link](); // x is 100
let y = [Link](); // y is 200

// Change location of the rectangle


let x = getWidth() / 2;
let y = getHeight() / 2;
[Link](x, y) // upper left corner is at center of screen

// Adding to and removing from screen


add(rect); // Add rectangle
remove(rect); // Remove rectangle

// Move the rect dx horizontally and dy vertically


[Link](dx, dy);

[Link] 10/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

Arcs

// To make an arc
let myArc = new Arc(radius, start, end, unit);

// More specifically, the parameters are:


// 1. radius of the arc
// 2. starting angle of the arc
// 3. ending angle of the arc
// 4. angle unit (0 for degrees, 1 for radians)

// To set the position of the center of the arc


[Link](x, y);

// Example, a 90-degree arc with


// radius of 50 and color of red:
let myArc = new Arc(50, 0, 90, 0);
[Link](100, 200);
[Link]("red");

// Get the location of the center of the arc


let x = [Link](); // x is 100
let y = [Link](); // y is 200

// Change the location of the center of the arc


let x = getWidth() / 2;
let y = getHeight() / 2;
[Link](x, y); // arc center is at center of screen

// Adding to and removing from screen


add(myArc); // Add arc
remove(myArc); // Remove arc

[Link] 11/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

Lines

// To draw a line from (x1, y1) to (x2, y2)


let line = new Line(x1, y1, x2, y2);

// Set the line color to green


[Link]("green");

// Set the line width to 10 pixels


[Link](10);

// Adding to and removing from screen


add(line);
remove(line);

// Move the line dx horizontally and dy vertically


[Link](dx, dy);

// Change the starting point of the line to (x1, y1)


[Link](x1, y1);

// Change the end point of the line to (x2, y2)


[Link](x2, y2);

// Get the line's x- and y-position values


let x = [Link](); // returns the smaller x-value of the two endpoints
let y = [Link](); // returns the smaller y-value of the two endpoints

[Link] 12/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

Ovals
// To make an Oval
let oval = new Oval(width, height);

// To set location of the center of the oval


[Link](x, y);

// Example, 200x50 blue oval with center at (100, 200)


let oval = new Oval(200, 50);
[Link](100, 200);
[Link]("blue");

// Get location of the center of the oval


let x = [Link](); // x is 100
let y = [Link](); // y is 200

// Change location of the oval


let x = getWidth() / 2;
let y = getHeight() / 2;
[Link](x, y) // oval's center is at center of screen

// Adding to and removing from screen


add(oval); // Add oval
remove(oval); // Remove oval

// Move the oval dx horizontally and dy vertically


[Link](dx, dy);

[Link] 13/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

Polygons

// To make a polygon
let polygon = new Polygon();

// To add points to the polygon


[Link](x, y);

// Example, 4-sided green polygon


// NOTE: The order in which you add the points
// determines how the polygon is drawn
let polygon = new Polygon();
[Link](20, 20);
[Link](10, 50);
[Link](100, 80);
[Link](60, 10);
[Link]("green");

// Check if polygon contains a point


[Link](x, y); // returns boolean

// Adding to and removing from screen


add(polygon); // Add polygon
remove(polygon); // Remove polygon

// Move the polygon dx horizontally and dy vertically


[Link](dx, dy);

[Link] 14/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

Text

// To make a graphical text object


let txt = new Text(label, font);

// To set the position of the lower left corner of the text


[Link](x, y);

// Example
let txt = new Text("Hello, world!", "30pt Arial");
[Link](100, 200);
[Link]("blue");

// Change what the text says


[Link]("Goodbye!");

// Get the location of the lower left corner of text


let x = [Link](); // x is 100
let y = [Link](); // y is 200

// Change the location of the text


let x = getWidth() / 2;
let y = getHeight() / 2;
[Link](x, y) // text's lower left corner is
// in the center of the screen

// Get the width and height of the text object


let width = [Link]();
let height = [Link]();

// Adding to and removing from screen


add(txt); // Add text
remove(txt); // Remove text

// Move the text dx horizontally and dy vertically


[Link](dx, dy);

[Link] 15/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

Images

// A web image can be added to the graphics canvas


// as a WebImage. WebImages are created, sized,
// and positioned much like other graphics objects.

// To create a new WebImage, use a URL that links


// directly to the image on the Internet.
// Use the Upload Tab in the editor to upload and create
// a valid URL for your own image.

let copter = new WebImage("[Link]

// set the dimensions of the image


[Link](300, 150);
// set the location of the image
[Link](getWidth()/4, getHeight()/2);
// Adding copter to screen
add(copter);
// Removing copter from screen
remove(copter);

// Image getter commands return information about your image


// Note that you need to make sure the image is loaded
// first before you use these commands. The .loaded method
// will call a function once the image is loaded.

// Write a getDimensions function with the getters


[Link](getDimensions);
// or
[Link](function() {
// gets the x-coordinate of the image's top left corner
[Link]([Link]());
// gets the y-coordinate of the image's top left corner
[Link]([Link]());
// gets the width of the image
[Link]([Link]());
// gets the height of the image
[Link]([Link]());
});

// Note that the URL to the image must be directly


// to the image file itself. It should generally end with
// something like .png, .jpg, or another image file type.

// To replace the image content of a WebImage, you can call


// .setImage(url):
let animal = new WebImage('[Link]
add(animal);

[Link]('[Link]

[Link] 16/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

CodeHS Image Library


[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]

Color
You can visit the W3Schools CSS Colors ([Link] page for a list of
colors.

[Link] 17/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

// You can use the setColor() method to give your objects a color
// like this:
[Link](color);

// You can pass in to setColor() any CSS color name as a string.


// Refer to the link above for a list of possible color names

// For example, here is how we set a circle to be teal:


let circle = new Circle(10);
[Link]("teal");

// You can also choose your own color by giving a red, green,
// and blue component like
let color = new Color(r, g, b);

// The values are between 0-255 for each component. After making
// a new color, you can use it to set the color of an object.

// For example, to set an existing rectangle called


// rect to be brown:
let brown = new Color(139, 69, 19);
[Link](brown);

// Another way to set the color of an object is to use a


// string with the hexadecimal color value with setColor.
// For example, to set a rect object to be pink:
[Link]("#FF66CC");

// There are also many color constants. You can set an objects
// color like this:
[Link]([Link]);

// List of available color constants:


[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]

// Other fun functions

// Return a random color within a group


let color = [Link]();
let color = [Link]();
let color = [Link]();

[Link] 18/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS
// Get a random color from the randomizer
let color = [Link]();

Rotation
/**
* The following graphic objects can be rotated:
* - Rectangle
* - Arc
* - Line
* - Oval
* - Text
* - WebImage
*/

// Set the rotation of the rectangle with these parameters:


// 1. angle to rotate
// 2. angle unit (0 for degrees, 1 for radians)
// This will default to degrees.

// Sets rotation of the rectangle to 45 degrees


[Link](45, 0);
[Link](45); // Does the same thing.

// Sets rotation of the rectangle to [Link]/2 radians


[Link]([Link] / 2, 1);

// Add rotation with these parameters:


// 1. angle to rotate
// 2. angle unit (0 for degrees, 1 for radians)
// This will default to degrees.

// Rotates the rectangle by 45 degrees


[Link](45, 0);
[Link](45); // Does the same thing.

// Rotates the rectangle by [Link]/2 radians


[Link]([Link] / 2, 1);

[Link] 19/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

Graphics Type and Layers

// To get the type of the object:


let type = [Link]();

// could return: 'Circle', 'Rectangle', 'Text', 'Line', or 'WebImage'

/* You can change the order of your graphics by


* using the layer property. Setting the layer
* to 0 sends the graphic to the very back of the canvas.
* The graphic with a higher layer number will be
* drawn on top of objects with a lower layer number.
* The default layer of a graphic is 1.
*/

[Link] = 1; // moves the graphic forward to 1 layer


[Link] = 5; // will be drawn on top of layers 0 - 4

[Link] 20/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

Debug Mode and Anchors

/*
* The debug method can be used to see where
* an object's anchor point is located
* By default, a circle's anchor point is
* at its center and a rectangle's anchor point
* is located at its top-left corner.
* The debug method evaluates a boolean and can
* be set to 'true' for any object
*/

// The debug method is set to 'false' by default


// Here's how you can turn it on for a circle object:
let circle = new Circle(50);
[Link] = true;

/*
* You can also change an object's anchor point
* by using setAnchor()
* An anchor of 0, 0 will cause the shape to
draw with its position at its top left corner
* An anchor of 0.5, 0.5 will cause the shape
to draw with its position at its center
* An anchor of 1, 1 will cause the shape to
draw with its position at its bottom right corner
*/

// Here's how you can change the anchor point of


// a rectangle to be at the bottom right corner:
let rect = new Rectangle(50, 25);
[Link]({vertical: 1, horizontal: 1});

// Note: it is best to change the anchor point while debug mode is on

[Link] 21/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

Control Structures
Booleans

// A boolean is either true or false


let myBoolean = true;

let anotherBoolean = false;

let result = readBoolean("Question? ");

// Not Operator
let x = !y; // x gets the opposite of y

// And Operator
let andExp = x && y;

// Or Operator
let orExp = x || y;

// You can combine many booleans!


let boolExp = x && (y || z);

[Link] 22/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

If Statements, If/Else, If/Else If/Else

if (BOOLEAN_EXPRESSION) {
// code to execute if the experession is true
}

if (BOOLEAN_EXPRESSION) {
// code to execute if the expression is true
} else {
// code to execute if the expression is false
}

if (x < 0) {
[Link]("x is negative.");
}

if (color == "red" || color == "blue" || color == "yellow") {


[Link]("Primary color.");
} else {
[Link]("Not a primary color.");
}

// You can use else if you have multiple


// conditions, but only one should happen.
if (condition_1) {

} else if (condition_2) {

} else if (condition_3) {

} else {

// You can always write these using nested


// if/else. For example:
if (condition_1) {
// code here runs if condition 1 is true
} else {
if (condition_2) {
// if condition 2 is true
} else {
// and here if condition 2 is false
}
}

[Link] 23/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

Logical Operators

// Logical operators return booleans (true/false values)


x && y // AND operator -- true if BOTH x and y are true
x || y // OR operator -- true if x OR y are true
! x // NOT operator -- true if x is false (and false if x is true)

// Logical operators in if statements


if (x && y) {
[Link]("x and y are both true");
}

if (x || y) {
[Link]("x and/or y are true");
}

if (!x && y) {
[Link]("x is false and y is true");
}

Comparison Operators

// Comparison operators return booleans (true/false values)


x == y // is x equal to y
x != y // is x not equal to y
x > y // is x greater than y
x >= y // is x greater than or equal to y
x < y // is x less than y
x <= y // is x less than or equal to y

// Comparison operators in if statements


if (x == y) {
[Link]("x and y are equal");
}

if (x > 5) {
[Link]("x is greater than 5.");
}

[Link] 24/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

For Loops

// for loops repeat code a specific number of times

const COUNT = 5;

for (let i = 0; i < COUNT; i++) {


/* Repeat code betweeen the brackets 5 times,
* as the COUNT variable is 5. */
}

// Print numbers 0-9


for (let i = 0; i < 10; i++) {
[Link](i);
}

While Loops

// while loops repeat until a boolean expression becomes false

while(boolean expression){
/* Repeat code betweeen brackets while
* 'boolean expression' is true */
}

// Countdown from from 15 to 10


let i = 15;
while (i > 9) {
[Link](i);
i--;
}

// Use a break statement to exit out of a loop


while (true) {
// code to repeat
if (condition) {
break; // breaks out of while loop
}
}

[Link] 25/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

Animation
Timers

setTimer(fn, delay); // Create a timer


stopTimer(fn); // Stop a timer

// Example: call moveBall every 40 milliseconds


function main() {
setTimer(moveBall, 40);
}

function moveBall() {
[Link](x, y);
}

main();

[Link] 26/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

Mouse Events

// Mouse events are used to create programs


// that respond to users' mouse clicks, drags,
// and movements.

// When the mouse event occurs, the function


// registered with the event will be called. Note
// that you leave out the parentheses () when
// passing the name of the function.

// Here is a list of mouse events that can be used:


mouseMoveMethod(functionToCall); // on mouse movement
mouseClickMethod(functionToCall); // on mouse clicks
mouseDragMethod(functionToCall); // on mouse drags
mouseDownMethod(functionToCall); // mouse button depressed
mouseUpMethod(functionToCall); // mouse button released

// Sample program using mouse events


function main() {
// Set up mouse callbacks
mouseMoveMethod(onMouseMove);
mouseClickMethod(addBall);
mouseDragMethod(updateLine);
}

function onMouseMove(e) {
[Link]("Mouse is at (" +
[Link]() + ", " +
[Link]() + ").");
}

function addBall(e) {
let ball = new Circle(20);
[Link]([Link](), [Link]());
add(ball);
}

function updateLine(e) {
[Link]([Link](), [Link]());
}

main();

// The function getElementAt(x, y) can be used to grab


// an object, if one exists, at the coordinates
// (x, y). If none present, returns null

// Example
function main() {
mouseClickMethod(turnRed);
}

[Link] 27/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS
// If you click on an object, turn it red.
function turnRed(e) {
let elem = getElementAt([Link](), [Link]());
if (elem != null) {
[Link]("red");
}
}

main();

Keyboard Events

// Similar to mouse events, you can also capture


// keyboard events

function main() {
// Set up keyboard callbacks
keyDownMethod(keyDown);
keyUpMethod(keyUp);
}

// Current approach is to use [Link] to get info about


// which key is pressed
function keyDown(e) {
if ([Link] == "ArrowLeft") {
[Link](-5, 0);
}
if ([Link] == "k"){
[Link]("You pressed k");
}
if ([Link] == "Enter"){
[Link]("You pressed Enter");
}
if ([Link] == " "){
[Link]("You pressed Space key");
}
}

function keyUp(e) {
[Link]("You lifted up a key");
}

main();

[Link] 28/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

Audio Files

// To add a sound file to a program, first create a variable


// to store the sound you want. Be sure to use a link
// directly to the audio file itself (for example,
// if it's an mp3, the link should end with .mp3).
// The link must be a full URL to a sound file that
// is available on the internet.
let mySong = new Audio("link_to_sound_file.mp3");

// To play the file, use .play()


[Link]();

// To pause a file, use .pause()


[Link]();

// To loop a file, first play the file,


// then set .loop to true:
[Link]()
[Link] = true;

[Link] 29/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

Sound
/*
* Create your own sound waves!
*/

// Construct a new Sound with a given note and sound wave type
let sound = new Sound("C4", "square");
let sound2 = new Sound("C1", "sawtooth");

// Set the tone to either a frequency value or a note value


[Link](440); // 440 Hz
[Link]("C4"); // Middle C note
[Link]("A2"); // Low A note
[Link]("A#8"); // High A sharp note

/*
* Set the oscillator type for the sound wave. Options are:
*
* Basic waves: "square", "sine", "triangle", or "sawtooth"
* Fat waves: "fatsquare", "fatsine", "fattriangle", or "fatsawtooth"
* AM waves: "amsquare", "amsine", "amtriangle", or "amsawtooth"
* FM waves: "fmsquare", "fmsine", "fmtriangle", or "fmsawtooth"
* Special waves: "pwm", or "pulse"
* Drum sound: "drum"
* Cymbal sound: "metal"
*/
[Link]("sine");
[Link]("square");

// Set the volume (in decibels)


[Link](2);

/*
* Get information about the sound
*/

let currentVolume = [Link]();


let currentNote = [Link]();
let currentOscillatorType = [Link]();

/*
* Adding effects to the sound
* Options are: "distortion", "reverb",
* "tremolo", "vibrato", or "chebyshev"
*/

// Add a distortion effect at full capacity


[Link]("distortion", 1);

// Add a tremolo effect at half capacity


[Link]("tremolo", 0.5);

[Link] 30/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS
// Add a vibrato effect at 0 capacity
[Link]("vibrato", 0);

// Starting and stopping the sound

// Play the sound continuously


[Link]();

// Play the sound for 3 seconds


[Link](3);

// Stop playing the sound immediately


[Link]();

[Link] 31/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

Data Structures
Arrays

// Create an empty array


let arr = [];

// Create an array with values


let arr = [1, 2, 4];

// An array can have any type of data (x is a variable)


let arr = [4, "hello", x];

// Access an element in an array with arr[index];


let firstElem = arr[0];

// Set an element in an array


arr[4] = 9;

// length of an array
let length = [Link];

// Looping over an array


for (let i = 0; i < [Link]; i++) {
let element = arr[i];
// Print out every element and its index
[Link]("Index " + i + ": " + element);
}

// Can also use for...of loops if you don't want the indexes
for (let element of arr) {
[Link](element);
}

// Add to an array
[Link](elem);

// Remove last element from array


let last = [Link]();

// Finding the index of an element


let index = [Link](5);

// Remove an element at an index i


[Link](i)

// Careful, arrays are assigned by reference


let arr1 = [1, 2, 3, 4];
let arr2 = arr1; // arr2 is now pointing to the same data as arr1
[Link](9); // changing arr2 also changes arr1
[Link](arr1); // prints [1, 2, 3, 4, 9]

/* ======== Additional array methods ======== */

[Link] 32/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

// Checks to see if a single item is included within an array.


// Returns true if included, false if not included.
[Link](item)

// Grabs the index of an item within an array. Returns the index


// of the item if in the array, otherwise returns -1.
[Link](item)

// Calls a function for every item in an array (with the item and
// its index as the parameters). This method does NOT alter the
// original array or return anything on its own.
[Link](functionName)

// Calls a function for every item in an array (with the item


// as the parameter). This method will return a new array with
// the new items, without changing the original array.
[Link](functionName)

// Calls a function for every item in an array (with the item


// as the parameter). The function itself should return true
// or false depending on whether the item satisfies a defined
// condition. Using this method will return true only if all
// items meet the function condition (ie, the function returns
// true for every item).
[Link](functionName)

// Calls a function for every item in an array (with the item


// as the parameter). The function itself should return true or
// false depending on whether the item satisfies a defined
// condition. Using this method will return true if at least one
// of the items meets the function condition (ie, the function
// returns true for at least item).
[Link](functionName)

// Starts at the specified index and removes a specific number


// of items from the array. This method returns the removed
// items in a new array.
[Link](starting index, # items to remove)

// Starts at the specified index and copies items (up to the


// ending index) into a new array. This method returns a new
// array with the copied items and does NOT affect the original
// array.
[Link](starting index, ending index)

// returns the items in the array as one string, separated by


// the separator (can be any string). This does NOT affect the
// original array.
[Link](separator)

[Link] 33/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

Objects

// Object literal
let obj = {
name: "Jeremy",
color: "blue"
};

// Objects have key-value pairs known as "properties"

// Set a property with bracket notation


obj["hobby"] = "juggling";

// Set a property with dot notation


[Link] = "french fries";

// Get a property value from a key


let food = obj["faveFood"]; // bracket notation
let food = [Link]; // dot notation

// Objects can also have key-value actions known as "methods". You


// define them the same way as properties, but the value is
// is a function instead of a single value.
let obj = {
name: "Jeremy",
color: "blue",
greet: function() {
[Link]("Hi there, my name is " + [Link]);
}
};

// In the above object, we use [Link] to refer to the name


// property already defined in that object. "this" is a special
// JS keyword that refers to the object itself.

// Adding another method


[Link] = function() {
[Link]("What do you call a fish with no eyes?");
}

// You call a method with dot notation


[Link](); // prints "Hi there, my name is Jeremy"

// Looping over key-value pairs in an object


for (let key in obj) {
let val = obj[key];
[Link](key + ": " + val);

// Note that this will include properties and methods. Can use
// typeof(val) to see if the value is a function (ie method).
if (typeof(val) != "function) {
[Link](key + " is a property");
}

[Link] 34/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS
}

// Careful, objects are assigned by reference


let obj1 = {name: "Kate", age:16};
let obj2 = obj1; // obj2 is now pointing to the same data as obj1
[Link] = "Sam"; // changing obj2 also changes obj1
[Link](obj1); // prints {"name":"Sam","age":16}

/* ===== Object Constructors ====== */

// If you're going to be creating multiple copies of certain object,


// like multiple person objects, it's more effective to use an
// object constructor.
function Person(name, color, hobby, food) {
[Link] = name;
[Link] = color;
[Link] = hobby;
[Link] = food;

[Link] = function() {
[Link]("Hi there, my name is " + [Link]);
}
}

// An object constructor creates a blueprint to create objects. To


// create a new single object, you call it with the "new" keyword.
let person1 = new Person("Ryan", "blue", "woodworking", "sourdough bread");

[Link](); // prints "Hi there, my name is Ryan"


[Link]([Link]); // prints "woodworking"

[Link] 35/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

Sets

// Make a new set named "newSet"


let newSet = new Set();

// Add to a set
[Link](5);

// Does a set contain a value


[Link](5); // returns a boolean

// Number of elements in the set


let count = [Link]; // returns an integer

// Make a new set named "setA"


let setA = new Set();

// Add 2 numbers to the set


[Link](1);
[Link](2);

// Make a new set named "setB"


let setB = new Set();

// Add 2 numbers to the set


[Link](2);
[Link](3);

// Call the intersect function on "setA" and pass in "setB", store the resulting
// set in a new variable named "mutualSet"
let mutualSet = [Link](setB);

[Link] 36/37
4/18/26, 4:50 PM Documentation - JavaScript ES6 | CodeHS

Grids

// Create a grid named "newGrid"


let newGrid = new Grid(rows, cols);

// Get a value in a grid


let elem = [Link](row, col);

// Set a value in a grid


[Link](row, col, val);

// Getting dimensions
let rows = [Link]();
let cols = [Link]();

// Is a row, col pair inbounds


[Link](row, col);

// Set all values in grid to initial value


[Link](0); // sets all grid values to 0

// Initialze a grid from an array


[Link]([
[6, 3, 2], // 0th row
[2, 5, 1], // 1st row
[4, 3, 9], // 2nd row
[1, 5, 1] // 3rd row
]);
Want more? See our full documentation for the CodeHS Graphics Library ([Link]
lib/docs/)!

[Link] 37/37

You might also like