I cannot teach you the whole of JavaScript in one lesson - and I wouldn't try, not even after a very strong cup of tea. The good news is you don't need the whole language to be useful. Once you know one programming language, the next one is mostly "ah, so *that's* how they spell a `FOR` loop."

This is a survival kit: the bits of syntax you'll see in every lesson from here on. If you already write JavaScript, skip ahead. If you've spent the last twenty years in SEU, settle in.

We'll type these into a file and run them with `node` later (Section 3). For now, just read them like you'd read a new RPG opcode.

Declaring variables

JavaScript is loosely typed. You don't say dcl-s count int(10) - you declare a name, and the type comes from whatever you put in it. It can even change later, though I wouldn't make a habit of that.

Use const for anything that won't be reassigned, and let for anything that will. They are both block-scoped, which is the sensible behaviour you'd expect from a modern language.

const appName = 'ingredients-app'; // a string - this binding cannot be reassigned
let quantity = 1000; // a number - this one can
quantity = 750;

const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];

const employee = {
  first: 'Nick',
  last: 'Litten',
  staffNumber: 1000,
};

You'll also see var in older examples (and in plenty of blog posts from the early Node.js years). It is function-scoped, it gets hoisted, and it has some sharp edges. New code in this course uses const and let. If you see var in a snippet on the internet, it still works - it's just not what I'd write today.

=, == and ===

This one catches everybody, so let's be precise:

=, == and ===
const myNumber = 1;

myNumber == '1'; // true - the string "1" is converted to a number
myNumber === '1'; // false - different types, no conversion
myNumber === 1; // true

Prefer ===

The automatic conversions behind == are a gift that keeps on giving, and not in a good way. (=== has a friend, !==, for "not equal, no conversion)

If, else, and curly braces

const status = 'OPEN';

if (status === 'OPEN') {
console.log('Take the order');
} else if (status === 'HOLD') {
console.log('Wait for the customer');
} else {
console.log('Nothing to do');
}

The curly braces { } are the same idea as BEGIN/END or a monitored block. Use them even for one-line branches - your future self will thank you.

Loops

These will feel very familiar.

let n = 3;

while (n > 0) {
  console.log('counting down', n);
  n -= 1; // same idea as n = n - 1
}

do {
  console.log('this always runs at least once');
} while (n > 0);

  for (let x = 1; x <= 5; x++) {
  console.log('pass', x);
}

For arrays, for...of walks the values (this is the one you want most of the time):

const days = ['Monday', 'Tuesday', 'Wednesday'];

for (const day of days) {
  console.log(day);
}

// or the array's own helper, with a callback:
  days.forEach((day, index) => {
  console.log(index, day);
});

For objects, for...in walks the keys - like ranging over the subfields of a data structure:

const employee = { first: 'Nick', last: 'Litten', staffNumber: 1000 };

for (const field in employee) {
  console.log(field + ' = ' + employee[field]);
}

That prints:

first = Nick
last = Litten
staffNumber = 1000

employee[field] is "the subfield whose name is in field."

Dot notation (`employee.first`) is what you use when you know the name already.

Functions - and functions that look like RPG subprocedures

A classic function declaration:

function printSomething(something) {
  console.log(something);
}

printSomething('Hello World'); // prints "Hello World"

And the same thing as an arrow function, which is the style you'll see most often in modern Node.js (we already used one earlier):

const printSomething = (something) => {
console.log(something);
};

printSomething('Hello World');

For a single expression you can drop the braces and the return:

const double = (n) => n * 2;
console.log(double(21)); // 42

Callbacks: functions as parameters

Here's the idea that makes Node.js tick, and the one that feels strangest if you've only written RPG. A function is a value. You can store it in a variable, and you can pass it to another function. That second function can call it later - a callback.

function repeat(num, callback) {
  for (let x = 1; x <= num; x++) {
    callback(x);
  }
}

function printSomething(something) {
  console.log(something);
}

repeat(5, printSomething);
// prints 1
// 2
// 3
// 4
// 5

You don't have to give the callback a name. An anonymous function is defined on the spot, just for that call:

repeat(5, function (n) {
  printSomething('call number ' + n);
});

// or, as an arrow function - this is the form we use in the rest of the course:
repeat(5, (n) => {
  printSomething('call number ' + n);
});

That pattern is everywhere: "when the SQL comes back, run this," "when the HTTP request arrives, run this." Earlier we dressed it up with async/await so it reads top-to-bottom again. Under the covers, it's still callbacks and the event loop.

A few small extras you'll trip over

Template literals - strings in backticks, with `${}` to drop a value in. Nicer than a pile of `+` signs:

const name = 'Nick';
console.log(`Hello, ${name}!`); // Hello, Nick!

null and undefined - undefined means "nobody has put anything here." null means "I deliberately put nothing here." They're different, which is the sort of thing JavaScript finds funny.

typeof tells you what you've got: typeof 1 is number, typeof '1' is string. Arrays sneakily report object, so use Array.isArray(value) for those.

console.log(...) is your DSPLY. It writes to stdout - the SSH terminal you're sitting in, or a job log if you submitted a batch job.

Try it, once Node.js is installed

After setting up Node.js, drop any of the snippets above into a file and run it:

node syntax-demo.js

Or just type node with no filename and you get a REPL (a live prompt). Type an expression, press Enter, see the result. Press Ctrl+D to leave. It's a very cheap way to settle an argument.

And if you'd like a proper walk through the language, the living references are [the Node.js docs] and [MDN's JavaScript guide]. I'd start there rather than with a book from a few years ago - JavaScript moves.

Right. You can now read the code in the rest of this course without squinting.

In the next module we'll talk about when to reach for Node.js, and we'll install it and type some of this for real.

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}
>