Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Creating functions

From: JavaScript Essential Training

Video: Creating functions

As we start to add more code, we want to make sure that it doesn't get messy and hard to read, so as with all languages, we are going to break apart large amounts of JavaScript into smaller reusable modular pieces. All we are doing is taking several statements, wrapping them up, and giving them a name, and that means we are creating functions. In other languages, these might be called modules or subroutines, but in JavaScript it's functions. To make one, we take the code that we want to enclose-- this could be one line, it could be a hundred lines-- we surround it with curly braces to create a code block to say where this function starts and ends.

Creating functions

As we start to add more code, we want to make sure that it doesn't get messy and hard to read, so as with all languages, we are going to break apart large amounts of JavaScript into smaller reusable modular pieces. All we are doing is taking several statements, wrapping them up, and giving them a name, and that means we are creating functions. In other languages, these might be called modules or subroutines, but in JavaScript it's functions. To make one, we take the code that we want to enclose-- this could be one line, it could be a hundred lines-- we surround it with curly braces to create a code block to say where this function starts and ends.

We need to say what this is, so we actually use the JavaScript word 'function all lowercase, and because we could have dozens or hundreds of these, we also give it a name. This part, like variables, is up to us. The name has to be one word. There can't be any spaces. You can use letters, numbers, Dollar sign, and underscore, but you can't start with a number. And the function name should simply be descriptive of what it does. I will just be generic right now. And then after the name of the function we need to have opening and closing parentheses.

These say whether this function expects to have data passed into it, and in this case empty parentheses means no, it doesn't. Now after the function is declared, then we can call it. Sometime in our code we can use the name of the function with the opening and closing parentheses, semicolon--because it is a full statement--and all the code in the function will be executed. We could do it again. We could do it again. Now, note that as soon as you put your code in a function, it won't execute.

It won't run unless you explicitly call it. Now as you start to write files of JavaScript, you'll end up having a lot of functions, and it doesn't officially matter where you put them in your file, because the JavaScript engine will first do a quick scan of your code and figure out what functions exist before it tries to run anything. But it's a best practice to define your functions before you call them. So in this case, for example, I have got the first line of code saying myFunction, but myFunction isn't declared till afterwards, which then calls myOtherFunction, which itself isn't declared till after that.

It's a better practice to rearrange them so that functions are defined and declared before you use them. You don't have to, but it makes for more readable code. Typically, that just means you are going to define all your functions up at the top of your JavaScript file. It's very common to create functions that expect parameters, they expect to be passed information. Now to do this, we take our parentheses and we put our parameters in there. We say how many pieces of information are going to be passed and what do I want to call them? We don't need the word var.

I am just saying here I expect to be passed one piece of information and I am going to call it x. So in the code inside myFunction, I will have this variable called x that I can play around with. Or if I want two, three, four, parameters, I just separate them with commas. You call them whatever you want. It's the same rules as variable naming. So defining a function that takes X,Y means that inside the code I can just treat X and Y as if they exist, in this case making a new variable from them.

Whatever is passed in I will multiply together, and then I will log out the result. And then again later in the code I can call this function. First off, I am passing in two number. Then I can call it again, pass in a couple of different numbers, and so on. Now if the format looks familiar, that's because we're using this when we use that alert, or we when we use console.log. Alert is a built-in function in JavaScript. It takes a long piece of information; in this case, we are passing in a string.

And we can optionally return values. Not only can the function accept information, but we can also send some back, and you can do one or the other, or both, or neither. If I want to return the information, all I use is the word return and then pass back a variable, or a literal, like a string literal in double quotes, or a number--it's up to you. Those of you who come from other programming languages might think, "Well, surely the function has to be defined differently if we return a value," and in JavaScript, no it doesn't. This is all we do.

You don't have to return anything from a function. It's up to you. Now what this format means is that later on I could use this function to create a result. And in fact in the last line here, I am creating a new variable and setting it equal to whatever is returned from passing in the numbers 6 and 9 into my function. Now if a function does return a value and you don't do anything with it, you are just calling the function. That will just be ignored. Now one of the usual issues with functions that take parameters is what happens if you get something wrong with them? What happens if you pass the wrong amount of information in there? Let's say we have a function defined called calculateLoan.

This takes four parameters--amount, months, interest, and name--and it presumably does something with them inside the body of the code. The way that we should call it is just by passing those four parameters in order, and inside our function, when it runs, we will have amount equal to 10,000, months equal to 60, interest equal to 7, and name equal to Sam Jones. Now if I call myFunction and I pass in an extra parameter here, in a lot of other programming languages this would break your code; in JavaScript it will just ignore it.

That extra one we drop off the end. We are effectively just running the function just fine. And the flip side of that, what happens if I pass in too few parameters? What will happen is that the missing one will be passed as undefined. interest and name in this case will be undefined variables. Now your function code might be able to deal with that, and it might not. So it doesn't necessarily mean it will work, but this is what will happen. And one last thing, we are going to talk about something called variable scope here.

