Introduction

Every programming language has got some sort of basics attached to it that develop a good foundation on the language, and JavaScript isn't any behind.

In this chapter we shall look into some of the basics of JavaScript, including things like input and output, variables, comments, statements and expressions. Let's go!

Statements

JavaScript is an interpreted language. This means that it's parsed by an interpreter. An interpreter executes a program statement-by-statement.

Execution begins with the first statement, then to the second one, then to the third one and so on.

Wait a sec... We didn't yet specify what exactly is a statement. Let's get done with that first.

A statement in JavaScript is a unitary piece of code that is executed by the interpreter one after another.

For instance, document.write() is a statement.

Usually, statements appear on a new line.

For instance, in the code below, we have two statements:

document.write('Hello')
console.log('World!')

The first statement is document.write('Hello') while the second one is console.log('World!').

This, however, does not mean that each statement in a JavaScript program has to always appear on a new line. Multiple statements can span the same line given that they are separated by a comma (,).

Consider the code below:

document.write('Hello');console.log('World!')

This is effectively identical to the code above. The only difference is that both the statements here appear on the same line with a , in between them.

One thing worth discussing here as you're in the early stages of learning JavaScript is that of code readability.

We'll start with a simple question...

Which code snippet above is more readable? The first one or the second one?

Well clearly the second one.

It is easier for us to grasp multiple statements if each of them is given on a separate line. This makes the overall code a lot more readable than if the statements all appear on the same line.

As you begin to write JavaScript code more and more, you're recommended to follow code readability guidelines. One of them is to put separate statements on separate lines.

We'll see more details to code readability guidelines later in this chapter.

Now JavaScript has many types of statements. Some deal with controlling the flow of execution, some deal with error handling, some deal with identifier declarations, some with grouping statements and so on.

The following chart summarises some of the most common types of statements in JavaScript.

We'll cover each and every single statement mentioned in this chart in this course. Everything would be covered in precise detail.

The document.write() and console.log() methods that we came across in the previous chapters, are expression statements.

This is because they are expressions i.e. they evaluate down to a particular value.

In this case, both expressions evaluate down to the value undefined, which is not really an interesting return value. But many other expressions in JavaScript yield interesting outcomes.

Consider the following arithmetic operations we performed in the last chapter.

5+5
10
60-50
10
10*20
200
50/2
25

Each of these is an expression and would, as a whole, be called an expression statement. The first one returns 10; so does the second one; the third one returns 200 and the last one 25.

As soon as we type one of these expression in the console and then press Enter, we get the returned value displayed back in the console.

Expression statements, which are simply expressions, play a crucial role in programming. In the following section, we discuss expressions in more detail.

Expressions

The idea of an expression is fundamental to JavaScript just like the idea of a statement. Both of these are amongst the building blocks of the language.

So what exactly are expressions?

An expression is a piece of code that gets resolved down to a value.

It is said to evaluate to a particular value.

Let's see some expressions in JavaScript.

Consider the following snippet:

5+5
10

Here, 5+5 is an expression. It resolves down to the value 10. This value is displayed back in the console.

On their own, all expressions are statements, but not all statements are expressions.

For instance, document.write(), which is an expression is also a statement, as we saw earlier. So is the expression console.log() — it's a statement as well. Even 5+5, which is an arithmetic expression, is a statement.

Contrary to this, the fi statement is NOT an expression. It can't be used anywhere where an expression is required. We'll explore details to if in the chapter JavaScript if..else Statements.

Anyways, as with statements, there are various kinds of expressions.

Below shown is a list of the kinds of expressions in JavaScript:

IMage Image

Let's consider some of the most common kinds from this list.

Primary expressions

Primary expressions are the simplest, atomic, expressions in JavaScript. They don't contain any other expression within them.

As a quick example, consider the value 5. It is a primary expression, since it contains no other expression — it's a standalone value.

Similarly, consider the value 'Hello World!', which we saw back in the JavaScript Get Started chapter. It's also a primary expression. It's called a string. Recall that a string is a sequence of textual characters denoted using single quotes ('').

We'll learn more on strings in the JavaScript Strings unit.

Shown below are some of the most common kinds of primary expressions in JavaScript:

