I am revisiting my JavaScript Countdown to turn elements of it into JavaScript functions.
A function allows for parts of code to be reused easily without having to recreate the segment of code every time it is needed. For example, below I have created a basic function that prints “Hello World!” and then called on it:
// geektechstuff
// JavaScript Functions
// defining the function
function printHelloWorld() {
console.log(“Hello World!”);
}
//calling the function
printHelloWorld();
The word function is used to tell JavaScript that a function is being defined and then the name we want to call the function, in this case printHelloWorld. The function name is followed by brackets () and then an opening curly brace { to start defining what we want the function to do. In my above example the function simply uses console.warn() to print Hello World! The function definition is ended with a closing curly brace }.
The function can then be called by simply typing its name followed by a semi-colon e.g. printHelloWorld();
Using the Countdown from yesterday, I can modify it into a function so that it can be reused for different dates without having to retype it each time:

// geektechstuff
// JavaScript Countdown
// defining the function
function countDown(askDate){
vardateToday=newDate();
vardateOfEvent=newDate (askDate);
vardifferenceBetweenDates=dateOfEvent.getTime() -dateToday.getTime();
vardays=Math.floor(differenceBetweenDates/ (1000*60*60*24));
console.warn(‘There are ‘+days+’ days until the event!’);
}
// calling the function
countDown(‘August 1, 2019’);
countDown(‘July 1, 2019’);
countDown(‘December 25, 2018’);
The askDate variable allows for different dates to be entered into the variable depending on which date I want to countdown to.
You must be logged in to post a comment.