DEV Community

Chinwendu Agbaetuo
Chinwendu Agbaetuo

Posted on • Updated on

Creating functions in JavaScript - Part 3

Create a function that prints the current date and time using function declaration, function expression, and arrow function.

Function declaration

function getDate () {
  console.log(new Date());
};

getDate();
Enter fullscreen mode Exit fullscreen mode

Arrow function

const getDate = () => { console.log(new Date)};

getDate();
Enter fullscreen mode Exit fullscreen mode

Function expression

const getDate = function () {
  console.log(new Date());
};

getDate();
Enter fullscreen mode Exit fullscreen mode
> Fri Apr 12 2024 10:44:38 GMT+0100 (West Africa Standard Time)
Enter fullscreen mode Exit fullscreen mode

Top comments (5)

Collapse
 
bcostaaa01 profile image
Bruno

Also, would be worth telling which type of function is it, because readers who don’t know any other way of defining functions, will think this is the standard, and it might be nowadays (if we talk modern ES - EcmaScript), but you can also define them with the function keyword.

Collapse
 
dindustack profile image
Chinwendu Agbaetuo

Hello Bruno, thanks for your feedback and for dropping your insights.

Collapse
 
harry176 profile image
Harry

Very nice. You could also define the function in one line by doing this:

const getDate = () => console.log(new Date());

getDate();
Enter fullscreen mode Exit fullscreen mode

A function body composed of a single-line block doesn't need curly braces! 😍

Collapse
 
dindustack profile image
Chinwendu Agbaetuo

That's correct, thanks for your valuable feedback.

Collapse
 
bcostaaa01 profile image
Bruno

Exactly πŸ‘ you don’t need a return statement on an arrow function which has only one line of code inside the block, or in this case when you can define all the logic like that.