5;
'Hello';
true;
undefined;
null;
this;
/abc/ig;

The first one is a number, the second one is a string, and the third one is the special value undefined — these you know already from the previous chapters.

Starting from the fourth expression, everything is new.

  1. null is another special value in JavaScript, akin to undefined. It is mostly used where object values are required.
  2. this is yet another special value — it refers to the current execution context. One of the most challenging things for newbie JavaScript developers to understand is this, however it's not that difficult. We'll explore it in more detail when we learn how to work with objects in the JavaScript Objects unit.
  3. /abc/ represents one of the most interesting and geeky parts of programming — regular expressions. The value /abc/ is called a regular expression. It serves to match patterns within strings and then perform desired searching, replacements and so on.

Using primary expressions and operators in JavaScript, we could create further complex

Arithmetic expressions

Arithmetic expressions deal with different types of arithmetic operations. These include addition, subtraction, multiplication, division, modulus and exponentiation.

Let's see each one.

The first four operators represent elementary operations and so we demonstrate them all together in the snippet below:

150 + 30
180
30 - 1
29
10 * 20.5
205
185 / 2
92.5

What might be new for you would be the modulus (%) and exponentiation (**) operators.

The modulus operator simply returns the remainder of a given division. For instance 10 % 3 returns 1, since 10 divided by 3 leaves off 1 as the remainder.

10 % 3
1
7 % 8
7
150 % 30
0

The exponentiation operator returns the result of exponentiating a given base number with a given exponent (also known as the power). For instance, 2 ** 5, which means 25, returns 32. The number 2 is raised to the power of 5.

10 ** 3
1000
7 ** 8
5764801
1 ** 0
1

Both the modulus and exponentiation operators in JavaScript are commonly used in mathematical calculations.

Relational expressions

As the name suggests, relational expressions check for relationships between given values. If the relationships are found, they return true or else false.

Simple!

Some of the most common relational expressions are discussed below.

The equality (==) operator takes two valuees and returns true is they are equal to one another, or else false.

A couple of inequality operators also exist in JavaScript.

For instance, the non-equality (!=) operator returns true if the given values are NOT equal to one another, or else false.

10 != 10
false
10 != 5
true
6 != 0
true

In the first statement, since both the given values are equal to one another, the operation evaluates down to false. However, in each of the next two statements, they aren't equal and likewise the operation returns true.

Similarly, we have the less than (<) and greater than (>) operators to determine which of two given values is smaller and which one is larger.

10 < 10
false
10 < 5
false
5 < 10
true
10 > 10
false
10 > 5
true
5 > 10
false
We'll learn more details to ==, !=, <, > in the JavaScript Operations chapter. There we'll also see the two <= and >= which stand for 'greater than or equal to' and 'less than or equal to' respectively.

Invocation expressions

Any expression that involves calling a function or method is referred to as an invocation expression.

'Invocation' is simply a more programmatic term for 'calling'.

document.write() and console.log() are both invocation expressions.

The former invokes the write() method on the document object while the latter invokes the log() method on the console object.

As you start writing complex JavaScript programs, you'll find yourself using invocation expressions very frequently.

This is because many important utilities in the language are given behind functions and methods. In addtion to this, we could even create our own functions and methods and then use them at will to carry out certain tasks. This makes it apparent as to why are invocation expressions so common out there.

We'll learn more on how to create functions in JavaScript in the JavaScript Functions unit.

Variables

Variables play a crucial role in programming in general, not just JavaScript.

In plain words:

A variable is a container for storing data.

A variable has a name and serves to store a given piece of data in memory.

Recall variables from school algebra classes? Well, variables in programming work pretty much the same way.

Let's see how to create a variable in JavaScript:

var x = 10;

This single line of code creates a variable x in memory and stores the number 10 in it.

The first part i.e. var x, is referred to as variable declaration. It declares a new identifier into the execution environment. This identifier has the name x. The declaration allocates memory for the respective variable.

The second part, i.e. x = 10, stores the value 10 in the variable x. It is commonly referred to as variable assignment. The name comes from the fact that we assign a value to the variable — in this case assign 10 to x.

Now beyond this statement, our program has a variable x available with the value 10 inside it. We could use this variable just like we'd use 10 anywhere in our script.

