Functions (JavaScript)

Hello World Function

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:

Hello World Function

// 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:
function_countDown
countDown as a JavaScript function
// 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.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.