Lesson 1.7: From pseudocode to JavaScript
JavaScript is a real language and it's already in your browser. The ideas are the pseudocode ones; the words change.
The idea
Pseudocode is for thinking, but it doesn't run. JavaScript does: it's a real programming language and every browser ships with it. Nothing to install.
Open the console
The console is a corner of the browser where you type JavaScript and it runs straight away.
- Open a new tab.
- Press
F12(on a Mac,Cmd + Option + J) and pick the Console tab. - Type this and press Enter:
console.log("Hello, world");
Hello, world
- To write several lines without running them, press
Shift + Enterat the end of each one. - If
undefinedshows up after a line, it isn't an error: the console shows what each instruction returns, andconsole.log()returns nothing. - If you paste code, the console may ask you to type "allow pasting" first. It's a protection against scams: only paste code you understand.
Same ideas, other words
| Pseudocode | JavaScript |
|---|---|
Write "Hello" | console.log("Hello"); |
Read name | let name = prompt("Name?"); |
age ← 30 | let age = 30; |
If … Then … EndIf | if (…) { … } |
While … Do … EndWhile | while (…) { … } |
Function … EndFunction | function name() { … } |
The next lessons go through them one by one.
The same program, twice
Algorithm Greet
Write "What's your name?"
Read name
Write "Hello, ", name
EndAlgorithm
let name = prompt("What's your name?");
console.log("Hello, " + name);
prompt()opens a window with the question and returns what you type.+joins pieces of text.;marks the end of each instruction.- There's no
AlgorithmorEndAlgorithm: the program is what you write.
Try it
In the console, write a program that asks for a name and a city and answers, for example, "Ana lives in Seville". It's the exercise from 1.2, for real this time.
Show the solution
let name = prompt("What's your name?");
let city = prompt("Which city do you live in?");
console.log(name + " lives in " + city);
Notice the spaces inside " lives in ": without them you'd get "Analives inSeville".
Summary
- JavaScript is a real language and it runs in the browser.
- The console (
F12) runs it straight away. console.log()writes;prompt()asks.