Consider the code below:

var x = 10;
console.log(x + 10);

First we declare and assign a value to a variable x and then log the expression x + 10.

x + 10 is literally the same as saying 10 + 10. Hence, it gets resolved down to 20 which is what gets logged in the console.

20

Whenever a given value is stored inside a variable, you could use that variable in every single way you could use that value.

For instance, consider the following console snippet where we create the same variable x above and then perform a handful of arithmetic operations on it.

var x = 10
undefined
x + 10
10
x - 2
8
x * 20
200
x / 2
5
x % 7
3
x ** 2
100

In the first statement when we write var x = 10, we get undefined displayed in the console. It's important to realise that var x = 10 is not an expression — it's a statement.

The console is just configured to display undefined whenever it executes a statement that is not an expression statement. In the case of an expression statement, such as x + 10, x - 2 and so on, the console displays whatever that expressions resolves down to.

The expression statement could resolve down to undefined, but the main point to note is that the console isn't hardcoded to display undefined for an expression statement, as it is for other statements.

Strings

A string is a sequence of textual characters.

Each character in a string is at a given position. Formally, this is called the index of the character.

The index of a character in a string is the position it sits at.

The first character is at index 0, the second is at index 1, the third is at index 2, and so on and so forth.

The total number of characters in a string is referred to as its length.

The length of a string is the total number of characters in it.

The length of a string is always 1 greater than the index of the last character in the string.

To create a string in JavaScript, we use a pair of single quotes ('') and put the text in between these. An example follows:

var s = 'Hello';
console.log(s);
Hello

Apart from single quotes, we could even use double quotes ("") to create strings in JavaScript.

Consider the following code:

var s = "Hello";
console.log(s);

Practically, there is not even a single difference between strings created using single quotes and strings created using double quotes.

But then what's the purpose of double quotes?

Well, double quotes are handy when we want to create a string that has single quotes in itself. If we were to create such a string using single quotes, these would come in conflict with the single quotes inside the string.

Let's see what this means:

var s = 'What's up?';
document.write(s);

Here we want to output the text "What's up?" on the document. What we do is create the string using single quotes ('') and then go on to execute the code.

Live Example

As soon as we do so, we don't see any output on the document. This hints us that something fishy has happened in the code. To inspect the problem, we open the console. It is where all programmatic errors and warnings are logged.

Opening the console, we see the following error message (in red color):

Uncaught SyntaxError: Unexpected identifier

This is called a syntax error.

Syntax errors refer to invalidly written code.

In our case, the syntax error pops up due to the usage of single quotes to denote the string.

Let's see how does the problem arise.

The first single quote instructs the JavaScript interpreter that a string value follows. The interpreter looks for the next single quote in the code and as soon as it finds one, it terminates the string right at that point.

This next single quote is the one before the character s. Hence the string understood by the interpreter is 'What'.

Beyond this point, the code is not considered text anymore — it is actual JavaScript code now. Putting an identifier or any other value next to a string is invalid, likewise the interpreter flags the s after the string as a syntax error.

This problem can be easily solved using double quotes ("").

Shown below is the same code as above, this time using double quotes ("") to denote the string:

var s = "What's up?";
document.write(s);

Live Example

As soon as we run this code, we get the expected output.

No errors occured.

