Introducing Functions: Getting functional - Head First JavaScript Programming (2014)

Head First JavaScript Programming (2014)

Chapter 3. Introducing Functions: Getting functional

image with no caption

Get ready for your first superpower. You’ve got some programming under your belt; now it’s time to really move things along with functions. Functions give you the power to write code that can be applied to all sorts of different circumstances, code that can be reused over and over, code that is much more manageable, code that can be abstracted away and given a simple name so you can forget all the complexity and get on with the important stuff. You’re going to find not only that functions are your gateway from scripter to programmer, they’re the key to the JavaScript programming style. In this chapter we’re going to start with the basics: the mechanics, the ins and outs of how functions really work, and then you’ll keep honing your function skills throughout the rest of the book. So, let’s get a good foundation started, now.

NOTE

More on this as we progress through the book.

SHARPEN YOUR PENCIL

Do a little analysis of the code below. How does it look? Choose as many of the options below as you like, or write in your own analysis:

var dogName = "rover";

var dogWeight = 23;

if (dogWeight > 20) {

console.log(dogName + " says WOOF WOOF");

} else {

console.log(dogName + " says woof woof");

}

dogName = "spot";

dogWeight = 13;

if (dogWeight > 20) {

console.log(dogName + " says WOOF WOOF");

} else {

console.log(dogName + " says woof woof");

}

dogName = "spike";

dogWeight = 53;

if (dogWeight > 20) {

console.log(dogName + " says WOOF WOOF");

} else {

console.log(dogName + " says woof woof");

}

dogName = "lady";

dogWeight = 17;

if (dogWeight > 20) {

console.log(dogName + " says WOOF WOOF");

} else {

console.log(dogName + " says woof woof");

}

A. The code seems very redundant.

B. If we want to change the display of the output, or add another weight for dogs, this is going to require a lot of reworking.

C. Looks tedious to type in!

D. Not the most readable code I’ve ever seen.

E. ________________________________________________________

What’s wrong with the code anyway?

We just looked at some code that got used over and over. What’s wrong with that? Well, at face value, nothing. After all, it works, right? Let’s have a closer look at the code in question:

image with no caption

Sure, this code looks innocent enough, but it’s tedious to write, a pain to read and will be problematic if your code needs to change, over time. That last point will ring true more and more as you gain experience in programming—all code changes over time and the code above is a nightmare waiting to happen because we’ve got the same logic repeated over and over, and if you need to change that logic, you’ll have to change it in multiple places. And the bigger the program gets, the more changes you’ll have to make, leading to more opportunities for mistakes. What we really want is a way to take redundant code like this and to put it in one place where it can be easily re-used whenever we need it.

BRAIN POWER

How can we improve this code? Take a few minutes to think of a few possibilities. Does JavaScript have something that could help?

image with no caption

By the way, did we happen to mention FUNCTIONS?

Meet functions. JavaScript functions allow you to take a bit of code, give it a name, and then refer to it over and over whenever we need it. That sounds like just the medicine we need.

image with no caption

Say you’re writing some code that does a lot of “barking.” If your code is dealing with a big dog then the bark is a big “WOOF WOOF”. And if it’s a small dog, the bark is a tiny “woof woof”. You’re going to need to use this barking functionality many times in your code. Let’s write a barkfunction you can use over and over:

image with no caption

Now we need to write the code for the function; our code will check the weight and output the appropriate sized bark.

image with no caption

Okay, but how does it actually work?

First, let’s rework our code using the new function bark:

image with no caption

Wow, that’s a lot less code—and it’s so much more readable to your co-worker who needs to go into your code and make a quick change. We’ve also got all the logic in one convenient location.

Okay, but how exactly does it all come together and actually work? Let’s go through it step by step.

First we have the function.

So we’ve got the bark function right at the top of the code. The browser reads this code, sees it’s a function and then takes a look at the statements in the body. The browser knows it isn’t executing the function statements now; it’ll wait until the function is called from somewhere else in the code.

Notice too that the function is parameterized, meaning it takes a dog’s name and weight when it is called. That allows you to call this function for as many different dogs as you like. Each time you do, the logic applies to the name and weight you pass to the function call.

