A Bit About JavaScript

Although who am I kidding, this turned out to be quite a hefty chapter

In this section, I've put together the JavaScript knowledge you need to avoid "beginner" problems when using jQuery. If you already have experience with JavaScript, feel free to skip ahead.

Want to learn JavaScript and jQuery? Then first master the power of the true instrument:

The list isn't complete, but the consolearrow-up-right is there, and you need to know how to use it

On Formatting

I'd like to immediately draw your attention to JavaScript code formatting. My experience tells me -- the best approach is to project the formatting standards of your main development language onto JavaScript. And if you want something global and widely accepted, I've already googled it for you:

As a bonus, here's a small tip: all variables containing a jQuery object are best named starting with the "$" symbol. Trust me, this little trick saves a lot of time.

JavaScript Basics

Variables

The first thing we'll encounter is variable declaration:

Pretty simple -- we declare a variable using the var keyword.

circle-info

You can skip the var, of course, but I strongly advise against it, because unexpected problems may arise in your code, which I'll tell you about a bit later.

Yes, yes, JavaScript is a dynamically typed language, and we don't need to specify the data type when declaring variables. You can even start a "holy war" over this, but please keep it inside your own head.

Two restrictions apply to variable names:

  • the name can consist of letters, digits, and the "$" and "_" symbols

  • the first character must not be a digit

Keep in mind, letter case matters:

I'd also like to introduce you to an ES6 (a.k.a. ECMAScript-2015 or ES-2015) feature -- declaring variables using the let construct:

On the surface, it doesn't look much different from var, but what a difference in behavior:

  • the scope of a let variable is limited to the block {...}, unlike var, which is visible everywhere within the function:

    here's how a variable declared with var behaves:

    now compare that with let:

  • a let variable is only visible after its declaration:

    "var":

    "let":

  • a let variable cannot be re-declared:

    "var":

    "let":

  • inside a loop, let creates a new variable for each iteration:

    "var":

    "let":

Here's your next challenge -- guess the values of x and y in the following example:

chevron-rightanswerhashtag

Constants

JavaScript had no constants before ES6, but since the need for them existed, there was an unspoken agreement: variables written in UPPER_CASE with underscores should not be changed:

circle-info

Such constants are needed to avoid "magic numbers".

Look at this code if(status==2) -- what it's about is hardly clear to anyone, but if(status==USER_STATUS_BANNED) is already much more informative.

In the ES-2015 era, we use const, and JavaScript takes care of the rest:

Yeah-yeah, I'll repeat myself -- this is a perfect example of proper constant naming. The name clearly indicates what's stored -- "active user status".

It's worth noting separately that a constant doesn't allow you to change the variable itself, but if you assign an object or array to a constant, you can do whatever your heart desires with it:

And there you go -- "readable" code. Take note.

Data Types

JavaScript doesn't have all that many data types:

  • number -- integer or floating-point:

    there are also the following special values:

    • Infinity -- beyond 1.7976931348623157E+10308 (i.e. bigger)

    • -Infinity -- beyond -1.7976931348623157E+10308 (i.e. smaller)

    • NaN (not-a-number) -- the result of a numeric operation that failed; for example, try running this code in the console:

      but keep in mind -- there's only one correct way to check a computation result for NaN:

      and many wrong ones:

  • string -- a string, enclosed in quotes:

    In JavaScript there's no difference between double and single quotes, you just need to make sure they match (hello PHP and Ruby).

  • boolean -- a boolean value, i.e. either "true" or "false"

  • object -- these are objects; I'll cover them in more detail shortly...

  • symbol -- a data type from ES6, used for creating unique identifiers (I won't be covering it, it's not widely used yet)

  • null -- a special value for defining "emptiness"

  • undefined -- another special value, for "undefinedness", used as the value of an undefined or non-existent variable. For example, if a variable is declared but no value has been assigned to it yet:

    In the second example, a surprise may await us if something defines a variable named "undefined"; I'll tell you how to work around this "unpleasantness" later.

circle-info

I also want to draw your attention to type coercion in JavaScript. This is a topic that causes many questions for beginner developers, and bugs related to it will haunt you for the first six months of work. Open the tutorial page about operator quirksarrow-up-right, study it, and when you're ready, move on to the next exercise.

Take a careful look at the code and tell me -- what will the result be:

