Please enable JavaScript to use CodeHS

JavaScript Documentation

Basics

Printing to Console

// Using the println() function will print the text and create a line break 
// Example of using println()
println("Hello");
println("world.");
// Result:
// Hello
// world.

// Using the print() statement does NOT create a line break
// Example of using print()
print("Hello world. ");
print("How are you?");
// Result:
// Hello world. How are you?

// You can also print to the console using console.log() (includes line break)
// Example:
console.log("Hello world!");

Variables

// Declare a variable
var myVarName;

// Initialize a variable
var myVarName = 5;

// Assign to an existing variable
myVarName = 10;

// Print a variable
println(myVarName);
println("The value is: " + myValue);

// Variables can also be declared and initialized using the keyword 'let'
let myVarName;
let myVarname = 5;

// 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
 * Variables defined with const cannot be reassigned
 * Variables defined with const 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
var str = readLine(prompt);

// Read an integer
// Integers are numbers without a decimal point - ex: 3
var num = readInt(prompt);

// Read a float
// Float are numbers with a decimal point - ex: 3.14
var cost = readFloat(prompt);

// Read a boolean
// Boolean are true/false
var bool = readBoolean(prompt);

// You should replace the word prompt with
// the question you'd like to ask. For example:
var name = readLine("What is your name? ");
var age = readInt("What is your age? ");
var finishedWork = readBoolean("Is your work done? ");

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
var z = x + y;
var 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
var squared = 5 ** 2;
println(squared);   // prints out 25

// Modulus
var z = 10 % 4             // 2 * 4 = 8; 10 - 8 = 2
println(z)                 // prints out: 2

// Absolute value
var abs = Math.abs(x);

// Square root
var sqrt = Math.sqrt(x);

// Rounding
// Math.round() can be used to round numbers
var pi = 3.14;
var roundedPi = Math.round(pi);
println(roundedPi);				// prints out: 3

var goldenRatio = 1.618;
var roundedGoldenRatio = Math.round(goldenRatio);
println(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.
var result = Math.floor(5/2);
println(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

// Random integer between low and high
Randomizer.nextInt(low, high);
Randomizer.nextBoolean();
Randomizer.nextFloat(low, high);
Randomizer.nextColor();

var roll = Randomizer.nextInt(1,6);

var color = Randomizer.nextColor();

Strings

// str.length
// returns the length of a string

// Example
var str = "hello";
var 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
var str = "hello";
var pos1 = str.indexOf("l"); // returns 2

var pos2 = str.indexOf("H"); // returns -1

// str.substring(start);
// returns a substring including the
// character at start to the end of the
// string

//Examples
var str = "hello";
var sub1 = str.substring(1); // equals "ello"
var 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
var str = "hello";
var sub1 = str.substring(0,2); // equals "he"
var sub2 = str.substring(1,4); // equals "ell"

Functions

// Functions can take in values, called parameters.
// The function below takes in a parameter called
// 'input' and prints it.
function printText(input) {
    println(input);
}

// 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;
}

Control Structures

Booleans

// A boolean is either true or false
var myBoolean = true;

var anotherBoolean = false;

var result = readBoolean("Question? ");

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

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

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

// You can combine many booleans!
var boolExp = x && (y || z);

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

// Logical operators in if statements
if(x && y){
	println("x and y are both true");
}

if(x || y){
	println("x and/or y are true");
}

if(!x && y){
    println("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){
	println("x and y are equal");
}

if(x > 5){
	println("x is greater than 5.");
}

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

if(BOOLEAN_EXPRESSION){
	// code to execute if true
}

if(BOOLEAN_EXPRESSION){
	// code if true
} else {
	// code if false
}

if(x < 0){
	println("x is negative.");
}

if(color == "red" || color == "blue" || color == "yellow"){
	println("Primary color.");
} else {
	println("Not a primary color.");
}

// You can use else if 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
	}
}

For Loops

var COUNT = 5;

for(var i = 0; i < COUNT; i++){
	/* Repeat code betweeen the brackets 5 times,
	 * as the COUNT variable is 5. */
}

// Print numbers 0-9
for(var i = 0; i < 10; i++){
	println(i);
}

While Loops

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

// Countdown from from 15 to 10
var i = 15;
while(i > 9){
	println(i);
	i--;
}
// This is a loop and a half format
while(true){
	// code
	if(condition){
		break;
	}
}

Data Structures

Arrays

// Create an empty array
var arr = [];

// Create an array with values
var arr = [1, 2, 4];

// An array can have any type
var arr = [4, "hello", x];

// Access an element in an array
var elem = arr[i];

var firstElem = arr[0];

// Set an element in an array
arr[4] = 9;

// Looping over an array
for(var i = 0; i < arr.length; i++){
	var cur = arr[i];
	// process cur
}

// length of an array
var length = arr.length;

// Add to an array
arr.push(elem);

// Remove last element from array
var last = arr.pop();

// Finding the index of an element in a list
var index = arr.indexOf(5);

// Remove an element from a list at index i
arr.remove(i)

Maps/Objects

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

// Objects/Maps have a collection of key, value pairs

// Set a value
obj["Jeremy"] = "123-4567";

// Get a value for a key
var phone = obj["Jeremy"];

// Loop over an object
for(var key in obj){
	var val = obj[key];
	// process key and val
}

Sets

// Make a new set named "newSet"
var 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
var count = newSet.size; // returns an integer

// Make a new set named "setA"
var setA = new Set();
// Add 2 numbers to the set
    setA.add(1);
    setA.add(2);
// Make a new set named "setB"
var 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"
var mutualSet = setA.intersect(setB);

Grids

// Create a grid named "newGrid"
var newGrid = new Grid(rows, cols);

// Get a value in a grid
var elem = newGrid.get(row, col);

// Set a value in a grid
newGrid.set(row, col, val);

// Getting dimensions
var rows = newGrid.numRows();
var 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
]);