image with no caption

Now let’s call the function.

To call, or invoke, a function, just use its name, followed by an open parenthesis, then any values you need to pass it, separated by commas, and finally a closing parenthesis. The values in the parentheses are arguments. For the bark function we need two arguments: the dog’s name and the dog’s weight.

NOTE

“Invoking a function” is just a fancy way of saying “calling a function.” Feel free to mix and match, especially when your new boss is around.

Here’s how the call works:

image with no caption

After you call the function, the body of the function does all the work.

After we know the value for each parameter—like name is “rover” and weight is 23—then we’re ready to execute the function body.

Statements in the function body are executed from top to bottom, just like all the other code you’ve been writing. The only difference is that the parameter names name and weight have been assigned the values of the arguments you passed into the function.

image with no caption

And when it’s done... The logic of the body has been carried out (and, in this example, you’ll see that Rover, being 23 pounds, sounds like “WOOF WOOF”), and the function is done. After the function completes, then control is returned to the statement following our call to bark.

image with no caption

SHARPEN YOUR PENCIL

We’ve got some more calls to bark below. Next to each call, write what you think the output should be, or if you think the code will cause an error. Check your answer at the end of the chapter before you go on.

image with no caption

CODE MAGNETS

image with no caption

This working JavaScript code is all scrambled up on the fridge. Can you reconstruct the code snippets to make a working program that produces the output listed below? Notice, there may be some extra code on the fridge, so you may not use all the magnets. Check your answer at the end of the chapter.

image with no caption

JAVASCRIPT CONSOLE

Wear a jacket

Wear a t-shirt

Wear a sweater

We’re using this to represent a generic console.

THE FUNCTION EXPOSED

This week’s interview: the intimate side of functions...

Head First: Welcome Function! We’re looking forward to digging in and finding out what you’re all about.

Function: Glad to be here.

Head First: Now we’ve noticed many JavaScript newbies tend to ignore you. They just get in and write their code, line by line, top to bottom, no functions at all. Are you really needed?

Function: Those newbies are missing out. That’s unfortunate because I’m powerful. Think about me like this: I give you a way to take code, write it once, and then reuse it over and over.

Head First: Well, excuse me for saying this, but if you’re just giving them the ability to do the same thing, over and over... that’s a little boring isn’t it?

Function: No no, functions are parameterized—in other words, each time you use the function, you pass it arguments so it can compute something that’s relevant to what you need.

Head First: Err, example?

Function: Let’s say you need to show a user how much the items in his shopping cart are going to cost, so you write a function computeShoppingCartTotal. Then you can pass that function the shopping carts of many users and each time I compute the amount of each specific shopping cart.

Head First: If you’re so great, why aren’t more new coders using you?

Function: That’s not even a true statement; they use me all the time: alert, prompt, Math.random, document.write. It’s hard to write anything meaningful without using functions. It’s not so much that new users don’t use functions, they just aren’t defining their own functions.

Head First: Well, right, alert and prompt, those make sense, but take Math.random—that doesn’t look quite like a function.

Function: Math.random is a function, but it happens to be attached to another powerful thing new coders don’t make a lot of use of: objects.

Head First: Oh yes, objects. I believe our readers are learning about those in a later chapter.

Function: Fair enough, I’ll save my breath on that one for later.

Head First: Now this argument/parameter stuff all seems a little confusing.

Function: Think about it like this: each parameter acts like a variable throughout the body of the function. When you call the function, each value you pass in is assigned to a corresponding parameter.

Head First: And arguments are what?

Function: Oh, that’s just another name for the values you pass into a function... they’re the arguments of the function call.

Head First: Well you don’t seem all that great; I mean, okay you allow me to reuse code, and you have this way of passing values as parameters. Is that it? I don’t get the mystery around you.

Function: Oh, that’s just the basics, there’s so much more: I can return values, I can masquerade around your code anonymously, I can do a neat trick called closures, and I have an intimate relationship with objects.

Head First: Ohhhhh REALLY?! Can we get an exclusive on that relationship for our next interview?

