Matching Podcast Episode 432
Listen Along: Chit Chat Across the Pond Episode 432
You can also Download the MP3
A Little History and Context
When you click the
Run button, your code will execute. The output will appear in a new popup window (so allow popups from this page when your browser asks).
Let’s start in the traditional way – with a Hello World program.
In our playground, and only in our playground, the function for writing a line of output is
pbs.say(). So, in this case our code is very simple – we just want to output the string of text “Hello World!”, so we just need this one line of code:
(This code is pre-populated into the code region by default)
To run this simple little script click the
Run button. A new window will pop up with one line of output – the string Hello World!.
; character to represent the end of a statement. The exact spacing of things does not matter, as long as there is at least one space character between things that need to be separated from each other. Single statements can be spread over multiple lines.
Multiple statements can be grouped together by enclosing them between
A single-line comment starts with the symbols
//, everything on the line from those two slashes on is considered a comment.
A multi-line comment starts with the symbols
/* and ends with the symbols
*/. Those two sequences, and everything in between is interpreted as a comment. Comments of this kind can extend over multiple lines.
pbs.say('boo!'); // this is a single-line comment at the end of a line // this on the other hand is a single-line comment covering the entire line pbs.say('who?'); /* this is a multi-line comment on a single line */ /* This is a more normal use of the multi-line comment style. Why? because it spreads over multiple lines of course! */
There are an infinity of possible coding and commenting styles. The only cardinal rule is consistency – whatever way you choose to lay out your code: be consistent!
We’ll talk more about code layout later in the series, when we’ve learned more about code blocks. For now I’ll just say that, while you are free to lay out your code however you wish, and while the most important rule is to be consistent, you should probably adopt one of the standard(ish) styles in common use. All my examples will use a variant of the so-called K&R style (named for the authors of the legendary book The C Programming Language, Kernighan and Ritchie). True K&R uses more spaces than I do. I hate horizontal scrolling, so I cuddle my braces which is something K&R don’t do in their book.
There is no right answer, and all the popular styles have sound logic behind them. It’s all about which considerations you find most important, and what your brain finds the easiest to interpret. The goal is clarity: so if a style doesn’t look clear to you, don’t use it!
Even though there is no one right answer, that doesn’t stop programmers having religious wars over this stuff – put three programmers into a room, and you’ll get five opinions on the matter!
- The first character must be a letter, a dollar symbol (
$), or an underscore (
- The remainder of the name can contain those same symbols, as well as digits
- You can’t use reserved words as variable names – you can get a full list of reserved words here (as well as a list of words you should avoid)
These rules will ensure that all your variable names are valid, though there are valid variable names that break these rules.
To declare a variable, use the keyword
var, followed by a space, followed by a valid name, optionally followed by an equals symbol, another space, and a value, and always terminated with a
; character. For example:
// a variable declaration without a value var x; // a variable declaration with a value var y = 4;
You declare a variable once. Then you use it as often as you need (it’s actually a little more complicated than that, but we’ll ignore that complexity for now).
Variables can be used anywhere values can be used. The
pbs.say() function prints a value,so, we can pass it a variable and it will print the value contained in that variable:
var x = 100; pbs.say(x);
Variables can hold either literal values, or references to objects. For now, we’re going to ignore object references and focus on literals.
var a = 4; var b = -42; var c = 3.1415; var d = -4.56; var e = 0xff; // the hex value ff var f = 2.41e4; // 2.41 x 10^4 var g = -2.3e-3; // -2.3 x 10^-3
There are just two boolean literal values:
var x = true; var y = false;
Notice that there are no quotation marks around the boolean literals.
\). To include a backslash in a string you need to write it as
\\. If you do need to escape a quotation mark of either kind, you do so by prefixing it with a backslash, so
Two other escape characters you should know about are
\n for the newline character, and
\t for the tab character.
var a = "a simple string"; var b = 'another simple string'; var c = 'so, she said "look how easy it is to avoid escaping things sometimes!"'; var d = 'he replied, "but it\'s not always that simple!"'; var e = "line 1\nline 2\nline3";
Operators apply an action to one or more values or variables. We’ve already met one operator so far today,
=, which is the assignment operator. For reasons that will become clear later, you should get into the habit of mentally reading something like
x = 4 as
x is assigned the value of
4. Do not under any circumstances get into the dangerously bad habit of mentally reading that line as
In this instalment we’re just going to look at one string operator, and the numeric operators.
You can use it to concatenate literal strings, or strings stored in variables, e.g.
pbs.say("You've gotta have a bowl" + " of coco pops"); var vessel = 'bowl'; var food = 'coco pops'; pbs.say("You've gotta have a " + vessel + " of " + food); vessel = 'cup'; food = 'coffee'; pbs.say("You've gotta have a " + vessel + " of " + food);
++ operator adds one to the value it is applied to. In other words, the value is incremented. And similarly, the
-- operator subtracts one from the value it is applied to. The value is decremented.
var x = 4; pbs.say(x); x++; pbs.say(x);
The other arithmetic operators behave like you would probably expect:
- modulus (remainder after integer division)
- raise to the power of
Operators are applied in a given order, their order of precedence. For the arithmetic operators, that order is the same as you learned in maths class back in your school days – multiply and divide before you add and subtract. Just like in mathematics, you can ensure the order of precedence you want by using round brackets.
Very sensibly, the assignment operator has the lowest precedence. All the operations are completed before the value is assigned to the variable.
One confusing point is that the increment and decrement operators have a higher precedence than the multiplication and division operators.
Assignment Operators (Convenient Shortcuts)
We’ve already met the basic assignment operator,
=, but it’s not the only one.
The following assignment operators also exist, and you can think of them as shortcuts, as shown below:
x += y;is equivalent to
x = x + y;(works for both addition and concatenation)
x -= y;is equivalent to
x = x - y;
x *= y;is equivalent to
x = x * y;
x /= y;is equivalent to
x = x / y;
x %= y;is equivalent to
x = x % y;
x **= y;is equivalent to
x = x ** y;
Concatenation or Addition?
+ symbol is used for both string concatenation and addition. How do you know which one will happen? If there is a string on either side of the plus, concatenation will happen.
This behaviour is quite logical, and most of the time, you get the behaviour you want and expect, but there are some subtleties, as illustrated in the examples below;
pbs.say(1 + 2); var x = 4; var y = 5; pbs.say(x + y); var z = '$'; pbs.say("the price was $" + x); pbs.say(4 + '5'); pbs.say('4' + '5'); pbs.say(true + false); pbs.say(true + 4); pbs.say(false + 4); var a = true; pbs.say("a is " + a);
Notice that the boolean literals are treated as numbers, with
false being treated as 0, and
Forcing the Types
You can force an explicit conversion from one type to another using a number of standard functions:
- Converts a value to a string – useful if you want to concatenate numbers instead of adding them.
- Converts a value to a whole number (i.e. an integer).
- Converts a value to a decimal (AKA floating point) number.
- Converts a value to a boolean value (
A lot of the time these conversions have a sensible outcome – it makes sense to convert the string
"34" to the number
34, and the number
3.1415 to the integer
NaN, which stands for not a number (though under the hood,
NaN is considered a number, go figure!).
NaN is also used to represent infinity. So when you divide by zero, you get
NaN. When you apply any arithmetic operator to
NaN, the result is
NaN + 4 is
You’ll also get
NaN at times you might hope not to. Sadly,
parseInt('four') gives you
parseInt('$4') gives you
parseInt('4 things') gives you
Every value collapses into either
false when needed. Anything can be turned to a string, even if it isn’t always a very meaningful string. The rules for collapsing down to boolean values are a little complex, so we’ll leave them be until the next instalment.
var x = 4; var y = 2; pbs.say(x + y); // default behaviour pbs.say(String(x) + String(y)); // force concatenation var a = '4'; var b = '2'; pbs.say(a + b); // default behaviour pbs.say(parseInt(a) + parseInt(b)); // force addition
undefined. When a variable has no value, it is said to be undefined. So, if you try use a variable x before you declare it and give it a value, it will evaluate to
You can also explicitly set a variable to be
undefined using the assignment operator.
pbs.say(a); var a = 42; pbs.say(a); a = undefined; pbs.say(a);
So far we’ve learned how to store values in variables, and, how to manipulate values with string and arithmetic operators. Variables and operators are core concepts in all programming languages. The exact syntax will vary from language to language, but the concept is universal.
Another one of these universal concepts is decision making or branching, and that’s what we’ll be looking at in the next instalment. We’ll be learning about comparison operators, boolean operators, and finally,
Join the Community
Find us in the PBS channel on the Podfeet Slack.