In this lesson we learn about JavaScript Functions, what they are and how we use them in JavaScript.
Functions are useful if you have some code/instructions that you want to use again and again. For example you might want to make characters in your game do a few different things when they jump.
The code for this might look something like this:
moveUp()
say("Let's go")
playSound(Jump)
moveDown()
Each time you wanted a character to jump you would have to write these 4 lines of code.
A more efficient and better way would be to create a function named jump and put the 4 lines of code in it.
function jump(){
moveUp()
say("Let's go")
playSound(Jump)
moveDown()
}
Then anytime you want a character to jump you would just put in jump()
and this would run the 4 lines of code that you have defined as the 'jump' function.
jump()
Let's try creating a function
and calling it to run in two different places. Go to the https://makecode.microbit.org website, create a new project and switch to JavaScript.
Add the following code to create a function called speak. that shows the Happy icon on the Microbit.
function speak(){
basic.showIcon(IconNames.Happy)
}
If you run your code nothing will happen that is because although we have defined what the 'speak' function is and what should happen (basic.showIcon(IconNames.Happy)
) when it's run, we haven't actually put in any code to make it run yet.
Program the A button to run the speak function.
Program the B button to run the speak function.
We can pass values and variables into functions, this is called passing parameters into a function. Let's look at how we write a function.
A JavaScript function is defined with the function
keyword, followed by a name for the function and then parentheses ( ). Then we place the code to be run by the function inside curly brackets { }.
function speak(){
basic.showIcon(IconNames.Happy)
}
So in the example above:
basic.showIcon(IconNames.Happy)
.Now let's pass a parameter into the function. We're going to pass in some text as a parameter called say and then use the say parameter in the code to run. Any parameters you are passing into a function go inside the parentheses ( ). Update your function code to the following:
function speak (say: string) { // passing in the 'say' parameter as a string
basic.showIcon(IconNames.Happy)
basic.showString(say) // using the 'say' parameter
}
: string
after it. You don't always need to do this in JavaScript but it is good practice as then the code knows what type the variable is.
You will also need to update the code where you call the function so that the parameter is passed in. Change your code for the A and B buttons to the following:
input.onButtonPressed(Button.A, function () {
speak('Hi')
})
input.onButtonPressed(Button.B, function () {
speak('Bye')
})