Function: We’ll talk...

What can you pass to a function?

When you call a function you pass it arguments and those arguments then get matched up with the parameters in the function definition. You can pass pretty much any JavaScript value as an argument, like a string, a boolean, or a number:

image with no caption

You can also pass variables as arguments, and that’s often the more common case. Here’s the same function call using variables:

image with no caption

And, you can even use expressions as arguments:

image with no caption

image with no caption

No, they’re different.

When you define a function you can define it with one or more parameters.

image with no caption

When you call a function, you call it with arguments:

image with no caption

So you’ll only define your parameters once, but you’ll probably call your function with many different arguments.

BRAIN POWER

What does this code output? Are you sure?

function doIt(param) {

param = 2;

}

var test = 1;

doIt(test);

console.log(test);

EXERCISE

Below you’ll find some JavaScript code, including variables, function definitions and function calls. Your job is to identify all the variables, functions, arguments and parameters. Write the names of each in the appropriate boxes on the right. Check your answer at the end of the chapter before you go on.

image with no caption

JavaScript is pass-by-value.

That means pass-by-copy.

It’s important to understand how JavaScript passes arguments. JavaScript passes arguments to a function using pass-by-value. What that means is that each argument is copied into the parameter variable. Let’s look at a simple example to see how this works.

1. Let’s declare a variable age, and initialize it to the value 7.

var age = 7;

image with no caption

2. Now let’s declare a function addOne, with a parameter named x, that adds 1 to the value of x.

3. function addOne(x) {

4. x = x + 1;

}

image with no caption

5. Now let’s call the function addOne, pass it the variable age as the argument. The value in age is copied into the parameter x.

addOne(age);

image with no caption

6. Now the value of x is incremented by one. But remember x is a copy, so only x is incremented, not age.

image with no caption

image with no caption

We’re glad you’re thinking about it. Understanding how JavaScript passes values to functions is important. On the one hand it is pretty straightforward: when an argument is passed to a function its value is first copied and then assigned to the corresponding parameter. But, if you don’t understand this, you can make some wrong assumptions about how functions, arguments and parameters all work together.

The real impact of pass-by-value is that any changes to a parameter’s value within the function will affect only the parameter, not the original variable passed to the function. That’s pretty much it.

But of course, there’s an exception to every rule, and we’re going to have to talk about this topic again when we learn objects, which we’ll talk about in a couple of chapters. But no worries, with a solid understanding of pass-by-value, you’re in good shape to have that discussion.

And, for now, just remember that because of pass-by-value, whatever happens to a parameter in the function, stays in the function. Kinda like Vegas.

BRAIN POWER REVISITED

Remember this Brain Power? Do you think about it differently now, knowing about pass by value? Or did you guess correctly the first time?

function doIt(param) {

param = 2;

}

var test = 1;

doIt(test);

console.log(test);

Weird Functions

So far you’ve seen the normal way to use functions, but what happens when you experiment a little by, say, passing too many arguments to a function? Or not enough? Sounds dangerous. Let’s see what happens:

image with no caption

EXPERIMENT #1: what happens when we don’t pass enough arguments?

Sounds dicey, but all that really happens is each parameter that doesn’t have a matching argument is set to undefined. Here’s an example:

image with no caption

EXPERIMENT #2: what happens when we pass too many argments?

Ah, in this case JavaScript just ignores the extra. Here’s an example:

image with no caption

EXPERIMENT #3: what happens when we have NO parameters?

No worries, many functions have no parameters!

function barkAtTheMoon() {

console.log("Woooooooooooooo!");

}

barkAtTheMoon();

JAVASCRIPT CONSOLE

Woooooooooooooo!

Functions can return things too

You know how to communicate with your functions in one direction; that is, you know how to pass arguments to functions. But what about the other way? Can a function communicate back? Let’s check out the return statement:

image with no caption

Tracing through a function with a return statement

Now that you know how arguments and parameters work, and how you can return a value from a function, let’s trace through a function call from start to finish to see what happens at every step along the way. Be sure to follow the steps in order.

