Let's take a look at how we go about defining functions for use in our own JavaScript code. So first, let's take a look at the syntax. in defining a function, you must first use the function keyword. As the first part of that, then you put the function name. Now in certain situations that function name is optional, and in those cases, it's called an anonymous function. Following that function name, you have a set of parentheses, that is not optional.
Then you have the curly braces, the curly braces enclose the, the code block that will execute anytime the function is called. And those curly braces are not optional. Either they must be there. That code block may be a single statement, or it can be multiple statements. Now once you've defined a function, you can then Call it or invoke it. by calling or invoking the function, it causes the code within the function to execute.
The syntax for calling a function is simply the function name. And then parentheses is actually the parentheses that tell the JavaScript engine to execute that code. Without the parentheses, it would just display the code you want to execute, so the parentheses are required. Now when that function is defined as part of an object, then you use the dot syntax to call that function. And in that case, we did we refer to it as a method. And we've done that multiple times in past movies already.
So the object dot method name and then parentheses to call the method of the object. All right, let me jump out to the console and we'll do a quick example. I'm going to define a very simple function called greeting. Here I have the function keyword, I have the function name, which is greeting the parentheses, then the curly braces inside the curly braces is the code block. This is the code that will execute when the function is called. As you can see, right now we have a single line, all it does is print hello to the console.
To call that I would need to enter greeting, and then parentheses. Notice what happens if I just enter greeting is simply displays the code that defines that function. If I want that to execute, I need to include the parentheses in there it executes and prints hello to the console. So that's how simple it is to define a function and then invoke that function. Most programs consist of many functions. And how do you determine if you need to use a function?
Well in the past movie, we went through some of the advantages of functions. If your code can fit into one of those advantages, then define a function. As you get used to writing more and more JavaScript programs. It will become more intuitive to you when to do a function. Basically, you think, Oh, I need to solve this little issue. That's a part of my requirements that will be a function.
Alright, now that we know how to define a function, let's look at the difference between a function declaration and a function expression.