What is a function? A JavaScript Functions is really just an encapsulated bunch of code. We’ve been looking at a bunch of JavaScript syntax: all of that can go inside JavaScript Functions and often that’s what you’ll do. When you put code inside a JavaScript Functions it isn’t run right away, like “loose” code. You decide when the code runs by calling the function, and you can do that as often as you want to. This is part of the benefit of JavaScript Functions.
But don’t forget the encapsulation part: that means that at the time you invoke, or call, a function, you don’t have any control (for the most part) of what goes on inside it. You’ll hand the JavaScript Functions some values to work with, and it will hand a value back; but what goes on inside it is black-boxed. This turns out to be an important thing that we can take advantage of.
There are two other important things you should know about JavaScript Functions. First off, functions are first-class objects in JavaScript, which means that they are objects, and that they are no different from any other value. Let’s take these two points a bit further.
JavaScript Functions are Objects: We saw how to create an object literal earlier. Now, we can’t create a function using that object literal notation, but a function can have properties and methods, because it is an object. You can add your own properties and methods to functions, but we’ll look at some of the built in ones soon.
JavaScript Functions are like other Values: In many programming languages, a function is something very different from primitive values like strings and numbers. However, in JavaScript, that’s not the case. You can use functions in most places that you’d use another value, like passing it to another function Also; you can redefine a function, just like you’d redefine any other variable. This, as you’ll see, is very handy. Now that we understand a bit of function theory, let’s look as some syntax.
JavaScript Functions Syntax
As we know, a JavaScript function is just any number of lines. But we need to wrap that in JavaScript functions material. Let’s say we have some code that determines an appropriate greeting for our website:
var hour = 10, var message; if (hour < 12) { message = "Good Morning!"; } else if (hour < 17) { message = "Good Afternoon!"; } else { message = "Good Evening!"; } Document.write (message); // Good Morning!
We’ve created an hour variable, with the hypothetical current hour. Then, we use an if statement to figure out in what range our hour is, and assign message accordingly.
So, what do we do to convert this code to a javaScript functions? Well, first, let’s meet the Javascript function shell:
function getGreeting () {// code goes here}
Start with the keyword function; then, write the name of the JavaScript Function. it can be whatever you want, as long as it follows the rules for variable names (i.e. alphanumeric characters, underscore, and dollar sign, but not starting with a number). Next, parentheses. Then, the lines of code go between curly braces.
Now, you might be tempted to throw all the code we wrote above into a JavaScript Function. shell. This isn’t wise for two reasons. Firstly, there would be no way to get to the variable message (more on function scope soon). Secondly, with a bit of customization, we can increase the usefulness of the function by tweaking it a bit.
Let’s make our JavaScript Functions With Parameters. A parameter or (we say Javascript Function Arguments) is a value that you hand to the javascript function when you ask the function to run. The JavaScript Functions With Parameters can then use the parameters however it needs to. How does this work syntactically?
function getGreeting (hour) {//code here}
Here, our JavaScript Function getGreeting accepts one parameter, which we’re calling hour. Function Parameters are like variable that you can only access from within the function. To invoke this function and give it an hour, we would do this:
getGreeting(10);
We could store the hour in a variable, but we don’t need to, since we won’t need it after this.
So, we’re passing the current hour to getGreeting. Now we’re ready to write the code inside that function.
function getGreeting(hour) { var msg; if (hour < 12) { msg = "Good Morning!"; } else if (hour < 17) { msg = "Good Afternoon!"; } else { msg = "Good Evening!";} return msg;} var message = getGreeting( 16 ); // 4 PM alert(message); // Good Afternoon!
If you’ve been following along carefully, there should be only one thing above that you’re not sure about: return msg. What’s up with that? To return a value is to pass it back to the code that called the function. That way, we can assign the calling of a function to a variable (as we do above), and it will be whatever value was returned from getGreeting.
Here are two more things I’d like to do to this function, to make it better. First, there’s really no need for the msg variable, because we only ever do one thing to it. Try this:
function getGreeting(hour) { if (hour < 12) {return "Good Morning!";} else if (hour < 17) { return "Good Afternoon!";} else {return "Good Evening!";}} alert( getGreeting( 3 ) ); // Good Morning!
This makes it clear that we can have more than one return. Once we figure out which value we must return, we’ll do so right away. I should note that a return statement will be the last line to be executed in a function; once the Javascript functions returns, it’s done; nothing else is executed. Therefore, unless your return statement is inside a conditional statement, you usually won’t have any code after the return line in your function.
One more thing: When writing JavaScript Functions With Parameters, you want them to be user friendly. Let’s do this: if the user doesn’t pass in a parameter, we’ll provide a reasonable default.
function getGreeting(hour) { hour = hour || new Date().getHours(); if (hour < 12) { return "Good Morning!"; } else if (hour < 17) { return "Good Afternoon!"; } else { return "Good Evening!"; } } alert( getGreeting( new Date().getHours() ) );
What’s going on here? We’re using a logical OR operator; remember what this does: if the first side is true, it will use that; otherwise, it will use the second side. In this case, we’re saying that we want to set the hour parameter to either the value of the hour parameter (if the user passed one in), or the current hour. We’re using the getHours function of a current Date object; we’ll see more about this in a page or so. If the user didn’t pass a parameter, hour will be undefined, which is false. Therefore, the function will assign the current hour to hour. And yes, you can assign new values to parameters like this.