chevron-rightanswerhashtag

Arrays

An array is a data collection with numeric indices. Data can be of any type; as an example, I'll show one of the simplest cases -- an array of strings:

Array numbering starts at "0", so to get the first element you'll need this code:

The array size is stored in the length property:

circle-info

In reality, length returns the index of the last array element + 1, so don't fall for this "beginner mistake":

The best way to iterate over an array is with a for(;;) loop:

In the previous example, the loop would show four undefined values, which could cause problems, and only then work with the value 10. The similar but not equivalent for (in) loop behaves differently (it will go straight to the value 10). Loop example:

To work with the last element of an array, use the push() and pop() methods:

To work with the first element of an array, use the unshift() and shift() methods:

The last two methods are slow because they rebuild the entire array step by step.

Exercise to reinforce the material:

  • how do I get the user named Andrey from the users array?

  • what is the array length?

chevron-rightanswerhashtag

Functions

Functions in JavaScript are simple. Here's an elementary example:

Simple, until you start talking about anonymous functions...

Anonymous Functions

In JavaScript you can create an anonymous function (i.e. a function without a name). All you need to do is slightly modify the previous construct:

Since a function is a perfectly valid object, you can assign it to a variable and/or pass it as a parameter to another function:

You can create an anonymous function and immediately invoke it with the required parameters:

It's not that hard. Soon you'll get used to them, and you'll miss them in other languages.

Arrow Functions

Ah, ES6 -- it brought an even more concise form for creating functions, the so-called "arrow functions":

This syntax is convenient, of course, but don't overdo it -- if you go too far, your code becomes unreadable, and you might end up hearing some rather unflattering words directed at you.

circle-info

Arrow functions have some other peculiarities too, but this isn't a JavaScript textbookarrow-up-right after all ;)

Solve a simple FizzBuzz problem:

Write a function that takes a number as an argument. If the number is divisible by 3, the function should output Fizz; if divisible by 5, then Buzz; if divisible by both 3 and 5, the function should return FizzBuzz; otherwise, return the number itself

chevron-rightanswerhashtag

Objects

Objects in JavaScript serve two roles:

  • data storage

  • object functionality

The first purpose can be described with the following code:

This is essentially an implementation of a key-value store, or a hash, or an associative array, or... Well, you get it, lots of names. In JavaScript, it's an object, and the notation above is JSON or JavaScript Object Notation (with a few caveats, though).

To iterate over such a store, you can use the for(.. in ..) loop:

Classes

Classes, constructors, and all that in JavaScript are a bit more complex, although to understand them you don't need that much. Remember this: any function called with the new keyword returns an object, and the function itself becomes the constructor of that object:

The behavior of the User() function when using new changes slightly:

  1. This construct will create a new, empty object

  2. The this keyword will get a reference to this object

  3. The function will execute and possibly modify the object via this (as in the example above)

  4. The function will return this (by default)

The result of executing the code will be the following object:

The ES6 (ES2015) standard introduced the class construct, which is essentially syntactic sugar for JavaScript -- specifically for those who don't like working with prototypes (yep, people like me).

If we rewrite the code above using classes, we get the following:

Off you go again to read the JavaScript textbookarrow-up-right :)

A simple task to reinforce the material:

Write a class for a cat, so we can find out its breed and color.

chevron-rightanswerhashtag

Scope and this

For those just starting their acquaintance with JavaScript, here are a few nuances:

  • when you declare a variable or function, it becomes part of "window":

  • when the desired variable is not found in the current scope, the search continues in the parent function's scope:

  • the magical this variable always points to the current object calling the function (since by default all variables and functions end up in "window", then "this == window"):

Everything related to "window" only applies to browsers. And since this book is about jQuery, I'm not covering any other behavior. But I'm dropping a not-so-subtle hint that there's an alternative reality with its own "jQuery", and it goes by the name cheerioarrow-up-right ;).

Closures

Once you understand closures, a lot of JavaScript magic will make sense. Here's a code example with explanations:

What's happening here? A function declared inside another function has access to the parent function's variables. Stare at the code until it clicks.

A great exercise that fully illustrates the essence of the problem: "An Army of Functionsarrow-up-right"

Recommended articles on the topic:

This JavaScript intro has dragged on. You'd better not be lazy and study the entire textbook by Ilya Kantorarrow-up-right.

Last updated