Introduction to JavaScript Syntax
00:00 The previous lesson was a deep dive on objects and classes in JavaScript. In this lesson, I’m going to change it up and go for breadth instead. Rapid fire, I’ll go through all sorts of JavaScript syntax for you.
00:13 You’ve seen this idea before. JavaScript uses braces, also known as curly brackets, to identify code blocks. This is quite common in programming languages and Python really is the outlier here. The location of the brace isn’t important.
00:26 It can be on the same line or different lines. This is a stylistic choice. It’s also the kind of thing wars are fought over. What I’ve done here by using both styles is likely a hanging offense somewhere.
00:38
You can even get away without the curly brackets in the case of an if
statement if there’s only a single line after it. I generally don’t recommend this, though.
00:46
It is really easy to forget to add the curly brackets when your single line becomes multiline. This is also a tricky bug to find. If you forget the curly brackets after an if
statement, you’re only going to be doing the conditional on the line immediately after it, even if your code is indented.
01:03 One last thing: Because of the curly brackets, the amount of indentation is also a style thing. I typically use four spaces because that’s the way the tab versus spaces thing has fallen out in places I’ve worked. A lot of JavaScript shops prefer two spaces.
01:18
This comes from the fact that JavaScript is used on the web and HTML tends to use two spaces because there’s a ton of indentation in HTML. Using for
would go off the right-hand margin pretty quickly. Like Python, JavaScript supports a ternary operator.
01:34
This is occasionally called the Elvis operator. Think of Elvis’s hairdo and look at the question mark (?
). This code is the same as the previous slide, except shorter. Before the question mark is the condition. After the question mark is the action to do if True
, and then after the colon (:
) is the action to do if False
. Ternary operators make for shorter code.
01:56 I’m not a fan, personally. I find them too dense and hard to read, but there are coders who swear by them.
02:03
Java and C both use semicolons (;
) to indicate the end of a statement. JavaScript included this idea to make transitioning between languages easier, but also automatically inserts them in most cases.
02:15 If you were paying close attention in previous lessons, you’ll have noticed I’ve been pretty sloppy about it. This, again, is mostly a stylistic thing. There are a couple of corner cases where it becomes important and I’ll cover those later when I talk about language quirks.
02:30
The names of functions and variables in JavaScript follow similar rules to Python. An identifier can be made up of letters, numbers, underscores (-
), and dollar signs ($
). It cannot start with a number and is case sensitive.
02:44 Although the dollar sign is supported, in very old versions it had a special meaning and should be avoided for that reason. Similarly, support for non-ASCII characters has changed over time but like all programming languages, it is best to avoid these things, particularly when you get into non-ASCII characters that look like ASCII characters.
03:04 Identifier naming conventions is one of those places where I fail when I write JavaScript. I’m sure seasoned JavaScript veterans would look at my code and scream “Pythonic heretic!” When declaring a type, such as classes and objects, both JavaScript and Python use capitalized words. For variables, attributes, and functions the convention is different.
03:25 Amusingly enough, Python uses snake case. That’s small words separated by underscores. Whereas JavaScript uses lower camel case. That’s small first letter and then capitalizing subsequent words.
03:38 Again, all of this is just convention. Your best bet is to stick with the style of the codebase you’re operating inside of. I’m not sure if I commented on this earlier—see what I did there?—but the comment characters in JavaScript are different than Python.
03:54
JavaScript embraces its C heritage and uses double forward slashes (//
) for inline comments, and it also supports multiline comments using the star-slash, star-slash (/* */
) pairing.
04:07
You’ve seen me using the different types of strings in previous lessons. JavaScript supports both single ('
) and double quotes ("
) for strings.
04:14
Neither of these types support multiline strings though. The relatively new backtick (`
) string is like an f-string in Python. It works as a template using the dollar sign curly braces notation (${}
) for variable interpolation.
04:28 The backtick string also has the added benefit of supporting multilines so you may use one just to get a multiline string even without an embedded variable.
04:38 I haven’t just been messy with semicolons. I’ve been messy with my variable declarations as well. JavaScript treats variable scope the opposite to Python.
04:47
Unless otherwise contained, everything is global. You can use the var
keyword to limit the scope to the calling context, but there are some odd behaviors with this one. So ES6 introduced let
and const
, which are the better choices. Let’s take a look at these.
05:05
In the top area here, I have the fruit.js
file. Line 2 declares a global variable called apple
. Line 3 uses the var
keyword.
05:15
The var
keyword limits scope to the current context. In the case of line 3, the context is global, so you’re still global. Let me show you this in Node, loading the file.
05:30
I’m still doing movie magic on the results of the .load
. Although I’ve shortened the output of the contents of the file, I’ve kept the return result. Notice that instead of it being undefined
, it is "Granny Smith"
.
05:42
That is because of the global variable in the file. Speaking of, let’s look at the value. And banana
. In the top area, line 6 declares strawberry
. There’s no var
keyword, so the declaration is global. But the function hasn’t run yet.
05:59
If I try to get strawberry
, it doesn’t exist.
06:04
Now let me run the tasty()
function. Looking at strawberry
again, now it is there in the global context. raspberry
, on the other hand, is not.
06:17
The var
keyword bound raspberry
to the context of the tasty()
function. var
has other consequences as well, which I’ll delve into later when I talk about language quirks. Because of this messiness, ES6 introduced some new keywords.
06:32
The first is let
. On lines 8 and 9, I use let
to declare a variable. I can assign it during the declaration or skip the assignment part.
06:42
If you only declare and don’t assign, the value of it will be undefined
. On line 13, I assign the grape
variable. This can be a bit of a foot gun.
06:52
If you think you’ve declared it but you haven’t, you’ve just leaked it into the global namespace. Just like var
, let
bounds to the local scope.
07:01
Although the tasty()
function has run, melon
does not exist in the global namespace.
07:08
The other keyword introduced in ES6 was const
. This declares a constant.
07:16 Constants don’t allow you to change what they point to.
07:22
Any attempt to reassign PI
results in an error. Do note, this doesn’t make the contents of the object being point to unchangeable. If your constant points to an object, you can still change the object.
07:34 You just can’t point the constant to a different object.
07:40 If you’ve been following the fuss in the Python community about PEP 634 and the introduction of pattern matching, you may be interested to know where that concept came from.
07:49
Many other programming languages support a switch
statement. These kinds of statements can be considered short forms for giant if, then, else blocks. Here, the variable named expression
is checked against each case statement.
08:03
If it matches one of them, then the case statement gets run. If none of them match, then the default gets run. Be careful with these. The break
keyword inside each statement is important. Without it, you will drop through to the next case.
08:17
This can result in multiple cases being evaluated, especially the default. The double star operator (**
) here for exponent math was only introduced in 2016 as part of ES7.
08:29
Depending on where you are JavaScripting, this operation may not be supported. You may have to use the math
module instead.
08:37 Time for a quick break. Go get a coffee or something. Next up, even more JavaScript syntax.
Become a Member to join the conversation.