How To Program In Javascript
Synthiam ARC lets you write JavaScript to control your robot and process data. Although JavaScript began as the language of the web, ARC uses it as a lightweight scripting language inside your project so you can read sensors, make decisions, and command robot skills.
Before you start
- ARC has IntelliSense: as you type, ARC shows suggestions to autocomplete functions, methods, and variables so you learn available features faster.
- ARC uses
print(): use it to log messages and inspect variables so you can verify what your code is doing step-by-step. - JavaScript executes top-to-bottom: your script runs in order unless you change flow with conditions, loops, or function calls.
- Spacing is less important than braces: in JavaScript, code blocks are defined by braces
{ }; whitespace is mainly for readability.
1) Showing text with print()
When 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 logic and follow execution.
print() calls — print variable values and which branch or loop your code takes.
// 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 a labeled container for a value so you can reuse it later. In scripting you often use var. (Modern JavaScript also has let and const, but var keeps examples simple for ARC.)
2.1 String variables (text)
A string is text, enclosed in double or single quotes: "like this" or 'like this'. Use strings for names, messages, 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 remain text
var roomNumberText = "101";
print("Room (as text): " + roomNumberText);
"10" makes it text, not the number 10. Text and numbers behave differently in comparisons and math.
2.2 Number variables
A number is for math: timers, distances, angles, speeds, percentages, etc. Numbers are written without 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 either true or false. Booleans are used frequently in IF statements and loop conditions.
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 represent "no value". JavaScript distinguishes:
null— intentionally set to nothing.undefined— typically means a variable 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 stores values in order. Think of it as boxes labeled 0, 1, 2, ... — the position is 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 (beginners should avoid mixing types 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] is the first item. 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
To operate on every item, use a loop.
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 stores related values under named properties — like fields on a form. Objects are extremely useful in robot scripting for grouping sensor readings, configuration, or state.
// 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 help keep related information together: sensor readings, current mode, last known position, configuration, and so on.
5) Conditions (IF statements)
An IF statement lets your script make decisions: "If this is true, do that; 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 (performs type conversion — avoid when learning)===strict equal (recommended — compares value and type)!=not equal!==strict not equal
=== and !== because they avoid confusing type conversions.
var a = 10;
var b = "10";
print("a == b: " + (a == b)); // true (type conversion)
print("a === b: " + (a === b)); // false (different types)
5.5 Combining conditions with AND / OR
Use logical operators to require multiple rules.
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 can create infinite execution if you forget an exit condition. While learning, always include a clear condition and use print() to monitor loop progress.
6.1 FOR loop (best for “repeat N times” or iterating an array)
A FOR loop has three parts: start, condition, and step.
// 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 while its condition is true. If that condition never becomes false, the loop never ends.
var tries = 0;
while (tries < 3) {
print("Try number: " + tries);
tries++;
}
print("Finished trying.");
6.3 DO / WHILE loop (runs at least once)
Use DO/WHILE when you want the body to execute before checking the condition.
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 the remainder of the current iteration and continues with the next.
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 call whenever needed. Functions reduce repetition and 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 so the same code can work with different values.
function greet(name) {
print("Hello, " + name + "!");
}
greet("DJ");
greet("World");
7.3 Returning a value
Use return to send a result back to the caller.
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 can be measured, searched, and modified with built-in methods.
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 as expected, follow a simple debugging process:
- Print where you are: add
print("Reached step 1"),print("Reached step 2"), etc. to trace flow. - Print values: log key variables before IF statements and inside loops.
- Simplify: temporarily remove robot commands and test logic with dummy values.
- Change one thing at a time: when multiple changes are made at once, it’s hard to know what caused a regression.
// 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
ARC's IntelliSense (autocomplete) is valuable while learning because:
- It shows function and property names so you don't have to memorize everything.
- It reduces typos, which are a major source of errors for beginners.
- It often displays parameter hints so you know what values a function expects.
13) Putting it together: “real script” style examples
The examples below show practical patterns you might use in ARC: configuration and state at the top, decisions, loops, and helper functions. Adapt these to your robot-specific ARC functions and skills.
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 your script interacts with hardware, sensors, network connections, or robot skills, operations can fail. A try / catch block lets you handle those errors gracefully so a single failure doesn't stop the entire script.
try. If an error occurs, execution jumps immediately to catch.
15.1 Basic try / catch structure
The simplest form has two parts: try for the risky code and catch for error handling.
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 an error occurs, JavaScript skips the rest of the try block and runs the catch block.
15.2 Why try / catch is important in ARC scripts
ARC scripts commonly interact with:
- Robot skills that may not be loaded
- Hardware that may be disconnected
- Sensors that may return invalid values temporarily
- Network connections that can drop or time out
Without try / catch, a single unexpected error can stop the script. With it, you can log the problem and continue safely.
15.3 Catching errors and continuing safely
A common pattern is to catch the error, log useful information, and use a safe fallback value.
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, keep the failure localized to a single iteration so the loop can continue.
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 and only wrap lines that can fail. That makes bugs easier to find.
15.5 Distinguishing different error situations
The error object in catch often contains a message. Inspect it to handle different problems differently.
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
Place try / catch inside a function to protect reusable logic and keep callers 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 — useful for cleanup.
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 — this makes debugging harder. - Ignoring the error message instead of printing it.
- Using
try / catchto hide logic bugs rather than fixing the root cause.
try / catch for unexpected runtime failures, not as a substitute for proper IF checks and validation.
15.9 Debugging with try / catch
When debugging, temporarily add more detail to catch blocks so you can inspect the error and continue testing.
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 makes Synthiam ARC scripts more robust, safer around hardware, and easier to debug when things go wrong.
print() to verify your script is doing exactly what you expect.