image with no caption

ANATOMY OF A FUNCTION

image with no caption

Now that you know how to define and call a function, let’s make sure we’ve got the syntax down cold. Here are all the parts of a function’s anatomy:

image with no caption

THERE ARE NO DUMB QUESTIONS

Q:

Q: What happens if I mix up the order of my arguments, so that I’m passing the wrong arguments into the parameters?

A:

A: All bets are off; in fact, we’d guess you’re pretty much guaranteed either an error at run time or incorrect code. Always take a careful look at a function’s parameters, so you know what arguments the function expects to be passed in.

Q:

Q: Why don’t the parameter names have var in front of them? A parameter is a new variable right?

A:

A: Effectively yes. The function does all the work of instantiating the variable for you, so you don’t need to supply the var keyword in front of your parameter names.

Q:

Q: What are the rules for function names?

A:

A: The rules for naming a function are the same as the rules for naming a variable. Just like with variables, you’ll want to use names that make sense to you when you read them, and provide some indication of what the function does, and you can use camel case (e.g. camelCase) to combine words in function names, just like with variables.

Q:

Q: What happens if I use the same name for an argument variable as the parameter? Like if I use the name x for both?

A:

A: Even if your argument and parameter have the same name, like x, the parameter x gets a copy of the argument x, so they are two different variables. Changing the value of the parameter x does not change the value of the argument x.

Q:

Q: What does a function return if it doesn’t have a return statement?

A:

A: A function without a return statement returns undefined.

image with no caption

Good catch. Yes and no.

These declarations work exactly the same within a function as they do outside a function, in the sense that you are initializing a new variable to a value. However, the difference between a variable declared outside a function and a variable declared inside a function is where that variable can be used—in other words, where in your JavaScript code you can reference the variable. If the variable is declared outside a function, then you can use it anywhere in your code. If a variable is declared inside a function, then you can use it only within that function. This is known as a variable’s scope. There are two kinds of scope: global and local.

image with no caption

Global and local variables

Know the difference or risk humiliation

You already know that you can declare a variable by using the var keyword and a name anywhere in your script:

image with no caption

And you’ve seen that you can also declare variables inside a function:

image with no caption

If a variable is declared outside a function, it’s GLOBAL. If it’s declared inside a function, it’s LOCAL.

But what does it matter? Variables are variables, right? Well, where you declare your variables determines how visible they are to other parts of your code, and, later, understanding how these two kinds of variables operate will help you write more maintainable code (not to mention, help you understand the code of others).

image with no caption

Another good catch.

There’s a long history of using the letter i as the variable you iterate with. This convention developed back in the days when space was limited (like when we used punched cards to write code), and there was an advantage to short variable names. Now it’s a convention all programmers understand. You’ll also commonly see j, k, and sometimes even x and y used in this manner. However, this is one of the only exceptions to the best practice of choosing meaningful variable names.

Knowing the scope of your local and global variables

Where you define your variables determines their scope; that is, where they’re visible to your code and where they aren’t. Let’s look at an example of both locally and globally scoped variables—remember, the variables you define outside a function are globally scoped, and the function variables are locally scoped: These four variables are globally scoped. That means they are defined and visible in all the code below.

image with no caption

image with no caption

The short lives of variables

When you’re a variable, you work hard and life can be short. That is, unless you’re a global variable, but even with globals, life has its limits. But what determines the life of a variable? Think about it like this:

Globals live as long as the page. A global variable begins life when its JavaScript is loaded into the page. But, your global variable’s life ends when the page goes away. Even if you reload the same page, all your global variables are destroyed and then recreated in the newly loaded page.

Local variables typically disappear when your function ends. Local variables are created when your function is first called and live until the function returns (with a value or not). That said, you can take the values of your local variables and return them from the function before the variables meet their digital maker.

NOTE

We say “typically” because there are some advanced ways to retain locals a little longer, but we’re not going to worry about them now.

So, there really is NO escape from the page is there? If you’re a local variable, your life comes and goes quickly, and if you’re lucky enough to be a global, you’re good as long as that browser doesn’t reload the page.

