For eighteen lessons you have been writing PRINT, IF and FOR. Maybe one question is still not answered: when do you write real code, the kind that programmers use at work?
The answer: what you have been writing is already almost real code. The pseudocode in these lessons was made to look like JavaScript and Python on purpose. Those are two widely used programming languages. For example: item numbers in a list start at 0, text is written in quotes, and, as in Python, text cannot be added directly to a number. So what you need to learn now is not a new way of thinking. Only the words are new, and a few rules for writing are different. In this lesson you see one program written in three languages. In the exercise, you run your first JavaScript.
A small dictionary
Almost every word in pseudocode has a direct partner in JavaScript and in Python:
| Pseudocode | JavaScript | Python |
|---|---|---|
PRINT "Total:", total |
console.log("Total:", total); |
print("Total:", total) |
READ name |
let name = prompt(); |
name = input() |
total ← 0 |
let total = 0; |
total = 0 |
IF total > 50 THEN |
if (total > 50) { |
if total > 50: |
ELSE |
} else { |
else: |
END IF |
} |
(the next line is no longer moved to the right) |
WHILE i < 3 DO |
while (i < 3) { |
while i < 3: |
FOR i ← 1 TO 3 |
for (let i = 1; i <= 3; i++) { |
for i in range(1, 4): |
FUNCTION deliveryFee(total) |
function deliveryFee(total) { |
def deliveryFee(total): |
RETURN 0 |
return 0; |
return 0 |
= for comparing |
=== |
== |
≠ |
!== |
!= |
DIV |
Math.floor(a / b) |
// |
MOD |
% (see below) |
% |
LENGTH(cart) |
cart.length |
len(cart) |
APPEND(cart, 5) |
cart.push(5); |
cart.append(5) |
TRUE, FALSE |
true, false |
True, False |
AND, OR and NOT become &&, || and ! in JavaScript. In Python they become and, or and not.
JavaScript's % matches MOD as long as both numbers are positive. With negative numbers, the results differ: -7 MOD 2 is 1, like % in Python, but -7 % 2 in JavaScript is -1. So in JavaScript, check whether x is odd with x % 2 !== 0, not x % 2 === 1.
READ is a little different. prompt() in the browser and input() in Python always give text, even when a number is typed. To calculate with it, you must first turn that text into a number: Number(prompt()) in JavaScript, int(input()) in Python. READ in pseudocode does that by itself. One more thing: prompt() exists only in the browser. When a JavaScript program runs in Node.js (JavaScript outside the browser), it stops at prompt() with the message ReferenceError: prompt is not defined. In Node.js, input is read with the readline module, ready-made code that comes with Node.js.
One program, three languages
Here is the delivery fee program from earlier lessons, in pseudocode. It adds up three shopping prices, then prints the total and the delivery fee:
FUNCTION deliveryFee(total)
IF total > 50 THEN
RETURN 0
END IF
RETURN 10
END FUNCTION
cart ← [15, 22, 8]
total ← 0
FOR i ← 0 TO LENGTH(cart) - 1
total ← total + cart[i]
END FOR
PRINT "Total:", total
PRINT "Delivery:", deliveryFee(total)
In JavaScript:
function deliveryFee(total) {
if (total > 50) {
return 0;
}
return 10;
}
let cart = [15, 22, 8];
let total = 0;
for (let i = 0; i < cart.length; i++) {
total = total + cart[i];
}
console.log("Total:", total);
console.log("Delivery:", deliveryFee(total));
In Python:
def deliveryFee(total):
if total > 50:
return 0
return 10
cart = [15, 22, 8]
total = 0
for i in range(0, len(cart)):
total = total + cart[i]
print("Total:", total)
print("Delivery:", deliveryFee(total))
All three print the same thing:
Total: 45
Delivery: 10
Read the three programs line by line, and match them with the dictionary above. Three things change shape:
←becomes=. JavaScript also addsletin front of a variable the first time that variable is made.- In JavaScript, a condition is written inside brackets:
if (total > 50). - In JavaScript, a block is closed with
}. In Python, a block is the lines that are indented (moved to the right), and the block ends when the next line is no longer indented.
So in Python, indenting is not only for tidiness: the indented lines are what is inside the block.
Where a loop ends
FOR i ← 1 TO 3 runs for 1, 2 and 3. The end number, 3, is included. JavaScript writes the end as a condition: for keeps going while i <= 3 is TRUE, and i++ adds 1 to i at the end of each round. Python is different: range(1, 4) stops before 4, so its end number is not included. These three loops print the same thing:
FOR i ← 1 TO 3
PRINT "Round", i
END FOR
for (let i = 1; i <= 3; i++) {
console.log("Round", i);
}
for i in range(1, 4):
print("Round", i)
Round 1
Round 2
Round 3
For a loop that goes through the items of a list, the pattern is always the same:
- Pseudocode writes the last item number:
TO LENGTH(cart) - 1. - JavaScript writes a condition that stops before the length of the list:
i < cart.length. - Python writes the length of the list itself,
range(0, len(cart)), because the end number ofrangeis not included.
There are three ways to write it but one result: the loop goes from number 0 to the last item number.
When you do not need the item numbers, JavaScript and Python have a shorter way. for (const price of cart) in JavaScript and for price in cart in Python give the items of cart one by one to price. So there is no end number for the loop, like LENGTH(cart) - 1, that you could write wrong. With total = total + price inside, the total is still 45.
Commas and the plus sign
A comma in PRINT, console.log and print works the same way: the parts are printed with one space between them. What differs is the plus sign, when text is added to a number:
price ← 5
PRINT "Price:", price
PRINT "Price:" + TEXT(price)
let price = 5;
console.log("Price:", price);
console.log("Price:" + price);
price = 5
print("Price:", price)
print("Price:" + str(price))
Price: 5
Price:5
Look at the third line of each program. In pseudocode, the number must first be turned into text with TEXT(price). Python needs the same, with str(price). Without str, Python stops with TypeError: can only concatenate str (not "int") to str. It means the same as the message "text can't be added to a number directly" that you know from pseudocode. JavaScript shows no error at all. It turns 5 into text without telling you, and joins it to the text in front of it with no space. Because there is no error, a number that gets joined when it should have been added is often found only when someone reads the result.
In real code, the usual way to put a number inside text is a template literal in JavaScript and an f-string in Python. A template literal is written between backticks (the sign left of the 1 key on many keyboards), not quotes. Each ${...} inside it is replaced with its value, so ${price} becomes 5. An f-string starts with the letter f, and each {...} inside it is replaced with its value. The number does not need to be turned into text first:
let price = 5;
let count = 3;
console.log(`${count} x ${price} = ${price * count}`);
price = 5
count = 3
print(f"{count} x {price} = {price * count}")
3 x 5 = 15
So there are three ways to put a number in text:
- A comma: the easiest, when one space between the parts is fine.
- The plus sign, with
TEXT(...)orstr(...): the pseudocode and Python way. In JavaScript, forgetting to turn the number into text gives no error, so take care. - A template literal or an f-string: the usual choice in real code, especially when there are several values in the middle of the text.
The rules for quotes are looser in JavaScript and Python. The pseudocode here uses only double quotes: "Hello". JavaScript and Python accept both single and double quotes, 'Hello' and "Hello", as long as the opening quote and the closing quote are the same kind.
⚠️ Mixed up between three languages
Once you start writing JavaScript or Python, the habits of that language are easily carried into pseudocode, and the reverse happens too.
letandconsole.logcarried into pseudocode.let total = 0stops with the message "Line 1: pseudocode has nolet." The advice: "A variable is set straight away, withoutlet: writetotal ← 0."console.log("Total:", total)stops with the message "Line 2: pseudocode uses PRINT, notconsole.log." The message also gives the line to write instead,PRINT "Total:", total.===and!==in pseudocode.IF total === 50 THENstops with the message "Line 2: pseudocode uses=, not===." For "not equal to", replace!==with≠or!=.++in pseudocode.count++stops with the message "Line 2: pseudocode has no++." Writecount ← count + 1.%,&&and||in pseudocode.%stops with the message "Line 1: pseudocode uses MOD, not%." The same goes for&&and||: "Line 3: pseudocode uses AND, not&&." and "Line 2: pseudocode uses OR, not||."- A curly bracket after
IF.IF total > 50 {stops with the message "Line 2: the IF condition must be followed by THEN. Not a curly bracket." - The
TOend carried into JavaScript.for (let i = 0; i <= cart.length; i++)asks forcart[3], an item that does not exist. JavaScript does not stop with an error. It givesundefined(no value), the total becomesNaN(not a number), andTotal: NaNis printed. Use<, not<=. - The
TOend carried into Python.range(1, 3)only runs for 1 and 2. For 1 to 3, add one to the end:range(1, 4). input()used directly as a number. In Python,input()always gives text, soprice + 2stops withTypeError: can only concatenate str (not "int") to str. Writeprice = int(input()).
TL;DR: JavaScript and Python use the same ideas as pseudocode. Only the words change: PRINT becomes console.log (JavaScript) or print (Python), and ← becomes =. END IF becomes } in JavaScript. In Python, a block ends when the lines stop being indented (moved to the right). The end number of FOR ... TO is included, but the end number of Python's range is not. JavaScript writes the end as a condition, i <= 3 or i < cart.length. A comma between the printed parts gives one space in all three languages. Text plus a number is an error in pseudocode and Python. JavaScript shows no error: it joins the number to the text with no space.
⚡ New words, the same thinking
Guess first: in JavaScript, is PRINT "Total:", total written console.log("Total:", total); or print("Total:", total)?
console.log("Total:", total);. print("Total:", total) is Python.
Meaning: The pseudocode here was made to look like two real programming languages, JavaScript and Python, on purpose. Almost every pseudocode word has a direct partner. ← becomes =, and JavaScript adds let the first time a variable is made: let total = 0;. IF becomes if. END IF becomes } in JavaScript. In Python, a block ends when the lines stop being indented (moved to the right).
⚡ Where a loop ends
Write:
for (let i = 1; i <= 3; i++) {
console.log("Round", i);
}
Guess first: in Python, the same loop is written for i in range(1, 4):. If the end is written as 3, range(1, 3), which numbers does the loop run for?
Only 1 and 2. The end number of range is not included, so for 1 to 3 you write range(1, 4).
Meaning: The code above is FOR i ← 1 TO 3 in JavaScript, and it runs for 1, 2 and 3. for starts from let i = 1, keeps going while i <= 3 is TRUE, and i++ adds 1 to i at the end of each round. So in pseudocode the end number is included, and in JavaScript the end is written as a condition.
⚡ Text plus a number
Meaning: A comma in PRINT, console.log (JavaScript) and print (Python) gives one space in all three. The plus sign differs. Suppose price holds 5. For "Price:" + price, pseudocode needs TEXT(price) and Python needs str(price), which turn the number into text. Without them, both stop with an error. JavaScript shows no error: it joins the number to the text, and the result is Price:5.