What is Javascript?

JavaScript was initially created to make web pages alive. The programs in this language are called scripts. They can be written right in a web page’s HTML and executed automatically as the page loads. Scripts are provided and executed as plain text. They don’t need special preparation or compilation to run. In this aspect, JavaScript is very different from another language called Java. Today, JavaScript can execute not only in the browser, but also on the server, or actually on any device that has a special program called the JavaScript engine.

The browser has an embedded engine sometimes called a “JavaScript virtual machine”. Different engines have different “codenames”. For example:

  • V8 – in Chrome and Opera.
  • SpiderMonkey – in Firefox.
  • …There are other codenames like “Trident” and “Chakra” for different versions of IE, “ChakraCore” for Microsoft Edge, “Nitro” and “SquirrelFish” for Safari, etc.

Hello, world!

The tutorial that you’re reading is about core JavaScript, which is platform-independent. 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.

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

  1. <!DOCTYPE HTML>
  2. <html>
  3. <p>Before the script...</p>
  4. <script>
  5. alert( 'Hello, world!' );
  6. </script>
  7. <p>After the script...</p>

As a rule, only the simplest scripts are put into HTML. More complex ones reside in separate files. Other pages that reference the same script will take it from the cache instead of downloading it, so the file is actually downloaded only once. That reduces traffic and makes pages faster.
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"gt;</script>.

The modern mode

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".

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.

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

Variables

Most of the time, a JavaScript application needs to work with information. Here are two examples:

  1. An online shop – the information might include goods being sold and a shopping cart.
  2. A chat application – the information might include users, messages, and much more.

Variables are used to store this information.

Declaration of Variables

A variable is a “named storage” for data. We can use variables to store goodies, visitors, and other data.

To create a variable in JavaScript, use the let keyword.

The statement below creates (in other words: declares or defines) a variable with the name “message”:

  1. let message

Now, we can put some data into it by using the assignment operator =:

  1. let message
  2. message = 'Hello'; // store the string

The string is now saved into the memory area associated with the variable. We can access it using the variable name:

  1. let message
  2. message = 'Hello';
  3. alert(message); // shows the variable content

To be concise, we can combine the variable declaration and assignment into a single line:

  1. let message = 'Hello!'; // define the variable and assign the value
  2. alert(message); // Hello!

Variable naming

There are two limitations on variable names in JavaScript:

  1. The name must contain only letters, digits, or the symbols $ and _.
  2. The first character must not be a digit.

Examples of valid names:

  1. let userName;
  2. let test123;

When the name contains multiple words, camelCase is commonly used. That is: words go one after another, each word starting with a capital letter: myVeryLongName.

What’s interesting – the dollar sign '$' and the underscore '_' can also be used in names. They are regular symbols, just like letters, without any special meaning.

Constants

To declare a constant (unchanging) variable, use const instead of let:

  1. const myBirthday = '18.04.1982';

Variables declared using const are called “constants”. They cannot be changed. An attempt to do so would cause an error:

  1. const myBirthday = '18.04.1982';
  2. myBirthday = '01.01.2001'; // error, can't reassign the constant!

When a programmer is sure that a variable will never change, they can declare it with const to guarantee and clearly communicate that fact to everyone.

There is a widespread practice to use constants as aliases for difficult-to-remember values that are known prior to execution.

Such constants are named using capital letters and underscores.

Like this:

  1. const COLOR_RED = "#F00";
  2. const COLOR_GREEN = "#0F0";
  3. const COLOR_BLUE = "#00F";
  4. const COLOR_ORANGE = "#FF7F00";
  5. // ...when we need to pick a color
  6. et color = COLOR_ORANGE;
  7. alert(color); // #FF7F00

Benefits:

  • COLOR_ORANGE is much easier to remember than "#FF7F00".
  • It is much easier to mistype "#FF7F00" than COLOR_ORANGE.
  • When reading the code, COLOR_ORANGE is much more meaningful than #FF7F00.

When should we use capitals for a constant and when should we name it normally? Let’s make that clear.

Being a “constant” just means that a variable’s value never changes. But there are constants that are known prior to execution (like a hexadecimal value for red) and there are constants that are calculated in run-time, during the execution, but do not change after their initial assignment.

For instance:

  1. const pageLoadTime = /* time taken by a webpage to load */;

