Error
Errors:
5 points
Want more? See our full documentation!
JavaScript Documentation
Basics
Printing to Console
// Using the console.log() function will print the text
// to the console and create a line break
console.log("Hello World.");
console.log("How are you?");
// prints:
// Hello World.
// How are you?
// Concatenate strings and variables using the "+" sign
console.log("Greetings " + "Earthling.");
// prints:
// Greetings Earthling
let species = "Martian";
console.log("Greetings " + species);
// prints:
// Greetings Martian
console.log("Greetings " + species + ". Welcome to Earth!");
// prints:
// Greetings Martian. Welcome to Earth!
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
console.log(myVarName);
console.log("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? ");
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? ");
console.log("Nice to meet you, " + name);
To read more about asynchronous user input, see this tutorial.
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;
console.log(squared); // prints out 25
// Modulus
let z = 14 % 4; // 14 ÷ 4 = 3 with a remainder of 2
console.log(z); // prints out 2
// Absolute value
let abs = Math.abs(x);
// Square root
let sqrt = Math.sqrt(x);
// Rounding
// Math.round() can be used to round numbers
const PI = 3.14;
let roundedPi = Math.round(PI);
console.log(roundedPi); // prints out: 3
const GOLDEN_RATIO = 1.618;
let roundedGoldenRatio = Math.round(GOLDEN_RATIO);
console.log(roundedGoldenRatio); // prints out: 2
// Floor Division
// Math.floor() can be used to perform floor
// division. With floor division, only the
// 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 = Math.floor(5/2);
console.log(result); // prints out: 2
// Geometry
// Note input is in radians, not degrees
Math.sin(radians); // Returns value between -1 and 1
Math.cos(radians); // Returns value between -1 and 1
Math.tan(radians); // Returns value
Random Numbers
// There are several different random methods
Randomizer.nextInt(low, high);
Randomizer.nextBoolean();
Randomizer.nextFloat(low, high);
Randomizer.nextColor();
// Example rolling a dice to get a random roll
let roll = Randomizer.nextInt(1, 6);
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() {
console.log("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) {
console.log("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;
}
Strings
// str.length returns the length of a string
// Example
let str = "hello";
let len = str.length; // equals 5
// str.indexOf(search) returns the first index of the search
// or -1 if not found. It is case sensitive.
//Examples
let str = "hello";
let pos1 = str.indexOf("l"); // returns 2
let pos2 = str.indexOf("H"); // returns -1
// str.substring(start) returns a substring including the
// character at start to the end of the string
//Examples
let str = "hello";
let sub1 = str.substring(1); // equals "ello"
let sub2 = str.substring(3); // equals "lo"
// str.substring(start, end) returns a substring including the
// character at start, but not including the character at end
//Examples
let str = "hello";
let sub1 = str.substring(0,2); // equals "he"
let sub2 = str.substring(1,4); // equals "ell"
To read more about string methods, see this tutorial.
Graphics
CodeHS Library
Check out our full documentation for the CodeHS Graphics Library!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);
Circles
// To make a circle
let circle = new Circle(radius);
// To set the location of the center of the circle
circle.setPosition(x, y);
// Example, red circle with 50px radius with center at (100, 200)
let circle = new Circle(50);
circle.setPosition(100, 200);
circle.setColor("red");
// Get the radius
circle.getRadius(); // returns 50
let curRadius = circle.getRadius(); // store in variable
// Change the radius
circle.setRadius(100);
// Get the position of the center of the circle
let x = circle.getX(); // x is 100
let y = circle.getY(); // y is 200
// Change the location of the circle
let x = getWidth() / 2;
let y = getHeight() / 2;
circle.setPosition(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
circle.move(dx, dy);
Rectangles
// To make a rectangle
let rect = new Rectangle(width, height);
// To set location of the upper left corner of rectangle
rect.setPosition(x, y);
// Example, 200x50 blue rectangle with upper left corner at (100, 200)
let rect = new Rectangle(200, 50);
rect.setPosition(100, 200);
rect.setColor("blue");
// Get location of the upper left corner of the rectangle
let x = rect.getX(); // x is 100
let y = rect.getY(); // y is 200
// Change location of the rectangle
let x = getWidth() / 2;
let y = getHeight() / 2;
rect.setPosition(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
rect.move(dx, dy);
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
myArc.setPosition(x, y);
// Example, a 90-degree arc with
// radius of 50 and color of red:
let myArc = new Arc(50, 0, 90, 0);
myArc.setPosition(100, 200);
myArc.setColor("red");
// Get the location of the center of the arc
let x = myArc.getX(); // x is 100
let y = myArc.getY(); // y is 200
// Change the location of the center of the arc
let x = getWidth() / 2;
let y = getHeight() / 2;
myArc.setPosition(x, y); // arc center is at center of screen
// Adding to and removing from screen
add(myArc); // Add arc
remove(myArc); // Remove arc
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
line.setColor("green");
// Set the line width to 10 pixels
line.setLineWidth(10);
// Adding to and removing from screen
add(line);
remove(line);
// Move the line dx horizontally and dy vertically
line.move(dx, dy);
// Change the starting point of the line to (x1, y1)
line.setPosition(x1, y1);
// Change the end point of the line to (x2, y2)
line.setEndpoint(x2, y2);
//Get the starting point of the line
let x = line.getX(); // x has same value as x1
let y = line.getY(); // y has same value as y1
Ovals
// To make an Oval
let oval = new Oval(width, height);
// To set location of the center of the oval
oval.setPosition(x, y);
// Example, 200x50 blue oval with center at (100, 200)
let oval = new Oval(200, 50);
oval.setPosition(100, 200);
oval.setColor("blue");
// Get location of the center of the oval
let x = oval.getX(); // x is 100
let y = oval.getY(); // y is 200
// Change location of the oval
let x = getWidth() / 2;
let y = getHeight() / 2;
oval.setPosition(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
oval.move(dx, dy);
Polygons
// To make a polygon
let polygon = new Polygon();
// To add points to the polygon
polygon.addPoint(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();
polygon.addPoint(20, 20);
polygon.addPoint(10, 50);
polygon.addPoint(100, 80);
polygon.addPoint(60, 10);
polygon.setColor("green");
// Check if polygon contains a point
polygon.containsPoint(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
polygon.move(dx, dy);
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
txt.setPosition(x, y);
// Example
let txt = new Text("Hello, world!", "30pt Arial");
txt.setPosition(100, 200);
txt.setColor("blue");
// Change what the text says
txt.setText("Goodbye!");
// Get the location of the lower left corner of text
let x = txt.getX(); // x is 100
let y = txt.getY(); // y is 200
// Change the location of the text
let x = getWidth() / 2;
let y = getHeight() / 2;
txt.setPosition(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 = txt.getWidth();
let height = txt.getHeight();
// Adding to and removing from screen
add(txt); // Add text
remove(txt); // Remove text
// Move the text dx horizontally and dy vertically
txt.move(dx, dy);
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("https://static.codehs.com/img/library/objects/helicopter.png");
// set the dimensions of the image
copter.setSize(300, 150);
// set the location of the image
copter.setPosition(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
copter.loaded(getDimensions);
// or
copter.loaded(function() {
// gets the x-coordinate of the image's top left corner
console.log(copter.getX());
// gets the y-coordinate of the image's top left corner
console.log(copter.getY());
// gets the width of the image
console.log(copter.getWidth());
// gets the height of the image
console.log(copter.getHeight());
});
// 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('https://static.codehs.com/img/library/characters/penguin.png');
add(animal);
animal.setImage('https://static.codehs.com/img/library/characters/monkey.jpg');
CodeHS Image Library
- https://static.codehs.com/img/library/characters/penguin.png
- https://static.codehs.com/img/library/characters/monkey.jpg
- https://static.codehs.com/img/library/characters/leopard.jpg
- https://static.codehs.com/img/library/characters/chameleon.jpg
- https://static.codehs.com/img/library/characters/lizard.jpg
- https://static.codehs.com/img/library/characters/butterfly.jpg
- https://static.codehs.com/img/library/objects/icicle.png
- https://static.codehs.com/img/library/objects/helicopter.png
- https://static.codehs.com/img/library/objects/asteroid.png
- https://static.codehs.com/img/library/objects/soccerBall.png
- https://static.codehs.com/img/library/landscapes/flowers.jpg
Color
You can visit the W3Schools CSS Colors page for a list of colors.
// You can use the setColor() method to give your objects a color
// like this:
obj.setColor(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);
circle.setColor("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);
rect.setColor(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:
rect.setColor("#FF66CC");
// There are also many color constants. You can set an objects
// color like this:
obj.setColor(Color.RED);
// List of available color constants:
Color.RED
Color.GREEN
Color.BLUE
Color.YELLOW
Color.CYAN
Color.ORANGE
Color.WHITE
Color.BLACK
Color.GRAY
Color.PURPLE
// Other fun functions
// Return a random color within a group
let color = Color.randomRed();
let color = Color.randomGreen();
let color = Color.randomBlue();
// Get a random color from the randomizer
let color = Randomizer.nextColor();
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
rect.setRotation(45, 0);
rect.setRotation(45); // Does the same thing.
// Sets rotation of the rectangle to Math.PI/2 radians
rect.setRotation(Math.PI / 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
rect.rotate(45, 0);
rect.rotate(45); // Does the same thing.
// Rotates the rectangle by Math.PI/2 radians
rect.rotate(Math.PI / 2, 1);
Graphics Type and Layers
// To get the type of the object:
let type = obj.getType();
// 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.
*/
obj.layer = 1; // moves the graphic forward to 1 layer
obj2.layer = 5; // will be drawn on top of layers 0 - 4
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);
circle.debug = 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);
rect.setAnchor({vertical: 1, horizontal: 1});
// Note: it is best to change the anchor point while debug mode is on
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);
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) {
console.log("x is negative.");
}
if (color == "red" || color == "blue" || color == "yellow") {
console.log("Primary color.");
} else {
console.log("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
}
}
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) {
console.log("x and y are both true");
}
if (x || y) {
console.log("x and/or y are true");
}
if (!x && y) {
console.log("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) {
console.log("x and y are equal");
}
if (x > 5) {
console.log("x is greater than 5.");
}
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++) {
console.log(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) {
console.log(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
}
}
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() {
ball.move(x, y);
}
main();
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) {
console.log("Mouse is at (" +
e.getX() + ", " +
e.getY() + ").");
}
function addBall(e) {
let ball = new Circle(20);
ball.setPosition(e.getX(), e.getY());
add(ball);
}
function updateLine(e) {
line.setEndpoint(e.getX(), e.getY());
}
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);
}
// If you click on an object, turn it red.
function turnRed(e) {
let elem = getElementAt(e.getX(), e.getY());
if (elem != null) {
elem.setColor("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 e.key to get info about
// which key is pressed
function keyDown(e) {
if (e.key == "ArrowLeft") {
ball.move(-5, 0);
}
if(e.key == "k"){
console.log("You pressed k");
}
}
function keyUp(e) {
console.log("You lifted up a key");
}
main();
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()
mySong.play();
// To pause a file, use .pause()
mySong.pause();
// To loop a file, first play the file,
// then set .loop to true:
mySong.play()
mySong.loop = true;
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
sound.setFrequency(440); // 440 Hz
sound.setFrequency("C4"); // Middle C note
sound.setFrequency("A2"); // Low A note
sound.setFrequency("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"
*/
sound.setOscillatorType("sine");
sound.setOscillatorType("square");
// Set the volume (in decibels)
sound.setVolume(2);
/*
* Get information about the sound
*/
let currentVolume = sound.getVolume();
let currentNote = sound.getFrequency();
let currentOscillatorType = sound.getOscillatorType();
/*
* Adding effects to the sound
* Options are: "distortion", "reverb",
* "tremolo", "vibrato", or "chebyshev"
*/
// Add a distortion effect at full capacity
sound.setEffect("distortion", 1);
// Add a tremolo effect at half capacity
sound.setEffect("tremolo", 0.5);
// Add a vibrato effect at 0 capacity
sound.setEffect("vibrato", 0);
// Starting and stopping the sound
// Play the sound continuously
sound.play();
// Play the sound for 3 seconds
sound.playFor(3);
// Stop playing the sound immediately
sound.stop();
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 = arr.length;
// Looping over an array
for (let i = 0; i < arr.length; i++) {
let element = arr[i];
// Print out every element and its index
console.log("Index " + i + ": " + element);
}
// Can also use for...of loops if you don't want the indexes
for (let element of arr) {
console.log(element);
}
// Add to an array
arr.push(elem);
// Remove last element from array
let last = arr.pop();
// Finding the index of an element
let index = arr.indexOf(5);
// Remove an element at an index i
arr.remove(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
arr2.push(9); // changing arr2 also changes arr1
console.log(arr1); // prints [1, 2, 3, 4, 9]
/* ======== Additional array methods ======== */
// Checks to see if a single item is included within an array.
// Returns true if included, false if not included.
array.includes(item)
// Grabs the index of an item within an array. Returns the index
// of the item if in the array, otherwise returns -1.
array.indexOf(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.
array.forEach(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.
array.map(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).
array.every(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).
array.some(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.
array.splice(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.
array.slice(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.
array.join(separator)
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
obj.faveFood = "french fries";
// Get a property value from a key
let food = obj["faveFood"]; // bracket notation
let food = obj.faveFood; // 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() {
console.log("Hi there, my name is " + this.name);
}
};
// In the above object, we use this.name 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
obj.joke = function() {
console.log("What do you call a fish with no eyes?");
}
// You call a method with dot notation
obj.greet(); // prints "Hi there, my name is Jeremy"
// Looping over key-value pairs in an object
for (let key in obj) {
let val = obj[key];
console.log(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) {
console.log(key + " is a property");
}
}
// 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
obj2.name = "Sam"; // changing obj2 also changes obj1
console.log(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) {
this.name = name;
this.color = color;
this.hobby = hobby;
this.faveFood = food;
this.greet = function() {
console.log("Hi there, my name is " + this.name);
}
}
// 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");
person1.greet(); // prints "Hi there, my name is Ryan"
console.log(person1.hobby); // prints "woodworking"
Sets
// Make a new set named "newSet"
let newSet = new Set();
// Add to a set
newSet.add(5);
// Does a set contain a value
newSet.contains(5); // returns a boolean
// Number of elements in the set
let count = newSet.size; // returns an integer
// Make a new set named "setA"
let setA = new Set();
// Add 2 numbers to the set
setA.add(1);
setA.add(2);
// Make a new set named "setB"
let setB = new Set();
// Add 2 numbers to the set
setB.add(2);
setB.add(3);
// Call the intersect function on "setA" and pass in "setB", store the resulting
// set in a new variable named "mutualSet"
let mutualSet = setA.intersect(setB);
Grids
// Create a grid named "newGrid"
let newGrid = new Grid(rows, cols);
// Get a value in a grid
let elem = newGrid.get(row, col);
// Set a value in a grid
newGrid.set(row, col, val);
// Getting dimensions
let rows = newGrid.numRows();
let cols = newGrid.numCols();
// Is a row, col pair inbounds
newGrid.inBounds(row, col);
// Set all values in grid to initial value
newGrid.init(0); // sets all grid values to 0
// Initialze a grid from an array
newGrid.initFromArray([
[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!