This is simply because the symbol used to denote the string (that is, ") does not appear inside the string itself. Thereby the interpreter passes the correct string value.

Dialog boxes

JavaScript provides three different kinds of dialog boxes to developers to be shown to the end user.

But what is a dialog box? Hmm, good question.

A dialog box is basically an interface element created by the browser itself. It serves to ask the user to input something or notify about something.

The first one is called the alert dialog, the second one is called a confirmation dialog and the last one is called a prompt dialog.

Each of these is accessible by a given function. Time for some detailed exploration...

Alert dialog

An alert dialog is displayed by calling the alert() function.

Did we cover the idea of a function in the previous chapters?

Well, we didn't. Let's first understand what exactly is meant by a function and then get back to alert().

What is a function?

Do you recall methods from the previous chapters? The idea of a method is a subset of the idea of a function.

A function is simply a block of code that gets executed when the function is called — or better to say, when the function is invoked.

alert() is an example of a function in JavaScript.

It is a predefined function provided to us by the browser, and has some code (which we can't see in the browser) to display an alert dialog box. This code is only executed when the function is called.

To call a function, we write a pair of parentheses (()) after the function's name.

So to call alert, we have to write alert().

JavaScript has many many predefined functions. We'll cover the most commons throughout this extensive course.

Apart from these predefined ones, we can even create our own functions. This is an extremely common practice in nearly all JavaScript programs you'll encounter, because of the benefits of using a function.

As an extremely quick example, consider an e-commerce web application where you have to calculate the total bill for a user when he/she checks out. You could create a function called calculateTotalBill() in JavaScript in order to perform this task, and then call the function when you actually need to.

The world of functions is just endless!

We'll cover functions in extremely precise detail in the JavaScript Functions unit.

A method such as document.write() or console.log() is a special kind of a function.

Precisely, it's a property of an object whose value is a function. We'll discover more details to methods in the JavaScript Objects unit.

Throughout this course, whenever specifying a function or method, we'll put () at the end of the respective entity. This would help in differentiating functions/methods from other values.

Alright, let's back to alert().

The alert() method when called displays an alert dialog on the webpage:

alert();

Live Example

Until and unless this dialog is cleared in some way — by pressing the Esc key on the keyboard, or the OK button on the alert box itself, execution would be paused at the alert() function.

Nothing ahead would be executed as long as the alert dialog isn't closed. This behaviour is generally known as synchronous execution in programming.

Coming back to alert(), as you just saw above, calling it as is without anything in between the () creates an empty dialog — there is no text in it.

As you would agree, this is not very useful.

To make the dialog more useful, the alert() function accepts an optional argument which is the text to display in the dialog.

Consider the following:

alert('Hello World!')

Live Example

As soon as you execute this code, an alert dialog is displayed with the text 'Hello World!' in it.

Syntax for a function

As we'll cover more and more functions and methods in this course, we'll need a formal way to see their details. These include what arguments the function takes, what value should each argument be of, which ones are required, which ones are optional, and so on.

This formal way would be to give a snippet detailing the arguments and owner object of the function/method. This is called the syntax of the function/method.

Here's the syntax for the alert() function:

alert(msg)

msg is a string to display in the alert box.

Notice how the word msg is given in italics. This convention is used to refer to a parameter of the function.

A parameter is the name with which we refer to a value passed to a function, while an argument is the actual value.

To be very specific, the msg parameter of the alert() function is optional. It would've been great if we could indicate this idea when showing the syntax of the function.

Guess what — there is a way!

By convention, when specifying the syntax for a function/method, enclosing the parameter in square brackets implies that it is optional.

By this means, we could rewrite the syntax for alert() as follows:

alert([msg])

Keep in mind that [ and ] don't have to be included in the actual invocation for the function. They are just given to indicate that a given parameter is optional.

That's it!

Alright, so now that we've covered almost every thing involved in alert(), let's call it with an argument and see the result.

Moving on, sometimes it's desired to write multiple lines of text in an alert dialog (or the two other kinds of dialogs we'll see next).

To do so, we write \n next to the character after which we want a new line.

\n is a special character in text values. It represents a newline.
A newline in a piece of text is also a character. You may have never thought of it this way, since newlines are not visible in any character form, and so aren't considered to be part of the text. But the truth is that, like every other character, a newline is a textual character as well.

Consider the code below:

alert('Hello\nWorld!')

Live Example

The text 'Hello' gets displayed on the first line, and the text 'World!' gets displayed on the second one. The \n character puts a newline after the 'o' character in the string.

All good uptil now?

With alert() all covered, let's move over to consider the second dialog box in JavaScript — confirm().

Confirmation dialog

A confirmation dialog is given by the confirm() function.

Here's its syntax:

confirm([msg])

As before, msg is a string to display in the dialog box.

Consider the code below:

confirm('This is a confirmation box')

Live Example

Shown below is how a confirmation dialog looks:

A confirmation dialog on Google Chrome for Windows.

As the name implies, a confirmation dialog is meant to ask for the user's confirmation on some given action.

It returns true if the user presses OK, or else false.

This return value is of particular importance when working with confirm(), since it specifies whether the user confirmed the given action or not.

A common application for confirm(), which even you might have come across, is to ask for the user's confirmation when he/she closes the corresponding webpage. This confirmation makes sure that the user is aware of the fact that he/she might lose any unsaved work, or anything in progress on the webpage.

Prompt dialog

The prompt dialog is given by the function prompt().

It is a means to get input from the user.

Syntactically, prompt() is a bit similar to alert() and confirm():

prompt([msg[, defaultValue]])

msg is a string to display in the dialog box while defaultValue is a string to put in the input field by default. Both these parameters are optional.

Consider the following code:

prompt('What is your age?')

Live Example

Here we ask the user to enter his/her age.

As soon as we execute this code, we get the following prompt dialog shown:

A prompt dialog box on Google Chrome for Windows.

The input field in the dialog box is where the user enters a value. The blinking cursor indicates that some value is expected to be input.

We'll enter 20 in here, and then press the OK button.

A prompt dialog box on Google Chrome for Windows.

By pressing the OK button on the dialog box, or the Enter key on the keyboard, the dialog disappears and the prompt() call completes and resolves down with the value input by the user — in this case, with '20'.

However, if the prompt dialog is canceled, by pressing the Cancel button on the dialog or the Esc key on the keyboard , the prompt() call returns null (after disappearing from the interface).

We could save the value returned by prompt() in a variable and then process it further.

In the following code, we output the entered age back to the user with a nice sentence:

var age = prompt('What is your age?');
document.write('You are ' + age + ' years old.');

Live Example

First, we create a variable age and then call prompt(). This invocation gets resolved down with whatever value is input by the user in the prompt dialog box.

Let's say the value input is 20. The call to prompt() would, hence, get replaced by the string '20'.

Next, we call document.write() to display some text out on the webpage. This text is composed by joining together three string values.

As a whole, the text 'You are 20 years old.' would be output.

Note that the return value of prompt() is always going to be a string. Hence, inputting 20 won't resolve the prompt() call with the number 20 — rather it would resolve it with the string '20'.

Always!

We could however get such string values, that solely hold numbers, to be converted into an actual number. The next section discusses how to do so.

Conversion to number

Often times while working in applications, you'll feel the need to convert strings into numbers. Classic uses of this arise when the strings are obtained by means of input from the user.

We saw an example of this above. The user was asked to enter his/her age in a prompt dialog. The age, as we know, is a number and might be required to be further passed through some arithmetic operation at our end.

For instance, we might want to tell the user their age after 20 years. This requires 20 to be added to the input number.

Such problems of getting a number from a string are extremely common in practical level applications. The question is how to do so.

We can use the Number() function in JavaScript to get the numeric equivalent of a string.

Below is the syntax of Number():

Number(string)

string is a string from which to obtain a number.

Let's try this function on a couple of strings:

Number('10')
10
Number('20')
20
Number('20a')
nan
Number('Hello')
nan

In the first two statements, we get the respective number inside the string returned.

In the last two statements, we get nan displayed in the console. This is a special kind of a number in JavaScript. It stands for Not-a-Number.

We'll see more details to nan in the JavaScript Numbers Basics chapter.

Code readability

Programs are parsed and executed by machines as we all know, however written and read by humans. Computers can read complex code and messy code however we can't.

We need clean and neatly layed out code which can suffice us in reading it and understanding it easily. No one is able to understand badly cluttered code, even not the developer himself. This is just what code readability guidelines talk about.

Starting at this very stage you should try your level best to write code that is easily readable and understandable by other developers. Part of this involves spacing and indenting out your code.

For instance, consider the code below which is not readable at all:

var x=10;if(x===10){alert("All set")}

Unlike the interpreter and the machine, you'll definitely have a hard time understanding this code. However by just adding spacing and new lines within this same code we can make it way more readable as shown below:

var x = 10;
if (x === 10) {
alert("All set");
}

In conclusion

With the basics of the basics dealt with, we are getting ourselves in good form to learn new and complicated stuff and discover new avenues in JavaScript.

In the coming chapters we will get into a bit more detail of some concepts shown here and from there to even more details. Programming is all about learning and getting it done!