Day 2 of learning JavaScript: Functions
Today is my second day of learning JavaScript. I learned some basic things about functions, which I have to know to build the passenger counter app more effectively.
What are functions and why do you use them?:
Functions are like little blocks that you define to do certain things that are taking much time to code with just one expression.
For example a countdown:
function countdown() { //you declare a function like that
//here you write the operation that you want the function to do
console.log(5)
console.log(4)
console.log(3)
console.log(2)
console.log(1)
} //don't forget the closing brace at the end ;)
countdown() //that's how you run the function
After that, I knew how to declare and execute functions. But for the app, I needed to know how to do a function that increments a variable with a certain value.
let count = 0 // you can use this variable in the function and also outside of the function, because its declared outside of the function and before the function
function counter() {
//here you can do any operation that you want the function to execute
count = count + 1 //basic math, increment by 1
// if you declare a new variable in the function, then you cant use the variable afterwards outside of the function
}
//execute the function as many times as you like (there will be an easier way to do that many times in a row soon with loops)
counter()
counter()
counter()
console.log(count) //now run the code and look how your number increased (console should show "3")
That's what I learned today about functions. It's much easier to code when you can use short expressions to do difficult and repeating operations. I hope you guys learned something valuable by reading this post!