How To Program In Javascript
Synthiam ARC lets you write JavaScript to control your robot and work with data. JavaScript is the language of the web, but ARC uses it as a scripting language inside your project.
Before you start
- ARC has IntelliSense: as you type, ARC can show a dropdown list of suggestions to autocomplete functions and variables.
- ARC uses
print(): use it to debug and to see what your code is doing step-by-step. - JavaScript runs top-to-bottom: just like reading a book, the script is executed in order unless you use conditions or loops.
- Spacing matters less than braces: in JavaScript, braces
{ }control blocks of code.
1) Showing text with print()
When you are learning to program, the most important skill is being able to see what your code is doing.
In ARC, print() writes messages to the output/log window so you can verify your logic.
print() calls. Print your variables. Print which path your code took.
// Print a simple message
print("Hello from Synthiam ARC!");
// Print multiple pieces of information by building a string
var robotName = "JD";
print("Robot name is: " + robotName);
2) Variables
A variable is like a labeled box where you store a value so you can use it later.
In JavaScript, you often create variables using var. (Modern JavaScript also has let and const,
but var is common in many scripting environments and keeps this guide simple.)
2.1 String variables (text)
A string is text. Strings go inside quotes: "like this" or 'like this'.
Use strings for things like names, phrases, or commands.
// Create a string variable
var greeting = "Hello!";
// Print it
print(greeting);
// Change it later (variables can be updated)
greeting = "Hi again!";
print(greeting);
// Combine strings using +
var firstName = "DJ";
var message = "Welcome, " + firstName + "!";
print(message);
// Strings can include numbers, but they are still text
var roomNumberText = "101";
print("Room (as text): " + roomNumberText);
"10" in a variable, that is text, not the number 10.
Text and numbers behave differently.
2.2 Number variables
A number is used for math: counting, timers, distances, angles, speeds, percentages, etc. Numbers do not use quotes.
// Create number variables
var speed = 50;
var angle = 90;
var batteryVoltage = 7.4;
// Print numbers
print("Speed is: " + speed);
print("Angle is: " + angle);
print("Battery voltage is: " + batteryVoltage);
// Do math
var a = 10;
var b = 3;
print("a + b = " + (a + b));
print("a - b = " + (a - b));
print("a * b = " + (a * b));
print("a / b = " + (a / b));
// Update a variable using its current value
var count = 0;
count = count + 1;
count = count + 1;
print("Count is now: " + count);
// Shorthand updates
count += 5; // same as count = count + 5
print("Count after += 5: " + count);
2.3 Boolean variables (true/false)
A boolean is a value that is either true or false.
Booleans are used constantly in IF statements and loops.
var isConnected = true;
var isMoving = false;
print("Connected? " + isConnected);
print("Moving? " + isMoving);
2.4 Null and undefined (empty / not set)
Sometimes you want a variable to be "empty". JavaScript has a few concepts here:
nullusually means “I intentionally set this to nothing.”undefinedusually means “this was never assigned a value.”
var value; // not assigned yet -> undefined
print("value = " + value);
value = null; // intentionally empty
print("value = " + value);
3) Arrays (lists of values)
An array is a list of values in a specific order. Think of it like a row of boxes: box 0, box 1, box 2, and so on. The position number is called the index, and indexes start at 0.
3.1 Creating arrays
// An array of numbers
var speeds = [10, 20, 30, 40];
// An array of strings
var phrases = ["Hello", "How are you?", "Goodbye"];
// An array can mix types (but beginners should avoid mixing until comfortable)
var mixed = [1, "two", true, null];
print("speeds: " + speeds);
print("phrases: " + phrases);
3.2 Accessing items by index
var colors = ["red", "green", "blue"];
print("First color (index 0): " + colors[0]);
print("Second color (index 1): " + colors[1]);
print("Third color (index 2): " + colors[2]);
colors[1] thinking it means the first item.
It does not. The first item is colors[0].
3.3 Changing items and adding items
var numbers = [5, 10, 15];
// Change an existing item
numbers[1] = 999;
print("After change: " + numbers);
// Add an item to the end
numbers.push(20);
print("After push: " + numbers);
// Remove the last item
var last = numbers.pop();
print("Popped item: " + last);
print("After pop: " + numbers);
// How many items are in the array?
print("Count = " + numbers.length);
3.4 Looping through an array
Often you want to do something to every item in a list. A loop is perfect for that.
var distances = [12, 9, 7, 15];
for (var i = 0; i < distances.length; i++) {
print("Item " + i + " is: " + distances[i]);
}
4) Objects (grouping related values)
An object lets you store related values together under names (called properties). Think of it like a form with labeled fields.
// Create an object describing a robot
var robot = {
name: "JD",
battery: 7.4,
isOnline: true
};
print("Name: " + robot.name);
print("Battery: " + robot.battery);
print("Online: " + robot.isOnline);
// Update a property
robot.battery = 7.2;
print("Battery now: " + robot.battery);
Objects are extremely useful in robot scripting because you often want to keep related information together: sensor readings, current mode, last known position, configuration, etc.
5) Conditions (IF statements)
An IF statement lets your script make decisions. It means: “If something is true, do this. Otherwise, do something else.”
5.1 Basic IF
var battery = 7.1;
if (battery > 7.3) {
print("Battery is strong.");
}
if (battery <= 7.3) {
print("Battery is getting low.");
}
5.2 IF / ELSE
var distanceCm = 25;
if (distanceCm < 20) {
print("Obstacle is close! Stop or turn.");
} else {
print("Path is clear enough.");
}
5.3 IF / ELSE IF / ELSE
var tempC = 22;
if (tempC < 10) {
print("It's cold.");
} else if (tempC < 25) {
print("It's comfortable.");
} else {
print("It's hot.");
}
5.4 Comparisons you will use constantly
>greater than<less than>=greater than or equal<=less than or equal==equal (try to avoid when learning)===strict equal (recommended)!=not equal!==strict not equal
=== and !== because they are less confusing.
They compare both value and type.
var a = 10;
var b = "10";
print("a == b: " + (a == b)); // true (because JavaScript tries to convert types)
print("a === b: " + (a === b)); // false (number is not the same type as string)
5.5 Combining conditions with AND / OR
Sometimes you need more than one rule.
var batteryOk = true;
var pathClear = false;
// AND: both must be true
if (batteryOk && pathClear) {
print("Go forward.");
} else {
print("Do not go forward (battery or path is not good).");
}
// OR: either can be true
var hasWifi = false;
var hasUart = true;
if (hasWifi || hasUart) {
print("We have at least one connection method.");
} else {
print("No connection available.");
}
// NOT: flips true/false
var isBlocked = true;
if (!isBlocked) {
print("Not blocked.");
} else {
print("Blocked.");
}
6) Loops (repeat code)
A loop repeats code. Loops are powerful, but they can also cause problems if you accidentally create a loop that never ends.
When you are learning, always include a clear exit condition, and use print() to watch what the loop is doing.
6.1 FOR loop (best for “repeat N times” or “walk through an array”)
A FOR loop has 3 parts:
- Start: create a counter variable (usually
i). - Condition: keep looping while this is true.
- Step: how the counter changes each loop.
// Print 0 through 4
for (var i = 0; i < 5; i++) {
print("i = " + i);
}
// Count down
for (var n = 5; n > 0; n--) {
print("Countdown: " + n);
}
print("Done!");
6.2 WHILE loop (best for “repeat until something changes”)
A WHILE loop repeats as long as the condition stays true. If the condition never becomes false, it will run forever.
var tries = 0;
while (tries < 3) {
print("Try number: " + tries);
tries++;
}
print("Finished trying.");
6.3 DO / WHILE loop (runs at least once)
Sometimes you want the code to run once before checking the condition (for example: ask a question, then repeat only if needed).
var x = 0;
do {
print("This runs at least once. x=" + x);
x++;
} while (x < 3);
6.4 break and continue
break exits the loop immediately. continue skips to the next loop iteration.
for (var i = 0; i < 10; i++) {
if (i === 5) {
print("Skipping 5");
continue;
}
if (i === 8) {
print("Stopping at 8");
break;
}
print("i = " + i);
}
7) Functions (reusable code)
A function is a named block of code you can run whenever you want. Functions help you avoid repeating yourself, and they make scripts easier to read.
7.1 A simple function
function sayHello() {
print("Hello!");
}
sayHello();
sayHello();
7.2 Function parameters (inputs)
Parameters let you pass information into a function.
function greet(name) {
print("Hello, " + name + "!");
}
greet("DJ");
greet("World");
7.3 Returning a value
Some functions produce a result. return sends a value back to whoever called the function.
function add(a, b) {
return a + b;
}
var result = add(5, 7);
print("Result is: " + result);
7.4 Early exit with return
function divide(a, b) {
if (b === 0) {
print("Cannot divide by zero.");
return 0;
}
return a / b;
}
print("10 / 2 = " + divide(10, 2));
print("10 / 0 = " + divide(10, 0));
8) Useful string tools
Strings are more than just text. You can measure them, search them, and modify them.
var text = "Synthiam ARC";
// Length
print("Length: " + text.length);
// Convert to uppercase/lowercase
print(text.toUpperCase());
print(text.toLowerCase());
// Check if it contains something
print("Contains 'ARC'? " + (text.indexOf("ARC") !== -1));
// Get a piece of the string
print("First 8 chars: " + text.substring(0, 8));
9) Useful number tools
// Rounding
var v = 3.14159;
print("Round: " + Math.round(v));
print("Floor: " + Math.floor(v));
print("Ceil: " + Math.ceil(v));
// Clamp a number (keep it within a range)
function clamp(value, min, max) {
if (value < min) {
return min;
}
if (value > max) {
return max;
}
return value;
}
print("Clamp 150 to 0..100: " + clamp(150, 0, 100));
10) Reading errors and avoiding common mistakes
10.1 Missing quotes around text
// WRONG: Hello is treated like a variable name (and will likely cause an error)
// var msg = Hello;
// RIGHT:
var msg = "Hello";
print(msg);
10.2 Forgetting to update the loop variable
// DANGEROUS: If you forget tries++, this can loop forever.
var tries = 0;
while (tries < 3) {
print("tries=" + tries);
tries++;
}
10.3 Using the wrong equality operator
var n = 5;
// Use === for clarity
if (n === 5) {
print("n is exactly 5");
}
11) Debugging strategy in ARC (the practical way)
When your script doesn't behave the way you expect, do this:
- Print where you are: add
print("Reached step 1"),print("Reached step 2"), etc. - Print values: print variables right before your IF statements and inside your loops.
- Simplify: temporarily remove robot commands and test logic with dummy values first.
- Change one thing at a time: if you change three things and it breaks, you won't know which change caused it.
// Example debugging pattern
var distanceCm = 18;
print("distanceCm=" + distanceCm);
if (distanceCm < 20) {
print("Decision: obstacle is close");
} else {
print("Decision: path is clear");
}
12) How ARC IntelliSense helps you
Synthiam ARC includes IntelliSense (autocomplete). This matters a lot when you are learning because:
- It can show you function names so you don’t have to memorize everything.
- It reduces typos (typos are a huge source of beginner frustration).
- It often shows hints about parameters (what you need to pass into a function).
13) Putting it together: “real script” style examples
The next examples are designed to look like how you might actually write scripts in ARC: variables at the top, decisions, loops, and helper functions. They do not assume any specific robot skill, so you can adapt the patterns to whichever ARC methods you are using.
13.1 Example: basic state + decisions
// Configuration
var minSafeDistanceCm = 20;
// State
var isRunning = true;
var lastDistanceCm = 0;
// Pretend we read a sensor (replace this with your ARC sensor call)
lastDistanceCm = 18;
print("Last distance: " + lastDistanceCm);
if (lastDistanceCm < minSafeDistanceCm) {
print("Obstacle detected. Choose a different action.");
isRunning = false;
} else {
print("Safe to continue.");
}
13.2 Example: loop through a list of steps
// A simple list of "steps" you want to run
var steps = ["Scan", "MoveForward", "Stop", "Speak"];
// Run each step in order
for (var i = 0; i < steps.length; i++) {
var step = steps[i];
print("Running step: " + step);
// Decision per step
if (step === "Scan") {
print("Pretend: scanning sensors...");
} else if (step === "MoveForward") {
print("Pretend: moving forward...");
} else if (step === "Stop") {
print("Pretend: stopping...");
} else if (step === "Speak") {
print("Pretend: speaking...");
} else {
print("Unknown step: " + step);
}
}
13.3 Example: while loop with safety limit
// Repeat until a condition changes, but don't run forever
var attempts = 0;
var maxAttempts = 10;
var targetFound = false;
while (!targetFound && attempts < maxAttempts) {
print("Searching... attempt " + attempts);
// Pretend condition changes (replace with real sensor/vision results)
if (attempts === 3) {
targetFound = true;
print("Target found!");
}
attempts++;
}
if (!targetFound) {
print("Target not found after " + maxAttempts + " attempts.");
}
14) Quick reference (copy/paste friendly)
// String
var s = "text";
// Number
var n = 123;
// Boolean
var ok = true;
// Array
var arr = [1, 2, 3];
arr.push(4);
var first = arr[0];
// Object
var obj = { name: "JD", speed: 50 };
var name = obj.name;
// IF
if (n > 100) {
print("big");
} else {
print("small");
}
// FOR
for (var i = 0; i < 5; i++) {
print(i);
}
// WHILE
var x = 0;
while (x < 3) {
print(x);
x++;
}
// Function
function hello(who) {
print("Hello " + who);
}
hello("ARC");
15) Error handling with try / catch
When you write scripts that talk to hardware, sensors, network connections, or robot skills, things can occasionally fail. A device might be disconnected, a value might be missing, or a command might not be available at the moment it runs.
A try / catch block lets you safely attempt an operation and handle errors without crashing or stopping the rest of your script.
try.
If an error occurs, JavaScript immediately jumps to catch.
15.1 Basic try / catch structure
The simplest form has two parts:
try— code you want to attemptcatch— code that runs only if an error occurs
try {
print("About to run risky code...");
// Example: something goes wrong
var result = unknownVariable + 1;
print("This line will not run if an error happens above.");
} catch (ex) {
print("An error occurred.");
print("Error message: " + ex);
}
If the error occurs, JavaScript skips the remaining lines inside try and immediately
runs the catch block.
15.2 Why try / catch is important in ARC scripts
In Synthiam ARC, your script often interacts with:
- Robot skills that may not be loaded
- Hardware that may be disconnected
- Sensors that may temporarily return invalid data
- Network connections that can drop or time out
Without try / catch, a single unexpected error can stop the entire script.
With it, you can detect the problem, log it, and keep the robot running safely.
15.3 Catching errors and continuing safely
A common pattern is to catch the error, print useful information, and then continue with a safe fallback.
var distanceCm = 0;
try {
// Replace this with a real ARC sensor call
distanceCm = GetADC(0);
print("Distance read: " + distanceCm);
} catch (ex) {
print("Failed to read distance sensor.");
print("Reason: " + ex);
// Safe fallback value
distanceCm = 999;
}
if (distanceCm < 20) {
print("Obstacle detected.");
} else {
print("No obstacle detected.");
}
15.4 Using try / catch inside loops
When a loop runs many times, you usually want a single failure to affect only that iteration, not stop the entire loop.
for (var i = 0; i < 5; i++) {
try {
print("Loop iteration: " + i);
// Example of a risky operation
var value = readSensorValue(i);
print("Sensor value: " + value);
} catch (ex) {
print("Error on iteration " + i);
print("Details: " + ex);
// Continue with next iteration
}
}
try block as small as possible.
Only wrap the lines that can actually fail. This makes bugs easier to find.
15.5 Distinguishing different error situations
The error object passed into catch often contains a message.
You can inspect it and react differently depending on the problem.
try {
ControlCommand("Some Skill", "DoSomething");
} catch (ex) {
var msg = ex.toString();
if (msg.indexOf("not found") !== -1) {
print("The robot skill is not loaded.");
} else if (msg.indexOf("disconnected") !== -1) {
print("Hardware is disconnected.");
} else {
print("Unknown error occurred:");
print(msg);
}
}
15.6 try / catch with functions
You can place try / catch inside a function to protect reusable logic.
This keeps calling code clean and simple.
function safeDivide(a, b) {
try {
if (b === 0) {
throw "Division by zero";
}
return a / b;
} catch (ex) {
print("safeDivide error: " + ex);
return 0;
}
}
print("10 / 2 = " + safeDivide(10, 2));
print("10 / 0 = " + safeDivide(10, 0));
15.7 finally (always runs)
An optional finally block runs whether an error occurred or not.
This is useful for cleanup code.
try {
print("Starting operation...");
// Risky operation here
} catch (ex) {
print("Operation failed: " + ex);
} finally {
print("Cleanup or final steps always run.");
}
15.8 Common beginner mistakes with try / catch
- Wrapping the entire script in one huge
tryblock (makes debugging harder) - Ignoring the error message instead of printing it
- Using
try / catchto hide logic bugs instead of fixing them
try / catch to handle unexpected runtime failures,
not to replace proper IF checks and validation.
15.9 Debugging with try / catch
When debugging a complex script, temporarily add more detail to your catch blocks.
try {
print("Before risky code");
riskyOperation();
print("After risky code");
} catch (ex) {
print("ERROR CAUGHT");
print(ex);
print("Script continued safely.");
}
Using try / catch correctly allows your Synthiam ARC scripts to be more robust,
safer around hardware, and easier to debug when something unexpected happens.
print() to verify your script is doing exactly what you think it’s doing.