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

Understanding JavaScript style

From: JavaScript Essential Training

Video: Understanding JavaScript style

When we talk about style with programming languages, we're moving away from the rules of how you must and must not write JavaScript into more of how you should and shouldn't write it. So how should you name your variables, where should you put your braces, what should you call your functions, and where should they be placed in your code? Because this matters. Style decisions matter for you and for other developers on your team. You want your code to be readable, you want it to be consistent, and you also kind of need to play along with how everyone else in the world is writing their JavaScript, because that's going to make it easier to read example code and read books and, more importantly, recognize whether that code is written well.

Understanding JavaScript style

When we talk about style with programming languages, we're moving away from the rules of how you must and must not write JavaScript into more of how you should and shouldn't write it. So how should you name your variables, where should you put your braces, what should you call your functions, and where should they be placed in your code? Because this matters. Style decisions matter for you and for other developers on your team. You want your code to be readable, you want it to be consistent, and you also kind of need to play along with how everyone else in the world is writing their JavaScript, because that's going to make it easier to read example code and read books and, more importantly, recognize whether that code is written well.

And style matters simply because JavaScript is the most publicly viewable programming language in the world. Unlike a desktop application, with JavaScript running on a web page, all your code is sent to whoever requests it. Every client's browser gets a copy of your JavaScript in plain readable text. Sure, most people won't look at it, but they could. They can view source. They can use tools like Firebug to get to it. Other web developers can see how you write your code. So think of all the JavaScript you write as effectively being published on the web and get into good habits early.

So what are these good habits? Well, let's begin with some naming conventions. We get to choose names for variables, functions, even objects, if you define your own objects. Now, the rules of JavaScript say you must use letters, numbers, dollar sign, and underscore, and you can't start with a number, but that doesn't mean that something like this would be a good name for a variable. We want clarity. We want readability. We want meaning. Yes, okay, when we're learning, we use placeholder names a lot: var a, var b, var c, x is a pretty common one, or common meaningless words like foo or bar.

But our real JavaScript variables will represent meaningful information: the name in a textbox, a date, the height and width of an image, or a collection of element nodes that represent the links in a menu. So naming conventions have developed over the years, and these days the dominant way JavaScript is written is this. Variables and functions, which will be most of what you name yourself, are written in camelCase. The word would start lowercase. If it's just one world like score, it would be all lowercase. But with multiple words you capitalize the first letter of each subsequent word, like the hump of a camel.

Multiple words are not separated with underscores as they might be in some other programming language. Functions are named the same way, or methods if they're in an object. Now, these are typically multiple words for clarity and often in a loose verb noun format. Think of the way that we work with the DOM: createElement, appendChild, getElementById. When we're working with objects, the convention here is to also capitalize the first word.

And quite often objects only aren't one word. Think of the way we've seen objects in JavaScript, like the Math object and the Date object and the Array object. Now, bear in mind, we still use camelCase too. After all you create a variable that uses camelCase that's based on an object that capitalizes the first letter. Now, if you're coming from a language that uses underscores a lot, or prefixes variables with an abbreviation that's meant to represent the type of information, you can argue against camelCase as much as you like.

There is nothing stopping you from using your favorite naming style, but camelCase is the dominant style for JavaScript. It is what's recommended by the Yahoo! style guidelines, by the Google style guidelines. It's what's used by the popular JavaScript libraries, like jQuery and Prototype, and of course it's what's used by the DOM methods themselves. There is no escaping camelCase in JavaScript. Let's talk about brace style, where to put the opening and closing curly braces. The dominant style in JavaScript is the most traditional brace style for C-based languages.

If you have an if statement or a while loop, the curly brace opens on the same line as the keyword, as the if or the while or the for. The code is indented inside the block, and the closing curly brace is on a line by itself. If you're adding an else to a if statement, you'll typically see that continued on the same line, again, with the opening curly brace of the next section on the same line as the keyword. Now, there are other ways, like Pascal or Allman style, when the opening braces on its own line and lines up with the closing brace, but I avoid this style in JavaScript.

Now, while it wouldn't matter in most languages, in JavaScript you can run into a situation with JavaScript's own ability to insert what it thinks are missing semicolons on lines that don't have them. It's a rare issue, so I'm not going to get into specifics, but if I use the style on the left, I don't have to worry, and it is the standard style. So for all your ifs, your whiles, your functions, all of these constructs, open the curly brace on the same line as the keyword, the while, the for, or the function. And while we're talking about blocks of code, as in other C-based languages, if you have say an if statement that only does one thing, you can technically remove the curly braces.

If there is one statement after the if and the condition, it behaves as if there are curly braces around it. But, as in other C-based languages, it's a really bad idea to do this, because later on it's super easy to add a line of code to this. And when you read this code what you think you're getting is this kind of block, where if x is more than 500 we're going to execute these two lines, but if we left the braces off, what we're actually getting is this.

If the condition is true, we will pop up the alert and we will always then go ahead and reset everything. And these kind of bugs can be a real pain to recognize, so always use the curly braces, even for one-line blocks. Now, another general rule here is even though you don't have to define your functions before you call them--so, for example, here I've got one function called some function that called other function, and other function is nicely defined after it in our code file-- the preference and the best practice is to define your functions before they are called.

In some languages you have to do this. In JavaScript you don't have to, but it does make for more readable and more usable code. So to review, we can really keep a few simple rules in mind: Use camelCase for variables, functions, and methods, and this will be the majority of what you have to name yourself. Open curly braces on the same line as the keyword. Always use blocks, even if there's only one line. Define your functions before you call them. And a couple of things we've been talking about along the way: always use semicolons to end a statement--even if you might not have to, you should--and always use var when declaring a variable.

We could go deeper than this with style, but that's enough to get us started. If you do want to go deeper and more formal, do a search for the phrase 'javascript style guidelines' and you'll find some really good documentation that have been created by the JavaScript developers at places like Yahoo! and Google and Mozilla. Now, I don't have a personal favorite, but if you're after something more formal, just take a look at these and be consistent about the way you write your code.

Show transcript

This video is part of

Image for JavaScript Essential Training
JavaScript Essential Training

56 video lessons · 105006 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.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

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.