Don’t forget to declare your locals!

If you use a variable without declaring it first, that variable will be global. That means that even if you use a variable for the first time inside a function (because you meant for it to be local), the variable will actually be global, and be available outside the function too (which might cause confusion later). So, don’t forget to declare your locals!

If you forget to declare a variable before using it, the variable will always be global (even if the first time you use it is in a function).

image with no caption

This program behaves as if you’d written this instead:

image with no caption

image with no caption

image with no caption

You “shadow” your global.

Here’s what that means: say you have a global variable beanCounter and you then declare a function, like this:

image with no caption

When you do this, any references to beanCounter within the function refer to the local variable and not the global. So we say the global variable is in the shadow of the local variable (in other words we can’t see the global variable because the local version is in our way).

NOTE

Note that the local and global variables have no effect on each other: if you change one, it has no effect on the other. They are independent variables.

EXERCISE

Below you’ll find some JavaScript code, including variables, function definitions and function calls. Your job is to identify the variables used in all the arguments, parameters, local variables and global variables. Write the variable names in the appropriate boxes on the right. Then circle any variables that are shadowed. Check your answer at the end of the chapter.

image with no caption

FIRESIDE CHAT

image with no caption

Tonight’s talk: Global and Local variables argue over who is most important in a program.

Global variable:

Local variable:

Hey Local, I’m really not sure why you’re here because I can handle any need for a variable a coder might have. After all, I’m visible everywhere!

Yes but using globals everywhere is just bad style. Lots of functions need variables that are local. You know, their own private variables for their own use. Globals can be seen everywhere.

You have to admit that I could replace all your previous local variables with global ones and your functions would work just the same.

Well, yes and no. If you’re extremely careful, sure. But being that careful is difficult, and if you make a mistake, then we’ve got functions using variables that other functions are using for different purposes. You’d also be littering the program with global variables that you only need inside one function call... that would just make a huge mess.

It wouldn’t have to be a mess. Programmers could just create all the variables they need up at the top of a program, so they’d all be in one place...

Yeah, and so what happens if you need to call a function that needs a variable, like, oh I dunno, x, and you can’t remember what you’ve used x for before. You have to go searching all over your code to see if you’ve used x anywhere else! What a nightmare.

Well, if you’d use better names, then you might be able to keep track of your variables more easily.

And what about parameters? Function parameters are always local. So you can’t get around that.

True. But why bother with arguments and parameters if you’ve got all the values you need in globals?

Excuse me, do you hear what you’re saying? The whole point of functions is so we can reuse code to compute different things based on different inputs.

But your variables are just so... temporary. Locals come and go at a moment’s notice.

Face it. It’s just good programming practice to use local variables unless you absolutely need globals. And globals can get you into real trouble. I’ve seen JavaScript programs that barely use globals at all!

Not at all? Globals are the mainstay of JavaScript programmers!

Of inexperienced programmers, sure. But as programmers learn to correctly structure their code for correctness, maintainability, and just good coding style, they learn how to stop using globals except when necessary.

I think I need a drink.

They let globals drink? Now, we’re really in dangerous territory.

image with no caption

THERE ARE NO DUMB QUESTIONS

Q:

Q: Keeping track of the scope of all these locals and globals is confusing, so why not just stick to globals? That’s what I’ve always done.

A:

A: If you’re writing code that is complex or that needs to be maintained over a long period of time, then you really have to watch how you manage your variables. When you’re overzealous in creating global variables, it becomes difficult to track where your variables are being used (and where you’re making changes to your variables’ values), and that can lead to buggy code. All this becomes even more important when you’re writing code with co-workers or you’re using third-party libraries (although if those libraries are written well, they should be structured to avoid these issues).

So, use globals where it makes sense, but use them in moderation, and whenever possible, make your variables local. As you get more experience with JavaScript, you can investigate additional techniques to structure code so that it’s more maintainable.

Q:

Q: I have global variables in my page, but I’m loading in other JavaScript files as well. Do those files have separate sets of global variables?

A:

