Intro to JavaScript

In this tutorial, you're going to write JavaScript in the Earth Engine Code Editor. Before getting started, use the Code Editor guide to get familiar with the Code Editor environment.

This tutorial covers just enough JavaScript to get you started writing Earth Engine scripts. Additional helpful resources:

Hello World!

Time to write your first JavaScript for Earth Engine! In your Chrome browser, go to code.earthengine.google.com and copy the following into the Code Editor:

print('Hello World!');

Click Run and observe that 'Hello world!' is printed to the Console tab. The line above is a JavaScript statement. In JavaScript, statements end in a semicolon. Earth Engine programs are made up of a set of statements like this one. You can prevent code from running without deleting it by commenting it. One of the ways to comment out code is by putting two forward slashes // before the code that you don't want to run. For example:

Basic JavaScript data types

Strings

Using variables to store objects and primitives helps code readability. For example, a variable that stores a string object is defined by single ' or double " quotes (but don't mix them), with single quotes preferred. Make a new string and store it in a variable called greetString:

// Use single (or double) quotes to make a string.
var greetString = 'Ahoy there!';
// Use parentheses to pass arguments to functions.
print(greetString);

Numbers

Note that variables are defined with the keyword var. Variables can also store numbers:

// Store a number in a variable.
var number = 42;
print('The answer is:', number);

In this example, observe that when print() is given two arguments separated by commas, each argument is printed on a different line.

Lists

Define lists with square brackets []. A list of numbers, for example:

// Use square brackets [] to make a list.
var listOfNumbers = [0, 1, 1, 2, 3, 5];
print('List of numbers:', listOfNumbers);

Lists can also store strings or other objects. For example:

// Make a list of strings.
var listOfStrings = ['a', 'b', 'c', 'd'];
print('List of strings:', listOfStrings);

Objects

Objects in JavaScript are dictionaries of key: value pairs. Make an object (or dictionary) using curly brackets {}, for example:

// Use curly brackets {} to make a dictionary of key:value pairs.
var object = {
  foo: 'bar',
  baz: 13,
  stuff: ['this', 'that', 'the other thing']
};
print('Dictionary:', object);
// Access dictionary items using square brackets.
print('Print foo:', object['foo']);
// Access dictionary items using dot notation.
print('Print stuff:', object.stuff);

Note that you can get a value from a dictionary by supplying the key. This example shows you how to do that for JavaScript objects. Later you'll learn how to do it for dictionaries that are on the Earth Engine server.

Functions

Functions are another way to improve code readability and reusability by grouping sets of operations. Define a function with the function keyword. Function names start with a letter and have a pair of parentheses at the end. Functions often take parameters which tell the function what to do. These parameters go inside the parentheses (). The set of statements making up the function go inside curly brackets. The return keyword indicates what the function output is. There are several ways to declare a function, but here we'll use something like this:

var myFunction = function(parameter1, parameter2, parameter3) {
  statement;
  statement;
  statement;
  return statement;
};

Let's consider the lines one by one. The first line creates a new function and assigns it to the variable myFunction. This variable could have been named anything. It defines how to call the function later. The terms in the parentheses after the function name (i.e. parameter1, parameter2, parameter3) are the parameter names and could have been named anything as well, though it's good practice to give them unique names that are different from the code outside the function. Whatever you name them, these are the names that function will use to refer to the values that are passed into the function when it is called. The value of a parameter once it's been passed into a function is called an argument. Although functions can use variables declared outside the function (global variables), function arguments are not visible outside the function. Functions can take as many parameters as you need, even zero. Here's a simple example of a function that just returns its argument:

// The reflect function takes a single parameter: element.
var reflect = function(element) {
  // Return the argument.
  return element;
};
print('A good day to you!', reflect('Back at you!'));

This is an example of a user-defined function. There are also lots of built-in Earth Engine functions. Explore the Code Editor Docs tab to learn about these built-in functions. Here's a very simple example of an Earth Engine function:

var aString = ee.Algorithms.String(42);

Earth Engine Objects and Methods

Now that you're comfortable with JavaScript, learn how to put JavaScript objects and primitives into Earth Engine containers for sending to the server and processing at Google.

Strings

For example, define a string, then put it into the ee.String() container to be sent to Earth Engine:

// Define a string, then put it into an EE container.
var aString = 'To the cloud!';
var eeString = ee.String(aString);
print('Where to?', eeString);

Numbers

Use ee.Number() to create number objects on the server. For example, use the Math.E JavaScript method to create a constant value on the server:

// Define a number that exists on the server.
var serverNumber = ee.Number(Math.E);
print('e=', serverNumber);

The ee.String() and ee.Number() methods are constructors. A constructor takes its argument (and possibly other parameters), puts it in a container, and returns the container and its contents as an Earth Engine object that you can manipulate in your code. Any constructor starting with ee returns an Earth Engine object.

Lists

To make a JavaScript list into an ee.List object on the server, you can put a JavaScript literal into a container as with numbers and strings.

// Make a sequence the hard way.
var eeList = ee.List([1, 2, 3, 4, 5]);

Since the ee.List objects only exist on the server, use Earth Engine provided functions to interact with them.

// Use a method on an ee.List to extract a value.
var value = sequence.get(2);
print('Value at index 2:', value);

Dictionaries

You can construct an Earth Engine Dictionary from a JavaScript object, as with strings, numbers and lists.

// Make a Dictionary on the server.
var dictionary = ee.Dictionary({
  e: Math.E,
  pi: Math.PI,
  phi: (1 + Math.sqrt(5)) / 2
});

// Get some values from the dictionary.
print('Euler:', dictionary.get('e'));
print('Pi:', dictionary.get('pi'));
print('Golden ratio:', dictionary.get('phi'));

// Get all the keys:
print('Keys: ', dictionary.keys());

In this example, observe that once you have an ee.Dictionary, you must use methods on the ee.Dictionary to get values.

Dates

Date objects are the way Earth Engine represents time and can be constructed from a string, a JavaScript Date, or using static methods provided by the ee.Date class.

// Define a date in Earth Engine.
var date = ee.Date('2015-12-31');
print('Date:', date);

// Get the current time using the JavaScript Date.now() method.
var now = Date.now();
print('Milliseconds since January 1, 1970', now);

// Initialize an ee.Date object.
var eeNow = ee.Date(now);
print('Now:', eeNow);

Casting

Sometimes, Earth Engine doesn't know the type of an object that gets returned from a method. You, as the programmer, know that the value variable in the previous example is a number object. But if you try to use the add() method of an ee.Number, you'll get an error like:

value.add is not a function

This is common with the get() function, which could return all sorts of Earth Engine objects. To correct it, use the ee.Number constructor to cast the result:

// Cast the return value of get() to a number.
print('No error:', ee.Number(value).add(3));