The value of pageLoadTime is not known prior to the page load, so it’s named normally. But it’s still a constant because it doesn’t change after assignment.

In other words, capital-named constants are only used as aliases for “hard-coded” values.

Data Types

A variable in JavaScript can contain any data. A variable can at one moment be a string and at another be a number:

  1. // no error
  2. let message = "hello";
  3. message = 123456;

Programming languages that allow such things are called “dynamically typed”, meaning that there are data types, but variables are not bound to any of them.

There are seven basic data types in JavaScript. Here, we’ll cover them in general and in the next chapters we’ll talk about each of them in detail.

The number type represents both integer and floating point numbers.

  1. let n = 123;
  2. n = 12.345;

There are many operations for numbers, e.g. multiplication *, division /, addition +, subtraction -, and so on.

Besides regular numbers, there are so-called “special numeric values” which also belong to this data type: Infinity, -Infinity and NaN.

A string in JavaScript must be surrounded by quotes.

  1. let str = "Hello";
  2. let str2 = 'Single quotes are ok too';
  3. let phrase = `can embed ${str}`;

In JavaScript, there are 3 types of quotes.

  1. Double quotes: "Hello".
  2. Single quotes: 'Hello'.
  3. Backticks: `Hello`.

The boolean type has only two values: true and false. This type is commonly used to store yes/no values: true means “yes, correct”, and false means “no, incorrect”.

The object type is special.

All other types are called “primitive” because their values can contain only a single thing (be it a string or a number or whatever). In contrast, objects are used to store collections of data and more complex entities. We’ll deal with them later in the chapter Objects after we learn more about primitives.

The symbol type is used to create unique identifiers for objects. We have to mention it here for completeness, but it’s better to study this type after objects.

Conditional operators

Sometimes, we need to perform different actions based on different conditions.

To do that, we use the if statement and the conditional (ternary) operator which we will be referring to as the “question mark” operator ? for simplicity.

The if statement evaluates a condition and, if the condition’s result is true, executes a block of code.

  1. let year = prompt('In which year was ECMAScript-2015 specification published?', '');
  2. if (year == 2015) alert( 'You are right!' );

If we want to execute more than one statement, we have to wrap our code block inside curly braces:

  1. if (year == 2015) {
  2. alert( "That's correct!" );
  3. alert( "You're so smart!" );
  4. }

We recommend wrapping your code block with curly braces {} every time you use an if statement, even if there is only one statement to execute. Doing so improves readability.

The if statement may contain an optional “else” block. It executes when the condition is false.

For example:

  1. let year = prompt('In which year was the ECMAScript-2015 specification published?', '');
  2. if (year == 2015) {
  3. alert( 'You guessed it right!' );
  4. } else {
  5. alert( 'How can you be so wrong?' ); // any value except 2015
  6. }

The operator is represented by a question mark ?. The formal term “ternary” means that the operator has three operands. It is actually the one and only operator in JavaScript which has that many.

Syntax is:

  1. let result = condition ? value1 : value2;

while and for

We often need to repeat actions.

For example, outputting goods from a list one after another or just running the same code for each number from 1 to 10.

Loops are a way to repeat the same code multiple times.

The while loop has the following syntax:

  1. while (condition) {
  2. // code
  3. // so-called "loop body"
  4. }

While the condition is true, the code from the loop body is executed.

For instance, the loop below outputs i while i < 3:

  1. let i = 0;
  2. while (i < 3) { // shows 0, then 1, then 2
  3. alert( i );
  4. i++;
  5. }

The for loop is the most commonly used loop.

It looks like this:

  1. for (begin; condition; step) {
  2. // ... loop body ...
  3. }

Functions

A function definition (also called a function declaration, or function statement) consists of the function keyword, followed by:

For example, we need to show a nice-looking message when a visitor logs in, logs out and maybe somewhere else.

We’ve already seen examples of built-in functions, like alert(message), prompt(message, default) and confirm(question). But we can create functions of our own as well.

To create a function we can use a function declaration.

It looks like this:

  1. function showMessage() {
  2. alert( 'Hello everyone!' );
  3. }

The function keyword goes first, then goes the name of the function, then a list of parameters between the parentheses (empty in the example above) and finally the code of the function, also named “the function body”, between curly braces.

Reference