Week 2

Learning goals

Teaching note. Start off explaining functions with how to use a function e.g. explain why the Math.random function is smart, or Math.max.

Recap Logical operators

0 = false
1 = true

AND &&

&&

0

1

0

0

0

1

0

1

OR ||

||

0

1

0

0

1

1

1

1

So you can say that false in combination with && always returns false

Typeof

typeof always returns the data type in a string.

So for example:

So the data type of what typeof returns is always a string, bar on the other hand is still a number.

Functions

A function is a reusable piece of code. It is used to hide away abstraction! Functions are very important in JavaScript, to the extent that some people call JavaScript a "function-oriented" language.

Two sides of a function

There are two sides to using function, using a function (calling a function) and creating a function.

Function usage

When you call a function some javascript code is run. Here's a simple example:

Here Math.random is a function. To activate the function we call it using parentheses (). When calling it we get a randomNumber! We now don't need to think about all the code it takes to create a random number in javascript, we simply call the function and get a random number. Code has been abstracted away for us!

Some functions is called with arguments, for example:

Arguments are used to control the code inside a function.

Function creation

When we create a function we use the function keyword:

Parameters and arguments

So remember the difference between the word "parameter" and "argument". Many people confuse them, and that's not a big problem, but understanding the difference is always nice:

  • A parameter is the name you want to give to the variable that is available inside of the function.

  • An argument is the actual value you want to assign to the parameters when you call the function.

Parameters acts as a placeholder for the arguments. The value of the parameter will get substituted with the value of the argument.

Return value

Sometimes we want to get a value back when calling a function. e.g. in the sum example. We want to call the function and get the sum back!

If we don't return anything from the function, it will automatically return undefined. This is the functions way of saying that nothing was returned.

Calling a function on something

In JavaScript, you can call functions on something. By this, we mean that you use the dot to call the function. For instance, when we say "call method trim on string s", we mean:

However, there are functions that you don't call on anything:

Here, you call the function sum on nothing.

Last updated