Public
Edited
Apr 6, 2024
Insert cell
# HALP, I don't know any javascript at all 🔰🆘

Martin: this notebook is a fork of the original [HALP, I don't know any javascript at all ](https://observablehq.com/@notionparallax/halp-i-dont-jnow-any-javascript-at-all)

all the cells have been selected, and then opened and pinned (their **code** part is shown)

results are always **above** the code (HTML, Markdown, JS)

Insert cell
Type JavaScript, then Shift-Enter. Ctrl-space for more options. Arrow ↑/↓ to switch modes.

Insert cell
md`# HALP, I don't know any javascript at all 🔰🆘😺

That's fine, but let's see if we can change that. I've put new terms in _itallics_ so that you can see that they're important words. Try to pay attention to these words, they come up a lot.

## What is javascript?

I'm guessing that given that you're here, you have _heard_ of javascript (JS), and have _some_ motivation to learn how to use it. But that doesn't mean that you know what it _is_. JS is a _programming language_, which—mainly by luck&mdashbecame the default programing language of web browsers. It's got a bit of a [dodgy history](https://en.wikipedia.org/wiki/JavaScript#History), and it had [a lot of detractors](https://github.com/denysdovhan/wtfjs/blob/master/README.md), but it's become a pretty [popular](https://insights.stackoverflow.com/survey/2021#section-most-popular-technologies-programming-scripting-and-markup-languages) now. If you click something on a website, and something other than a full page-reload happens, the odds are that some javascript made that happen. The level of knowledge needed to make that kind of thing happen is for another day, but this page is about getting the basics into your brain so that you're ready to do more interesting things another day.

## What is a _notebook_?

This webpage [waves arms at the screen] is a notebook. It isn't like a normal website, it's not just _showing_ you code, it's running it too. When you change the symbols on the screen, those changes recalculate and the outcomes change too. The bit in <span style="background-color: whitesmoke; border-radius: 6px; padding: 0 5px;">grey boxes</span> are input cells. You can click these and change them. The text just above, usually in <span style="color: #20a5ba; font-family: monospace;">this nice teal</span> is the result of running that cell.

There are some [excellent tutorials about how to use notebooks here](https://observablehq.com/tutorials) so you could stop here and watch the first couple, or you can just muddle along and you'll get it soon enough.

In other programming _environments_ there's a lot of _boilerplate_ needed to get going. Boilerplate is a term that means "_code that doesn't really do anything, but you need to put in anyway, don't ask why, just remember it_", and it sucks when you're first learning to code. One of the nice things about a notebook is that it shows the results of the things we do without needing to do any other things, for example:`
Insert cell
35 + 7
Insert cell
md`\`35 + 7\` is a _statement_, the notebook shows us the result of the statement above the cell. The statement _evaluates_ to a _number_.

For some reason these notebooks show the result above the statement that generates them, which isn't how we're used to reading. Usually the result is below, but you will get used to it eventually. You might be more accustomed to seeing it written as: <span style="color: #20a5ba; font-family: monospace; display:inline-block;"><span style="background-color: whitesmoke; border-radius: 6px; padding: 0 5px;">35 <span style="color:black;">+</span> 7</span> <span style="color:black;">=</span> 42</span> but most things you'd be doing in a notebook aren't this small. Often we'll be making very big, very cool graphs or maps.

This statement doesn't _mean_ anything, it's just adding one number to another and giving us a result. we can also work with words:`
Insert cell
"Hello, world!"
Insert cell
md`That's a statement too, but this time we're making a _string_. The idea that 12.7 is a _number_ is pretty easy, but why _string_? As far as I know, it's becasue it's a string of _char_s (characters). It's basically text, and is anything at all, wrapped by quotes, so \`"hello"\` or \`"!!!"\` or \`"75"\`.

_Note_: That last one isn't a number, it's the character seven and the character 5, sitting next to each other, not the number for 15×5. That might trip you up one day, so keep an eye out for it.`
Insert cell
myName = "Ben"
Insert cell
md`If I want to store a value so that I can use it later, I can use a _variable_. in this case, the _variable name_ is \`myName\` and it now has the _value_ \`"Ben"\`. It has that value because we _assigned_ it.

The value on the right of the \`=\` is assigned to the variable name on the left.

There are a couple of rules about variable naming:
1. It can't start with a number
1. No spaces inside it
1. other stuff that's complicated and we'll get to another day.`
Insert cell
myEuroShoeSize = 4 * (10 + 1)
Insert cell
md`The european shoe size number is clearly the best, but like an old English person, I can't possibly express it simply. Luckily, the computer has no problems with that. It _evaluates_ the _expression_ on the right of the \`=\` and _assigns_ it to the variable.

<img src="${await FileAttachment("image@1.png").url()}" style="float: right; width: 16em;">JS follows the [BODMAS](https://www.mathsisfun.com/operation-order-bodmas.html) rules of operator precedence. Unlike boomers who use facebook.

---

There's a newish feature in JS called template strings. Most beginner courses don't teach it, but I think it's super useful.`
Insert cell
`My name is ${myName} and my shoes are size ${myEuroShoeSize}, which is the only way to measure feet.`
Insert cell
md`Regular strings are wrapped in "" quotes, but template strings are wrapped in &#96;&#96; backticks. That's this key:`
Insert cell
md`
<figure>
<img src="${await FileAttachment("image.png").url()}">
<figcaption>A large print keyboard from [visionaustralia](https://shop.visionaustralia.org/shop/product/es0202)</figcaption>
</figure>`
Insert cell
md`Then you can put little bits of regular JS inside \`$\{some js\}\` sections and it'll show up inside your string output.

---
So far, we've seen two _types_ of data, numbers and strings. The third you might see is a _boolean_. These can be true or false, and show up like this:`
Insert cell
4 > 5
Insert cell
0 == (10 - 5 - 5)
Insert cell
md`The statement that four is more than five is \`false\`. It's \`true\` that the result of \`10 - 5 - 5\` is the same as zero.

There are lots of _comparisons_ ( < > ==)and _logical operations_ AND, NOT, etc. but we'll get to them later.

Task: Make that comparison be different, but still balance out to _true_

---

It's all very well having a thing, but sooner or later you'll want lots of things. JS gives us two main ways to tidy up. We can have _lists_ and _objects_. This is a list:`
Insert cell
myList = [1,2,4, myName, myEuroShoeSize, "hello", false, "...one last thing"]
Insert cell
md`Lists are wrapped in [] square brackets, or staples <img src="https://trimedortho.com/wp-content/uploads/2019/11/staples-Banner_1.jpg" alt="some staples" style="height:4em; float: right;">

They can have any number of things in them, including zero:`
Insert cell
[]
Insert cell
md`This is called an empty list, and shows up a lot more than you'd expect`
Insert cell
md`<img src="https://live.staticflickr.com/3191/2855823558_44d2c784b0_b.jpg" alt="a nice crab" style="height:4em; float:right;">Lists are the easiest way to put something into a _collection_, but the easiest way to get it our again is to use an object. Objects use _key_:_value_ pairs. They're wrapped in _curley braces_, or crab claws `
Insert cell
myObject = ({animalType:"dog", petName:"Patch", isGood:true, legs:4})
Insert cell
md`Task: play with this to make it be your pet, or name the crab.

_Note: the round-brackets are an Observable thing, not a JS thing, just go with it for now and we'll come back to it later._

We've put things into a list and an object, but how do we get things back out again? For this we need to use the _index_ of the thing we want to get out. Like this:`
Insert cell
myList[3]
Insert cell
The _definition_ of that list is off the screen now, so to jog our memory `myList` is: `${myList.join(", ")}`

or maybe a bit clearer:


| 0| 1| 2| 3| 4| 5| 6| 7|
|--|--|--|--|--|--|--|--|
|`${myList.join("|")}`|
Insert cell
myList[0]
Insert cell
`0` what?! For reasons that are too complicated to go into now, lists in almost all programing languages start counting at zero.

Again, to jog our memory: `${JSON.stringify(myObject)}`

To get something (a _value_) out of an object, we need to use its _key_:
Insert cell
myObject["animalType"]
Insert cell
md`You can also get fancy and nest things. This example is pretty silly, but things _like_ this come up much more often than you'd expect.`
Insert cell
myList[myObject["legs"]]
Insert cell
md`Task: see if you can work out why that works.

---

The last type of thing we're going to see today is a _function_. I'll talk a lot more about these later, but they're basically a lump of code that represents an idea.`

Insert cell
function greet(name){
return `Hello ${name}`
}
Insert cell
greet("Kermit the Frog")
Insert cell
md`They save us typing the same code over and over, and they keep ideas together. Making functions is _a good thing to do_&trade;.

---

JS uses a _lot_ of functions, for example:`
Insert cell
myList.map(greet)
Insert cell
md`\`map\` applies a function to each of the values in a list, and gives you back a list of the transformed values. Again, this is a pretty silly example but it allows for some super powerful things, like all the websites you see on the internet!

(Well, not map specifically, but people using JS)

That's a lot for today, slurp it up, and then stop. or you'll burn out your brain. If you have questions you can ask them in the #programming channel on slack. I'll make more of these notebooks to explain the answers to your questions.

![](https://i.pinimg.com/originals/df/1a/ff/df1aff8395678d11b99b575f0e3b19d5.gif)`
Insert cell
# The anatomy of functions

We talked about functions at the end of the previous session, but I left so much unsaid.
Insert cell
function theNameOfTheFunction(argument1, argument2){
const result = argument1 + argument2
return result
}
Insert cell
That might look simple, but there's a LOT going on there. Let's unpack it a bit.

Words in <span style="color:#c30771">this pinky colour are keywords, or reserved words</span>. They are used by JS and we can't use them to name anything else. They say to the language "pay attention, something specific is coming up here".

<span style="color:#c30771; font-family:monospace;">function</span> is telling the language that what's coming up a going to be a function, and to start understanding the pattern of things coming up.

<span style="color:#005f87; font-family:monospace;">theNameOfTheFunction</span> is the name of the function. This is used as a way to _call_ the function in future. You should spend a bit of time coming up with good names for your functions because they're the interface for YOUR mind to use.

The variable names in brackets `(argument1, argument2)` are the _arguments_. These are placeholders for real values that you'll give the function later on.

The _block_ of code inside the `{}` is the _body_ of the function. That's the code that's doing the work.

lastly, <span style="color:#c30771; font-family:monospace;">return</span> gives us the result back. You don't need a return, but if you don't have one you won't get anything back. People often forget this step when they're learning and wonder why they are getting back `undefined` instead of something useful.

So we've defined a function, how do we use it? Or in programming speak, how do we _call_ it?
Insert cell
theNameOfTheFunction(10, 15)
Insert cell
Like wizards casting spells in books, you need to use the name of the ~~spell~~ function to get it to work. You need to _pass_ in some arguments too. In this case, we're passing `10` and `15` as the arguments, so we get back `25`. (Or in programmer speak, "the function returns `25`")

Insert cell
Type JavaScript, then Shift-Enter. Ctrl-space for more options. Arrow ↑/↓ to switch modes.

Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more