Stay organized with collectionsSave and categorize content based on your preferences.
This tutorial covers just enoughJavaScriptto get you started writing Earth Engine scripts. For more thorough JavaScript tutorials,
seethese Mozilla developer
resources. For an introduction to programming, with examples in JavaScript, seeEloquent JavaScript. For suggestions
on JavaScript coding style, see theGoogle JavaScript Style
Guide. In this tutorial, you're going to write JavaScript in the Earth EngineCode Editor. Before getting started,
usethe Code Editor guideto get familiar
with the Code Editor environment.
Hello World!
Time to write your first JavaScript for Earth Engine! In your Chrome browser, go tocode.earthengine.google.comand copy
the following into theCode Editor:
ClickRunand observe that 'Hello world!' is printed to theConsole 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:
It's good practice to put lots of comments in your code, to describe what you're trying
to do. It's also good to delete commented code that doesn't do anything anymore.
Both these practices will improve code readability.
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), withsingle quotes
preferred. Make a new string and store it in a variable calledgreetString:
Code Editor (JavaScript)
// Use single (or double) quotes to make a string.vargreetString='Ahoy there!';// Use parentheses to pass arguments to functions.print(greetString);
Numbers
Note that variables are defined with the keywordvar. Variables can also
store numbers:
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 thefunctionkeyword. Function names
start with a letter and have a pair of parentheses at the end. Functions often takeparameterswhich tell the function what to do. These parameters go inside the
parentheses(). The set of statements making up the function go inside curly
brackets. Thereturnkeyword indicates what the function output is. There
are several ways to declare a function, but here we'll use something like this:
Let's consider the lines one by one. The first line creates a new function and assigns
it to the variablemyFunction. 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 anargument. Although functions can use variables declared outside
the function (globalvariables), 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:
This is an example of a user-defined function. There are also lots of built-in Earth
Engine functions. Explore the Code EditorDocs
tabto learn about these built-in functions. Here's a very simple example of an
Earth Engine function:
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2023-10-06 UTC."],[[["\u003cp\u003eThis tutorial provides a basic introduction to JavaScript for use within the Google Earth Engine Code Editor.\u003c/p\u003e\n"],["\u003cp\u003eIt covers fundamental JavaScript concepts like variables, data types (strings, numbers, lists, objects), and functions.\u003c/p\u003e\n"],["\u003cp\u003eUsers are encouraged to utilize the Code Editor's features like the Console and Docs tabs for a better experience.\u003c/p\u003e\n"],["\u003cp\u003eEarth Engine programs consist of JavaScript statements, and the tutorial provides examples for basic operations.\u003c/p\u003e\n"],["\u003cp\u003eThe tutorial serves as a starting point for learning Earth Engine, with more advanced topics covered in subsequent tutorials.\u003c/p\u003e\n"]]],["This tutorial introduces basic JavaScript concepts within the Earth Engine Code Editor. Key actions include writing and running code, like `print('Hello World!');`, using comments (`//`), and defining variables with `var`. It covers data types such as strings (using quotes), numbers, lists (using `[]`), and objects (using `{}`). Functions are explained using `function`, with parameters and the `return` statement. It also highlights built-in Earth Engine functions and the location of their documentation.\n"],null,["# Introduction to JavaScript for Earth Engine\n\nThis tutorial covers just enough\n[JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/About_JavaScript)\nto get you started writing Earth Engine scripts. For more thorough JavaScript tutorials,\nsee [these Mozilla developer\nresources](https://developer.mozilla.org/en-US/docs/Web/JavaScript). For an introduction to programming, with examples in JavaScript, see\n[Eloquent JavaScript](http://eloquentjavascript.net/). For suggestions\non JavaScript coding style, see the\n[Google JavaScript Style\nGuide](http://google.github.io/styleguide/javascriptguide.xml). In this tutorial, you're going to write JavaScript in the Earth Engine\n[Code Editor](https://code.earthengine.google.com/). Before getting started,\nuse [the Code Editor guide](/earth-engine/guides/playground) to get familiar\nwith the Code Editor environment.\n\nHello World!\n------------\n\nTime to write your first JavaScript for Earth Engine! In your Chrome browser, go to\n[code.earthengine.google.com](https://code.earthengine.google.com/) and copy\nthe following into the [Code Editor](/earth-engine/guides/playground):\n\n### Code Editor (JavaScript)\n\n```javascript\nprint('Hello World!');\n```\n\nClick **Run** and observe that 'Hello world!' is printed to the\n[Console tab](/earth-engine/guides/playground#console-tab). The line above is a JavaScript\nstatement. In JavaScript, statements end in a semicolon. Earth Engine programs are made\nup of a set of statements like this one. You can prevent code from running without\ndeleting it by commenting it. One of the ways to comment out code is by putting two\nforward slashes `//` before the code that you don't want to run. For example:\n\n### Code Editor (JavaScript)\n\n```javascript\n// print('Hello World!');\n```\n\nIt's good practice to put lots of comments in your code, to describe what you're trying\nto do. It's also good to delete commented code that doesn't do anything anymore.\nBoth these practices will improve code readability.\n\nBasic JavaScript data types\n---------------------------\n\n### Strings\n\nUsing variables to store objects and primitives helps code readability. For example,\na variable that stores a string object is defined by single `'` or double\n`\"` quotes (but don't mix them), with\n[single quotes\npreferred](https://google.github.io/styleguide/javascriptguide.xml#Strings). Make a new string and store it in a variable called\n`greetString`:\n\n\n### Code Editor (JavaScript)\n\n```javascript\n// Use single (or double) quotes to make a string.\nvar greetString = 'Ahoy there!';\n// Use parentheses to pass arguments to functions.\nprint(greetString);\n```\n\n### Numbers\n\nNote that variables are defined with the keyword `var`. Variables can also\nstore numbers:\n\n### Code Editor (JavaScript)\n\n```javascript\n// Store a number in a variable.\nvar number = 42;\nprint('The answer is:', number);\n```\n\nIn this example, observe that when `print()` is given two arguments separated\nby commas, each argument is printed on a different line.\n\n### Lists\n\nDefine lists with square brackets `[]`. A list of numbers, for example:\n\n### Code Editor (JavaScript)\n\n```javascript\n// Use square brackets [] to make a list.\nvar listOfNumbers = [0, 1, 1, 2, 3, 5];\nprint('List of numbers:', listOfNumbers);\n```\n\nLists can also store strings or other objects. For example:\n\n\n### Code Editor (JavaScript)\n\n```javascript\n// Make a list of strings.\nvar listOfStrings = ['a', 'b', 'c', 'd'];\nprint('List of strings:', listOfStrings);\n```\n\n### Objects\n\nObjects in JavaScript are dictionaries of `key: value` pairs. Make an object\n(or dictionary) using curly brackets `{}`, for example:\n\n### Code Editor (JavaScript)\n\n```javascript\n// Use curly brackets {} to make a dictionary of key:value pairs.\nvar object = {\n foo: 'bar',\n baz: 13,\n stuff: ['this', 'that', 'the other thing']\n};\nprint('Dictionary:', object);\n// Access dictionary items using square brackets.\nprint('Print foo:', object['foo']);\n// Access dictionary items using dot notation.\nprint('Print stuff:', object.stuff);\n```\n\nNote that you can get a value from a dictionary by supplying the key. This example\nshows you how to do that for JavaScript objects. Later you'll learn how to do it for\ndictionaries that are on the Earth Engine server.\n\nFunctions\n---------\n\nFunctions are another way to improve code readability and reusability by grouping sets\nof operations. Define a function with the `function` keyword. Function names\nstart with a letter and have a pair of parentheses at the end. Functions often take\n*parameters* which tell the function what to do. These parameters go inside the\nparentheses `()`. The set of statements making up the function go inside curly\nbrackets. The `return` keyword indicates what the function output is. There\nare several ways to declare a function, but here we'll use something like this:\n\n### Code Editor (JavaScript)\n\n```javascript\nvar myFunction = function(parameter1, parameter2, parameter3) {\n statement;\n statement;\n statement;\n return statement;\n};\n```\n\nLet's consider the lines one by one. The first line creates a new function and assigns\nit to the variable `myFunction`. This variable could have been named\nanything. It defines how to call the function later. The terms in the parentheses after\nthe function name (i.e. parameter1, parameter2, parameter3) are the parameter names and\ncould have been named anything as well, though it's good practice to give them unique names\nthat are different from the code outside the function. Whatever you name them, these are\nthe names that function will use to refer to the values that are passed into the function\nwhen it is called. The value of a parameter once it's been passed into a function is\ncalled an *argument* . Although functions can use variables declared outside\nthe function (*global* variables), function arguments are not visible outside the\nfunction. Functions can take as many parameters as you need, even zero. Here's a simple\nexample of a function that just returns its argument:\n\n### Code Editor (JavaScript)\n\n```javascript\n// The reflect function takes a single parameter: element.\nvar reflect = function(element) {\n // Return the argument.\n return element;\n};\nprint('A good day to you!', reflect('Back at you!'));\n```\n\nThis is an example of a user-defined function. There are also lots of built-in Earth\nEngine functions. Explore the Code Editor [Docs\ntab](/earth-engine/guides/playground#api-reference-docs-tab) to learn about these built-in functions. Here's a very simple example of an\nEarth Engine function:\n\n### Code Editor (JavaScript)\n\n```javascript\nvar aString = ee.Algorithms.String(42);\n```\n\nIn the next section, learn more about [Earth Engine Objects\nand Methods](/earth-engine/tutorials/tutorial_js_02)."]]