Syntax
At its most basic, the Javascript interpreter (ie. the engine that executes your code, such as your browser) runs your code line-by-line, starting from the top of your script file. Even with this simplification, we must ask: what is a line?
For Javascript, a line is something ending with a semicolon ;
. In principle you can put multiple 'lines' of code on a single line in your code editor and it doesn't matter, in the same way in written language a paragraph can be stuffed with sentences.
You don't have to end your lines with a semicolon, but many sensible people consider it good style.
Naming before use
A whole bunch of things are pre-defined as part of the language, or provided by the interpreter. If you want to use your own names for things (such as variables or functions), you have to declare them. Names must be simple: no spaces or exotic characters. It's often that "camel case" is used inOrderToCombineWordsTogether
. Less common in Javascript is "snake case" so_that_words_run_together
. It's up to you, but be consistent.
The case is usually important as well. If you call a variable AGE
you better well keep shouting AGE
in the rest of your code.
You'll get an error if you happen to use a name that is already defined or otherwise has special meaning in the language. You can check the list on MDN.
Variables
Code you write will always use data in some manner or another. It might be a set of coordinates of where a user pressed the screen, data to keep track of whether the user has finished the tutorial, or perhaps the subject line of an email to send. This is to say that data is pervasive and comes in many forms.
We need some way of indicating what data we want to work with in our code, some way of referencing it, or 'pointing at' the what we want to manipulate. We do so by assigning data to a variable.
You can think of a variable as a named signpost, which points to a particular place in the computer's memory. This has a few implications which are covered in Variables II.
In order to use a variable, you have to declare it in some way to let the interpreter know what you're on about. If you don't, you get an error along the line of "ReferenceError: ... is not defined".
Declare variables with the let
statement. In the below example, four variables were declared and each initialised with a starting value:
let touchCoordinateX = 20;
let weight = 50.41;
let subjectLine = 'Dear mum';
let hasUserFinishedTutorial = false;
You may see code examples using var
to declare a variable instead of let
. This is an older Javascript practice. Now one should use let
or const
(discussed later).
Scopes
Curly braces { }
are used to establish a section of code, almost like a paragraph is a grouping of sentences. A common programming mistake is having an opening {
but not having a corresponding closing }
. Always start what you finish.
Curly braces establish a scope. Generally speaking, variables you define within a scope have no meaning outside of that scope. This is particularly important for functions and control structures.
Example snippet of code to make your interpreter freeze:
console.log('Starting');
while (true) { // Loop the block defined by { } forever
console.log('...Still running');
}
When reading code, keep in mind that scoped code might conditionally run. Normally code will execute line-by-line, but as soon as there is a scoped block, it should give you pause to question when and under what circumstances the block will execute.
For example, take this if
block:
if (weight > 20) { // Expression: weight>20
console.log('Heavy'); // Runs if expression is true
} else {
console.log('Light'); // Runs if expression is false
}
The first block only runs if the expression (weight > 20
) is true. So if weight
is 21, you'll get "Heavy" printed tot he console. If it's false, the second block will run instead, printing out "Light".
Likewise if you put code inside a function, it will only run if the function is called:
function checkWeight() {
console.log('Alright');
}
In the absence of checkWeight()
being called, the console message will never print.
Comments
You can write comments in your code for yourself or your colleagues. This can just be some text prefixed with //
. It can be on the end of a line of code or on a line of its own. For longer comments, you might want to start with a /*
and end with */
. Anything between these markers is considered a comment. Examples:
/*
My awesome code
*/
// This function says "Hi"
let myFunction = function() {
console.log('Hi.'); // Print to console
};
Functions
A function is a reusable chunk of code that takes in some input and produces some output. Inputs are called parameters or arguments, the output is called the return value and we say that we want to call a function.
Here is an example of calling a function named 'greet', passing in three parameters:
greet('Thom', 'York', 41);
Like data, functions must be referenced somehow. We can explicitly name the function, or we can assign it to a variable:
function greet(firstName, lastName, age) {
// ...code goes here
}
const greet = (firstName, lastName, age) => {
// ...code goes here
}
Functions are sometimes associated with an object, and therefore need to be accessed using dot notation. The dot denotes that whatever comes next is part of what followed: a.b
means that b
is part of, or referenced from a
. You could imagine it as a tree structure, where b
branches off a
.
For example log
is a function that is referenced by the in-built console
object. We can't just call log
because it's not already defined, only the console
object is. To access it then, we use the dot notation:
console.log('Hi ' + lastName, + ', '+ firstName +', age '+ age);
A way of reading the dot notation above might be to say "calling console's 'log' function" or "calling 'log' which lives on 'console'". Objects typically have several functions available for use, with the object being a handy way of grouping them. You can see this for example by printing the object to the console:
// Print information about itself (!)
console.log(console);
You'll see that there are other functions like info
, error
, warn
and so on available.