There are a number of ways to define functions in Javascript.
The oldest looks like this:
function foo (a, b) {
return a + b * 3;
}
🚫 Don’t use this style. 🚫
const foo = (a, b) => {
return a + b * 3;
};
Later in the year when you know more, I’ll explain why I chose to teach you this syntax.
const foo = (a, b) => a + b * 3;
This only works when the body of the function is a single expression whose value you want to return.
var
đźš«var
is a really bad vestige of Javascript’s hasty original development.
In this class we use let
and const
to declare variables.
I haven’t talked about semicolons but you should pay some attention to them.
Javascript is pretty forgiving if you forget them but some are required.
For now assignment statements and return
statements should end with a semicolon.
const foo = (a, b) => {
const x = b * 3;
return a + x;
};
When you know what well-formatted code looks like, it makes it easier to spot errors.
The autoformatter in the code editor is your friend!
The “Format Document” command will clean up lots of issues.
Indent to show the structure of your code.
In general leave space around punctuation.
Let your code breathe!
No space between a function name and the opening paren of its arguments when calling it.
foo(10, 20)
Operators with only one operand snug up against it.
!sleepy
i++
The names we choose are the main way we can make the meaning of our code clear.
This includes making our own code clear to ourselves.
Variables, especially, tend to have short, simple names.
Functions sometimes have slightly longer names.
Four functions that take the same kind of value should probably use the same argument name.
const isRed = (bird) => ...
const isSpotted = (bird) => ...
const isNotRed = (bird) => ...
const isNotSpotted = (bird) => ...
Good
const isFlobbyBird = (red, spotted) => red && spotted;
Okay
const isFlobbyBird = (isRed, isSpotted) => isRed && isSpotted;
Not so good
const isFlobbyBird = (x, y) => x && y;
const manhattanDistance = (x1, x2, y1, y2) => {
return Math.abs(x1 - y1) + Math.abs(x2 - y2);
}
It works correctly, but there’s something wrong with it.
Avoid ambiguious variable names like o
and l
.
A name like s1
implies an s2
.
Run words together in camelCase
.
Often we pick a name and later change how we’re using the variable.
If so, we need to rename it to match its new meaning.