function buttonClickHandler() {
const btnEl = document.getElebentById('importantBtn');
btnEl.innerHtml = 'No it is not so important';
}
This function is good but we can't reuse it
We want to calculate the distance based on a speed and time
function calculateDistance() {
let speed = 60;
let time = 2;
alert("Distance is: " + speed * time);
}
calculateDistance();
Parameters are like variable boxes which you can use inside function
function yourFunctionName(parameter1, parameter2) {
// inside you can use them with theis names
}
yourFunctionName(valueForArgument1, valueForArgument2);
function calculateDistance() {
let speed = 60;
let time = 2;
alert("Distance is: " + speed * time);
}
calculateDistance();
function calculateDistance(speed, time) {
alert("Distance is: " + speed * time);
}
calculateDistance(60, 2);
calculateDistance(100, 3);
Arguments should be provided in correct order
calculateDistance(60, 2); // speed = 60, time = 2
calculateDistance(3, 100); // speed = 3, time = 100
function calculateDistance(speed, time) {
alert("Distance is: " + speed * time);
}
calculateDistance(60, 2);
calculateDistance(100, 3);
Now we can reuse our function with different values of speed and time!
But still we can only alert the result :(
return statement stops the execution of a function and returns some value back
function yourFunctionName(parameter1, parameter2) {
let result = parameter1 + parameter2; // or any other operations
return result;
}
function calculateDistance(speed, time) {
const distance = speed * time;
return distance;
}
function calculateDistance(speed, time) {
const distance = speed * time;
return distance;
}
const distance = calculateDistance(60, 2);
alert(distance);
console.log(`In console: ${distance}`);
// or in another example
alert(calculateDistance(60, 2) + calculateDistance(200, 2))
Let's create another function
function outputDistance(distance, callback) {
let sentence = "Distance to the Alps is equal to: " + distance;
callback(sentence);
}
outputDistance('100KM', alert);
which is the same as
function outputDistance(distance) {
alert(distance);
}
outputDistance('100KM');