Now, scope of a variable simply means where is this variable visible? What part of your code can see it, what part of your code can use it? So, I have got a function declared here called simpleFunction. It has got some code in it, and then we have a line that declares a variable foo=500. We then have console.log foo and if we call this variable, it's going to output 500 to the console. But let's say right after I call this variable, I then write another line of code that says console.log(foo), and then I run console.log(foo), trying to write out the contents of that foo variable.

I know this function has already run, so surely I can write it out. But no, what I get here is the message undefined because outside the function, as far as JavaScript is concerned, foo doesn't exist. That's because when we use the word var inside a function definition, this creates a variable that's known as a local variable. It only exists and is only relevant inside the function itself. If I needed to have a variable that was visible throughout my entire file of code, what I'd do is I would declare foo outside the function.

This now becomes what's called a global variable if it's declared at the absolute top level and outside any function that you have. Then what I need to do inside the function is I don't need to define it again, so I am not using a word var. foo can be set to 500. We can write it out inside the function, and we can write it out outside the function. Now, usually when you're declaring variables inside a function, you only want to access them inside the functions, so using var is absolutely fine, but just be aware that you have this concept of local variables with functions. And for those of you coming from other languages with variable scope, know that this is only relevant with JavaScript inside functions.

This doesn't apply to other code blocks like loops and if statements and so on. It's a very simple split. You use var inside the function, it only exits inside the function; otherwise, it's available everywhere.

Show transcript

This video is part of

Image for JavaScript Essential Training
JavaScript Essential Training

56 video lessons · 112452 viewers

Simon Allardice
Author

 
Expand all | Collapse all
  1. 3m 28s
    1. Welcome
      1m 1s
    2. What you should know
      1m 44s
    3. Using the exercise files
      43s
  2. 15m 41s
    1. Introduction to JavaScript
      8m 6s
    2. Creating your first JavaScript
      2m 13s
    3. Getting to know the tools and applications
      5m 22s
  3. 56m 8s
    1. Understanding the structure of JavaScript code
      7m 9s
    2. Where to write your JavaScript
      3m 56s
    3. Creating variables
      6m 21s
    4. Working with conditional code
      5m 44s
    5. Working with operators
      13m 28s
    6. Sending messages to the console
      2m 59s
    7. Working with loops
      8m 1s
    8. Creating functions
      8m 30s
  4. 36m 13s
    1. Working with arrays
      7m 57s
    2. Working with numbers
      6m 13s
    3. Working with strings
      8m 27s
    4. Working with dates
      5m 38s
    5. Working with objects
      7m 58s
  5. 9m 6s
    1. What is the DOM?
      5m 49s
    2. Working with nodes and elements
      3m 17s
  6. 25m 17s
    1. Accessing DOM elements
      11m 3s
    2. Changing DOM elements
      5m 42s
    3. Creating DOM elements
      8m 32s
  7. 24m 45s
    1. Introduction to JavaScript event handling
      8m 16s
    2. Working with onClick and onLoad events
      7m 36s
    3. Working with onBlur and onFocus events
      2m 36s
    4. Working with timers
      6m 17s
  8. 21m 41s
    1. Common JavaScript errors
      7m 14s
    2. Using Firebug
      4m 7s
    3. Going through a debugging session
      10m 20s
  9. 10m 13s
    1. Accessing form elements
      4m 20s
    2. Preventing a form from being submitted
      2m 36s
    3. Hiding and showing form sections
      3m 17s
  10. 9m 49s
    1. CSS and JavaScript
      3m 46s
    2. Removing and applying CSS classes
      2m 16s
    3. Changing inline styles
      3m 47s
  11. 19m 44s
    1. Understanding JavaScript style
      7m 39s
    2. Minifying your code
      4m 28s
    3. Using JavaScript code checkers
      7m 37s
  12. 22m 24s
    1. Introduction to JavaScript libraries
      3m 17s
    2. Linking to multiple JavaScript files
      2m 11s
    3. Introduction to jQuery
      12m 7s
    4. Using a content distribution network to deliver JavaScript files
      4m 49s
  13. 17m 35s
    1. JavaScript in HTML5
      9m 37s
    2. Using Modernizr
      3m 2s
    3. Using Strict Mode
      4m 56s
  14. 33m 3s
    1. Knowing the JavaScript to avoid
      6m 35s
    2. Introduction to regular expressions
      6m 56s
    3. Working with AJAX
      10m 44s
    4. Working with objects and prototypes
      8m 48s
  15. 21m 10s
    1. Example: Countdown
      8m 3s
    2. Example: Resize
      5m 47s
    3. Example: Accordion
      7m 20s
  16. 4m 58s
    1. Where to go from here
      4m 0s
    2. Goodbye
      58s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ .

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Join now Already a member? Log in

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed JavaScript Essential Training.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member ?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferences from the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Learn more, save more. Upgrade today!

Get our Annual Premium Membership at our best savings yet.

Upgrade to our Annual Premium Membership today and get even more value from your lynda.com subscription:

“In a way, I feel like you are rooting for me. Like you are really invested in my experience, and want me to get as much out of these courses as possible this is the best place to start on your journey to learning new material.”— Nadine H.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.