A: There is only one global scope so every file you load sees the same set of variables (and creates globals in the same space). That’s why it is so important you be careful with your use of variables to avoid clashes (and reduce or eliminate global variables when you can).

Q:

Q: If I use the same name for a parameter as I do for a global variable, does the parameter shadow the global?

A:

A: Yes. Just like if you declare a new, local variable in a function with the same name as a global, if you use the same name for a parameter as a global, you’re also going to shadow the global with that name. It’s perfectly fine to shadow a global name as long as you don’t want to use the global variable inside your function. But it’s a good idea to document what you’re doing with comments so you don’t get confused later when you’re reading your code.

Q:

Q: If I reload a page in the browser, do the global variables all get re-initialized?

A:

A: Yes. Reloading a page is like starting over from scratch as far as the variables are concerned. And if any code was in the middle of executing when you reload the page, any local variables will disappear, too.

Q:

Q: Should we always declare our local variables at the top of a function?

A:

A: Just like with global variables, you can declare local variables when you first need to use them in a function. However, it’s a good programming practice to go ahead and declare them at the top of your function so someone reading your code can easily find those declarations and get a sense at a glance of all the local variables used within the function. In addition, if you delay declaring a variable and then decide to use that variable earlier in the body of the function than you originally anticipated, you might get behavior that you don’t expect. JavaScript creates all local variables at the beginning of a function whether you declare them or not (this is called “hoisting” and we’ll come back to it later), but the variables are all undefined until they are assigned a value, which might not be what you want.

Q:

Q: Everyone seems to complain about the overuse of global variables in JavaScript. Why is this? Was the language badly designed or do people not know what they’re doing, or what? And what do we do about it?

A:

A: Globals are often overused in JavaScript. Some of this is because the language makes it easy to just jump in and start coding—and that’s a good thing—because JavaScript doesn’t enforce a lot of structure or overhead on you. The downside is when people write serious code this way and it has to be changed and maintained over the long term (and that pretty much describes all web pages). All that said, JavaScript is a powerful language that includes features like objects you can use to organize your code in a modular way. Many books have been written on that topic alone, and we’re going to give you a taste of objects in Chapter 5 (which is only a couple of chapters away).

image with no caption

Actually, you can put your functions anywhere in your JavaScript file.

JavaScript doesn’t care if your functions are declared before or after you use them. For instance, check out this code:

image with no caption

This might seem really odd, especially if you remember when the browser loads your page, it starts executing the JavaScript from the top to the bottom of your file. But, the truth is JavaScript actually makes two passes over your page: in the first pass it reads all the function definitions, and in the second it begins executing your code. So, that allows you to place functions anywhere in your file.

EXERCISE

The Thing-A-Ma-Jig

The Thing-A-Ma-Jig is quite a contraption—it clanks and clunks and even thunks, but what it really does, well, you’ve got us stumped. Coders claim they know how it works. Can you uncrack the code and find its quirks?

image with no caption

image with no caption

image with no caption

WEBVILLE GUIDE TO CODE HYGIENE

image with no caption

In Webville we like to keep things clean, organized and ready for expansion. There’s no place that needs to be better maintained than your code, and JavaScript can seem pretty loosey-goosey when it comes to organizing your variables and functions. So we’ve put together a neat little guide for you that makes a few recommendations for those new to Webville. Take one, they’re FREE.

Global variables, right at the TOP!

It’s a good idea to keep your globals grouped together as much as possible, and if they’re all up at the top, it’s easy to find them. Now you don’t have to do this, but isn’t it easier for you and others to locate the variables used in your code if they’re all at the top?

Functions like to sit together.

Well, not really; they actually don’t care, they’re just functions. But, if you keep your functions together, it’s a lot easier to locate them. As you know, the browser actually scans your JavaScript for the functions before it does anything else. So you can place them at the top or bottom of the file, but if you keep them in one place your life will be easier. Here in Webville, we often start with our global variables and then put our functions next.

Let your local variables be declared at the TOP of the function they’re in.

Put all your local variable declarations at the beginning of the function body. This makes them easy to find and ensures they are all declared properly before use.

That’s it, just be safe and we hope you enjoy your time coding in Webville!

