JavaScript Fundamentals



 Let’s learn the fundamentals of script building.

Hello, world!

This part of the tutorial is about core JavaScript, the language itself. Later on, you’ll learn about
Node.js and other platforms that use it.

But we need a working environment to run our scripts and, since this book is online, the
browser is a good choice. We’ll keep the amount of browser-specific commands (like
alert )
to a minimum so that you don’t spend time on them if you plan to concentrate on another
environment (like Node.js). We’ll focus on JavaScript in the browser in the
next part of the
tutorial.

So first, let’s see how we attach a script to a webpage. For server-side environments (like
Node.js), you can execute the script with a command like
"node my.js" .

The “script” tag

JavaScript programs can be inserted into any part of an HTML document with the help of the
<script> tag.
For instance:

<!DOCTYPE HTML>
<html>
<
body>
<
p>Before the script...</p>
<
script>
alert( 'Hello, world!' );
</
script>
<
p>...After the script.</p>
</
body>
</
html>

The <script> tag contains JavaScript code which is automatically executed when the
browser processes the tag.

Modern markup

The <script> tag has a few attributes that are rarely used nowadays but can still be found in
old code:
The type attribute: <script type=…>
The old HTML standard, HTML4, required a script to have a type . Usually it was
type="text/javascript" . It’s not required anymore. Also, the modern HTML standard,
HTML5, totally changed the meaning of this attribute. Now, it can be used for JavaScript
modules. But that’s an advanced topic; we’ll talk about modules in another part of the tutorial.
The language attribute: <script language=…>
This attribute was meant to show the language of the script. This attribute no longer makes
sense because JavaScript is the default language. There is no need to use it.
Comments before and after scripts.
In really ancient books and guides, you may find comments inside <script> tags, like this:

<script type="text/javascript"><!--
...
//-->
</script>

This trick isn’t used in modern JavaScript. These comments hid JavaScript code from old
browsers that didn’t know how to process the
<script> tag. Since browsers released in the
last 15 years don’t have this issue, this kind of comment can help you identify really old code.


External scripts

If we have a lot of JavaScript code, we can put it into a separate file.
Script files are attached to HTML with the
src attribute:

<script src="/path/to/script.js"></script>

Here, /path/to/script.js is an absolute path to the script file (from the site root).
You can also provide a relative path from the current page. For instance,
src="script.js"
would mean a file "script.js" in the current folder.
We can give a full URL as well. For instance:

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.2.0/lodash.js"></script>

To attach several scripts, use multiple tags:

<script src="/js/script1.js"></script>
<
script src="/js/script2.js"></script>

Summary

  • We can use a <script> tag to add JavaScript code to a page.
  • The type and language attributes are not required.
  • A script in an external file can be inserted with <script src="path/to/script.js"></script> .

There is much more to learn about browser scripts and their interaction with the webpage. But
let’s keep in mind that this part of the tutorial is devoted to the JavaScript language, so we
shouldn’t distract ourselves with browser-specific implementations of it. We’ll be using the
browser as a way to run JavaScript, which is very convenient for online reading, but only one of
many

Code structure

The first thing we’ll study is the building blocks of code.

Statements

Statements are syntax constructs and commands that perform actions.
We’ve already seen a statement,
alert('Hello, world!') , which shows the message
“Hello, world!”.
We can have as many statements in our code as we want. Statements can be separated with a
semicolon.
For example, here we split “Hello World” into two alerts:

alert('Hello'); alert('World');

Usually, statements are written on separate lines to make the code more readable:

alert('Hello');
alert('World');

Semicolons

A semicolon may be omitted in most cases when a line break exists.
This would also work:

alert('Hello')
alert('World')

Here, JavaScript interprets the line break as an “implicit” semicolon. This is called an automatic semicolon insertion.
In most cases, a newline implies a semicolon. But “in most cases” does not mean “always”!
There are cases when a newline does not mean a semicolon. For example:

alert(3 +
1 +
2);

The code outputs 6 because JavaScript does not insert semicolons here. It is intuitively
obvious that if the line ends with a plus
"+" , then it is an “incomplete expression”, so the
semicolon is not required. And in this case that works as intended.
But there are situations where JavaScript “fails” to assume a semicolon where it is really
needed.
Errors which occur in such cases are quite hard to find and fix.

We recommend putting semicolons between statements even if they are separated by
newlines. This rule is widely adopted by the community. Let’s note once again –
it is possible to
leave out semicolons most of the time. But it’s safer – especially for a beginner – to use them.

Comments

As time goes on, programs become more and more complex. It becomes necessary to add
comments which describe what the code does and why.
Comments can be put into any place of a script. They don’t affect its execution because the
engine simply ignores them.

One-line comments start with two forward slash characters // .
The rest of the line is a comment. It may occupy a full line of its own or follow a statement.
Like here:

// This comment occupies a line of its own
alert('Hello');
alert('World'); // This comment follows the statement

Multiline comments start with a forward slash and an asterisk /* and end with an
asterisk and a forward slash
*/
.
Like this:

/* An example with two messages.
This is a multiline comment.
*/

alert('Hello');
alert('World');

The content of comments is ignored, so if we put code inside /* … */ , it won’t execute.
Sometimes it can be handy to temporarily disable a part of code:

/* Commenting out the code
alert('Hello');
*/

alert('World');

Please, don’t hesitate to comment your code.
Comments increase the overall code footprint, but that’s not a problem at all. There are many
tools which minify code before publishing to a production server. They remove comments, so
they don’t appear in the working scripts. Therefore, comments do not have negative effects on
production at all.
Later in the tutorial there will be a chapter
Code quality that also explains how to write better
comments

The modern mode, "use strict"

For a long time, JavaScript evolved without compatibility issues. New features were added to
the language while old functionality didn’t change.
That had the benefit of never breaking existing code. But the downside was that any mistake or
an imperfect decision made by JavaScript’s creators got stuck in the language forever.
This was the case until 2009 when ECMAScript 5 (ES5) appeared. It added new features to the
language and modified some of the existing ones. To keep the old code working, most
modifications are off by default. You need to explicitly enable them with a special directive:
"use strict" .

“use strict”

The directive looks like a string: "use strict" or 'use strict' . When it is located at
the top of a script, the whole script works the “modern” way.
For example:

"use strict";
// this code works the modern way
...

We will learn functions (a way to group commands) soon.
Looking ahead, let’s just note that
"use strict" can be put at the start of most kinds of
functions instead of the whole script. Doing that enables strict mode in that function only. But
usually, people use it for the whole script.

Browser console

For the future, when you use a browser console to test features, please note that it doesn’t use
strict
by default.
Sometimes, when
use strict makes a difference, you’ll get incorrect results.
You can try to press
Shift+Enter to input multiple lines, and put use strict on top, like
this:

'use strict'; <Shift+Enter for a newline>
// ...your code
<Enter to run>

It works in most browsers, namely Firefox and Chrome.
If it doesn’t, the most reliable way to ensure
use strict would be to input the code into
console like this:

(function() {
'use strict';
// ...your code...
})()

Always “use strict”

We have yet to cover the differences between strict mode and the “default” mode.
In the next chapters, as we learn language features, we’ll note the differences between the strict
and default modes. Luckily, there aren’t many and they actually make our lives better.
For now, it’s enough to know about it in general:
1. The
"use strict" directive switches the engine to the “modern” mode, changing the
behavior of some built-in features. We’ll see the details later in the tutorial.
2. Strict mode is enabled by placing
"use strict" at the top of a script or function. Several
language features, like “classes” and “modules”, enable strict mode automatically.
3. Strict mode is supported by all modern browsers.
4. We recommended always starting scripts with
"use strict" . All examples in this tutorial
assume strict mode unless (very rarely) specified otherwise.

Post a Comment

You're welcome to share your ideas with us in comments.

Previous Post Next Post