image with no caption

WHO AM I?

image with no caption

A bunch of JavaScript attendees, in full costume, are playing a party game, “Who am I?” They give you a clue, and you try to guess who they are, based on what they say. Assume they always tell the truth about themselves. Fill in the blank next to each sentence with the name of one attendee.

Tonight’s attendees:

function, argument, return, scope, local variable, global variable, pass-by-value, parameter, function call, Math.random, built-in functions, code reuse.

I get passed into a function. ______________________________

I send values back to the calling code. ______________________________

I’m the all important keyword. ______________________________

I’m what receives arguments. ______________________________

It really means ‘make a copy’. ______________________________

I’m everywhere. ______________________________

Another phrase for invoking a function. ______________________________

Example of a function attached to an object. ______________________________

alert and prompt are examples. ______________________________

What functions are great for. ______________________________

Where I can be seen. ______________________________

I’m around when my function is. ______________________________

FIVE MINUTE MYSTERY

image with no caption

The case of the attempted robbery not worth investigating

Sherlock finished his phone call with the bumbling chief of police, Lestrade, and sat down in front of the fireplace to resume reading the newspaper. Watson looked at him expectantly.

“What?” said Sherlock, not looking up from the paper.

“Well? What did Lestrade have to say?” Watson asked.

“Oh, he said they found a bit of rogue code in the bank account where the suspicious activity was taking place.”

“And?” Watson said, trying to hide his frustration.

“Lestrade emailed me the code, and I told him it wasn’t worth pursuing. The criminal made a fatal flaw and will never be able to actually steal the money,” Sherlock said.

“How do you know?” Watson asked.

“It’s obvious if you know where to look,” Sherlock exclaimed. “Now stop bothering me with questions and let me finish this paper.”

With Sherlock absorbed in the latest news, Watson snuck a peek at Sherlock’s phone and pulled up Lestrade’s email to look at the code.

image with no caption

Why did Sherlock decide not to investigate the case? How could he know that the criminal would never be able to steal the money just by looking at the code? Is there one problem with the code? Or more?

BULLET POINTS

§ Declare a function using the function keyword, followed by the name of the function.

§ Use parentheses to enclose any parameters a function has. Use empty parentheses if there are no parameters.

§ Enclose the body of the function in curly braces.

§ The statements in the body of a function are executed when you call a function.

§ Calling a function and invoking a function are the same thing.

§ You call a function by using its name and passing arguments to the function’s parameters (if any).

§ A function can optionally return a value using the return statement.

§ A function creates a local scope for parameters and any local variables the function uses.

§ Variables are either in the global scope (visible everywhere in your program) or in the local scope (visible only in the function where they are declared).

§ Declare local variables at the top of the body of your function.

§ If you forget to declare a local variable using var, that variable will be global, which could have unintended consequences in your program.

§ Functions are a good way to organize your code and create reusable chunks of code.

§ You can customize the code in a function by passing in arguments to parameters (and using different arguments to get different results).

§ Functions are also a good way to reduce or eliminate duplicate code.

§ You can use JavaScript’s many built-in functions, like alert, prompt, and Math.random, to do work in your programs.

§ Using built-in functions means using existing code you don’t have to write yourself.

§ It’s a good idea to organize your code so your functions are together, and your global variables are together, at the top of your JavaScript file.

JAVASCRIPT CROSS

In this chapter you got functional. Now use some brain functions to do this crossword.

image with no caption

Across

Down

4. A parameter acts like a _________ in the body of a function.

6. JavaScript uses __________ when passing arguments to functions.

10. You can declare your functions __________ in your JavaScript file.

11. What gets returned from a function without a return statement.

13. Local variables disappear when the _________ returns.

16. If you forget to declare your locals, they’ll be treated like ________.

17. A local variable can __________ a global variable.

1. A variable with global ________ is visible everywhere.

2. Use functions so you can _______ code over and over again.

3. The variables that arguments land in when they get passed to functions.

5. To get a value back from a function, use the ________ statement.

7. What gets passed to functions.

8. When you reload your page, all your __________ get re-initialized.

9. ________ through your code means following the execution line by line.

12. Watson looked at the bank heist code in Sherlock’s ______ on his phone.

14. It’s better to use ________ variables whenever you can.

15. Extra arguments to a function are __________.

SHARPEN YOUR PENCIL SOLUTION

Do a little analysis of the code below. How does it look? Choose as many of the options below as you like, or write in your own analysis. Here’s our solution.

var dogName = "rover";

var dogWeight = 23;

if (dogWeight > 20) {

console.log(dogName + " says WOOF WOOF");

} else {

console.log(dogName + " says woof woof");

}

dogName = "spot";

dogWeight = 13;

if (dogWeight > 20) {

console.log(dogName + " says WOOF WOOF");

} else {

console.log(dogName + " says woof woof");

}

dogName = "spike";

dogWeight = 53;

if (dogWeight > 20) {

console.log(dogName + " says WOOF WOOF");

} else {

console.log(dogName + " says woof woof");

}

dogName = "lady";

dogWeight = 17;

if (dogWeight > 20) {

console.log(dogName + " says WOOF WOOF");

} else {

console.log(dogName + " says woof woof");

}

NOTE

We chose all of them!

A. The code seems very redundant.

B. If we wanted to change how this outputs, or if we wanted to add another weight for dogs, this is going to require a lot of reworking..

C. Looks tedious to type in!

D. Not the most readable code I’ve ever seen.

E. Looks like the developer thought the weights might change over time.

SHARPEN YOUR PENCIL SOLUTION

We’ve got some more calls to bark below. Next to each call, write what you think the output should be, or if you think the code will cause an error. Here’s our solution.

image with no caption

CODE MAGNETS SOLUTION

image with no caption

This working JavaScript code is all scrambled up on the fridge. Can you reconstruct the code snippets to make a working program that produces the output listed below? Notice, there may be some extra code on the fridge, so you may not use all the magnets. Here’s our solution.

image with no caption

JAVASCRIPT CONSOLE

Wear a jacket

Wear a t-shirt

Wear a sweater

EXERCISE SOLUTION

Below you’ll find some JavaScript code, including variables, function definitions and function calls. Your job is to identify all the variables, functions, arguments and parameters. Write the names of each in the appropriate boxes on the right. Here’s our solution.

image with no caption

EXERCISE SOLUTION

Below you’ll find some JavaScript code, including variables, function definitions and function calls. Your job is to identify the variables used in all the arguments, parameters, local variables and global variables. Write the variable names in the appropriate boxes on the right. Then circle any variables that are shadowed. Here’s our solution.

image with no caption

EXERCISE SOLUTION

The Thing-A-Ma-Jig

The Thing-A-Ma-Jig is quite a contraption—it clanks and clunks and even thunks, but what it really does, well, you’ve got us stumped. Coders claim they know how it works. Can you uncrack the code and find its quirks?

image with no caption

FIVE MINUTE MYSTERY SOLUTION

image with no caption

Why did Sherlock decide not to investigate the case? How could he know that the criminal would never be able to steal the money just by looking at the code? Is there one problem with the code? Or more? Here’s our solution.

image with no caption

WHO AM I? SOLUTION

image with no caption

A bunch of JavaScript attendees, in full costume, are playing a party game, “Who am I?” They give you a clue, and you try to guess who they are, based on what they say. Assume they always tell the truth about themselves. Fill in the blank next to each sentence with the name of one attendee. Here’s our solution.

Tonight’s attendees:

function, argument, return, scope, local variable, global variable, pass-by-value, parameter, function call, Math.random, built-in functions, code reuse.

I get passed into a function. argument

I send values back to the calling code. return

I’m the all important keyword. function

I’m what receives arguments. parameter

It really means ‘make a copy’. pass-by-value

I’m everywhere. global variable

Another phrase for invoking a function. function call

Example of a function attached to an object. Math.random

alert and prompt are examples. built-in functions

What functions are great for. code reuse

Where I can be seen. scope

I’m around when my function is. local variable

JAVASCRIPT CROSS SOLUTION

image with no caption