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!

Strings

It won't be wrong to say, even though graphical processing has seriously taken the rise these days, text remains one of the cornerstones of modern-day computing.

The idea of a string in programming languages is just a way to denote literal text.

Defining it formally:

A string is a sequence of characters that represents text.

There are essentially three ways to denote a string in JavaScript:

  1. Using a pair of single quotes ('')
  2. Using a pair of double quotes ("")
  3. Using a pair of backticks (``)

Of these three ways, we'll only be concerned with the first two for this entire unit. The last method i.e. of using a pair of backticks (``) will be explored in detail in the JavaScript Strings unit.

A pair of single quotes is the simplest of all ways to represent a string.

Consider the code below where we log the string 'Hello' to the console:

console.log('Hello');
Hello

Keep in mind that the quotes used to denote a string are themselves not part of the string.

This can be confirmed by the console output shown above — only Hello is output confirming the fact that the ' character at the beginning and end of 'Hello' isn't part of the actual data stored internally.

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

Consider the following code:

console.log("Hello");
Hello

Here we log the string "Hello" which is, in practice, identical to the string 'Hello'.

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

In the code below, we want to output the text "What's up?" in the console. What we do therefore is simply create the string using a pair single quotes (''), and then put the desired text inside it:

console.log('What's up?');

Now when we run this code, we don't see any output in the console. Or better to say, we see an error mesage in the console saying that there is some kind of problem with our code.

Here's the error message (in red color):

Uncaught SyntaxError: Unexpected identifier

The error arises because of the malformed statment in our code. Such an error is called a syntax error.

A syntax error is an error that arises due 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 the problem arises.

The first single quote ('What's up?') 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 ('What's up?'). Hence the string parsed by the engine 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 ('What's up?') as a syntax error.

This problem can be easily solved by denoting the string using a pair of double quotes ("").

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

console.log("What's up?");

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

What's up?

No errors occur. This is simply because the symbol used to denote the string (that is, ") does not appear inside the string itself. Thereby the engine parses the correct string value, just as we want it to.

One thing to note about both single-quoted and double-quoted strings is that they can't span multiple lines. They must be defined on one single line. Failing to do so will lead to a syntax error.

Consider the code below:

console.log('Hello World!
JavaScript is awesome.');

Here we are trying to output 'Hello World!' on the first line and then 'JavaScript is awesome.' on the second line, and therefore write both the sentences on new lines within the string literal.

However, JavaScript considers this as invalid code and consequently logs an error as follows:

Uncaught SyntaxError: Invalid or unexpected token

But why?

This is because a string in JavaScript can NOT contain a newline as it is.

In the code above, we entered a newline right after the ! character inside the string (on the very first line). This is invalid and the cause of the syntax error.

So then how do we denote a newline if we really want it?

Well, it's really simple and quite standard across almost all programming languages — use an escape sequence.

What's an escape sequence?

Certain characters in a piece of text can't anyhow be represented as a single literal graphical character. For instance, the first letter of the English alphabet can be given in uppercase as A, or in lowercase as a. That's good!

But what if we want a newline in the text? How do we give that?

Back when computer scientists began working with text, they faced this same challenge. But the solution wasn't something to demand another decade or so. It was pretty simple...

Just take a certain character to have a special meaning. And then follow that character with another character to, as a whole, denote a special character such as a newline, a tab, and so on.

The character chosen to have a special meaning was backslash (\).

The backslash paired with a character following it is collectively referred to as an escape sequence. The character following \ depends on what character, as a whole, do we need to denote.

The name 'escape sequence' implies the fact that this simple sequence of two characters is escaped i.e. it doesn't appear literally as it is.

Hence, when a backslash appears in a string, we have a special character sequence. But on its own, the backslash has no meaning — it's ought to be paired with another character to denote something such as a newline, or a tab, or anything else.

Shown below are some of the common escape sequences used in JavaScript and, in general, all over different programming languages.

Escape sequenceNamePurpose
\nNewline (a.k.a. line feed)Denotes a new line.
\rCarriage returnTake the cursor to the beginning of the current line.
\tTabDenotes a tab.
\'Single-quote escapeDenotes the character '.
\"Double-quote escapeDenotes the character ".

Let's try using \n.

Suppose we need to make the following console output:

Hello World! JavaScript is awesome.

Just by looking at it, it's clear that the second sentence is on a new line. Hence, we need to use the \n escape sequence to denote the newline in the string.

Here's the code to output the text shown above:

console.log('Hello World!\nJavaScript is awesome.');

The \n inside the string denotes a newline. It takes the cursor to the next line and therefore whatever follows \n appears on a new line.

When we run this code, we get the desired output:

Hello World! JavaScript is awesome.

Now, let's try to apply the same idea to printing two sentences on separate lines out on the document, instead of on the console.

In the following snippet, we have the same code as before except for that instead of console.log(), we pass the string to the document.write() method:

document.write('Hello World!\nJavaScript is awesome.');

This snippet produces the output shown below:

Hello World! JavaScript is awesome.

Wait... There is a problem here.

We used the \n character but there seems to be no effect in the output made. What's going on?

The thing is that HTML parses text differently than the browser's console. You might already know of this from your old HTML lessons. That is, HTML treats a whole sequence of whitespace characters (which includes the spaces, newlines, and tabs) as one single space.

Hence, in the code above, the text that HTML ultimately parses is the following:

Hello World!
JavaScript is awesome.

The newline after the first sentence is simply reduced down to a single space and then the respective output is made.

The question is, how to denote a newline in HTML?

Well, this requires prior knowledge of HTML and CSS only — we just don't need JavaScript in here. A newline in HTML could be denoted in two ways:

  1. Use the <br> tag.
  2. Set the white-space CSS property to pre.

Let's make the same output as before using both of these ways.

First, with the <br> tag:

document.write('Hello World!<br>JavaScript is awesome.');

As you can see, we write the <br> tag as it is inside the string. When the HTML engine now parses this text, it sees the <br> tag and consequently places a newline right in place of it.

Hello World!
JavaScript is awesome.

Good.

Now, let's try the second option i.e. using the CSS property white-space.

With white-space: pre set on the <body> element of the HTML page, we don't need the <br> tag to denote a newline — it could be given simply by a literal newline character.

For JavaScript, this means that we could denote a newline in the HTML using the same \n escape sequence we use to denote a newline in the console.

Consider the following HTML code along with the <script> tag where we put our JavaScript code. The reason of showing the HTML is so that we can clearly see the CSS:

<!DOCTYPE html>
<html>
<head>
   <style>
      body {white-space: pre}
   </style>
   <script>
      document.write('Hello World!\nJavaScript is awesome.');
   </script>
</head>
<body>
</body>
</html>

When we load this webpage, we get the following output:

Hello World!
JavaScript is awesome.

Just as we wanted.

In the code above, we could've put the <style> and <script> tags inside <body>, instead of putting them in <head>. However, this would lead to an issue.

That is, if the tags are placed just as they are written above, then the space between the tags would be output to the document as well, due to the white-space: pre style. Likewise, the given text would appear after two lines and be a little bit indented to the right.

Putting the <style> and <script> tags inside <head> solves this spacing issue as document.write() adds stuff right inside the <body> element which in this case is completely empty beforehand.

Numbers

Working with numbers is yet another crucial part of computing. In fact, every single thing that happens inside the wires and chips of a computer is a mere computation over numbers.

In JavaScript, working with numbers is superbly easy.

An integer, which is a number without a fractional part, is denoted as we'd do it in normal writing. That is, we write the number as it is.

Some examples of integers are -1000, -1, 0, 10, 50, 12345 and so on.

In the code below, we log the number 10:

console.log(10);
10

Notice that we don't encapsulate the value 10 within quotation marks (' or "). This is because it's not a string, but rather a number.

Moving on, it's also possible to denote numbers having a decimal point in JavaScript. Such numbers are usually called floating-point numbers, or simply floats.

Once again, they are denoted just as we'd do them in normal writing. That is, we write the integer followed by the decimal point (.) followed by the fractional part.

Some examples of floating-point numbers are -1.0, -0.327, 0.7, 10.05, 8984564.45468975 and so on.

In the code below, we log the number 10.5:

console.log(10.5);
10.5

Simple.

As we'd discover in the JavaScript Data Types chapter later in this unit, unlike many programming languages out there, JavaScript only provides us with one number type. There aren't separate types for integers and floats, as there are in other languages.

Every number is essentially just a number and is internally represented in the format for a floating-point number.

We'll explore all the details to this design choice taken by JavaScript, the advantages and disadvantages of it, and many many more details regarding the different types of data in the language in the JavaScript Data Types chapter.

Basic arithmetic

Let's perform some basic arithmetic over numbers — the very basic ones such as addition, subtraction, multiplication, division, remainder, and exponentiation.

In JavaScript, each of these arithmetic operations is represented by a symbol, formally known as an operator.

For addition, we use the + operator. For subtraction, we use -, for multiplication *, and for division /. Finding the remainder of a division, also known as the modulo operation, is done using the % operator. Exponentiation is done using the ** operator.

Let's try all of these operations on a couple of numbers.

In the snippet below, we enter the given expressions directly in the console to inspect the aforementioned operators:

10 + 10
20
50 - 20.5
29.5
3 * 6
18
10 / 3
3.3333333333333
48 % 7
6
2 ** 10
1024

The last two operations work as follows:

  1. 48 % 7 returns the remainder when 48 is divided by 7. The result is 6.
  2. 2 ** 10 is simply 210 which is equal to 1024.

So this was easy, wasn't it?

Now here's a simple test:

10 - 6 * 10 + 2

What do you think would the output of this expression be?

Well let's try it out:

10 - 6 * 10 + 2
-48

It's -48 and that's because multiplication is performed before addition and subtraction.

In the dictionary of programming, this is known as operator precedence.

The multiplication operator (*) has a higher precedence than the addition (+) and subtraction (-) operators, hence it's performed first.

We'll learn more about operators and operations in the JavaScript Operations chapter.

As in many programming languages, to enforce a certain operation to be done before the other, we can use a pair of parentheses (()) to group that operation.

Here's the same expression as before, this time with the subtraction being done first:

(10 - 6) * 10 + 2
42

Simple, as always.

Variables

Recall variables from school algebra classes?

Well, variables in programming work pretty much the same way.

One of the most fundamental building blocks of programming is the idea of variables. They are one of the concepts taught in the beginning stages of nearly any programming language.

Let's start by understanding what exactly is a variable.

A variable is a container for holding data.

A variable can be thought of as a box with a label on it inside which we have the respective piece of data. This is a really good analogy to help us visualize how a variable works.

However, it doesn't necessarily convey the underlying mechanics of a variable from the perspective of computers. A more technical definition of a variable would be in terms of memory.

A variable is a name referring to a location in memory where some sort of data is stored.

It is merely an abstraction for working directly with all the tedious addresses of memory where our data resides.

With the definition out of the way, let's see how to create a variable in JavaScript.

The var keyword in JavaScript is used to create a variable. The general syntax of var could be expressed as follows:

var variable_name = value;

variable_name is the name of the variable while value is the value to put inside the variable.

Here's an example:

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.

A variable declaration introduces a new identifier into the execution environment and allocates memory for it. In our case above, this identifier has the name x.

The second part, i.e. x = 10 is commonly referred to as variable assignment.

The name 'assignment' comes from the fact that we assign a value to the variable. In our case, we assign the value 10 to x.

Now after the statement shown above executes, the 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 where we add 10 to x and then log the result:

var x = 10;

console.log(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 just like we'd perform the operations directly on the value 10:

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 realize that var x = 10 doesn't return anything and hence we get undefined logged.

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.

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 behavior 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 a 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 extracting a number out of a string are extremely common in practical level applications. The question is how to do so?

Just by converting the string into a number. In JavaScript, we can use the Number() function to get the numeric equivalent of a given string.

Shown below is the syntax of Number():

Number(value)

value is the value 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 and is returned by the last two expression since they can't be parsed as numbers by any means.

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

Time for a quick task.

Write a piece of code that defines a variable x holding the string '-50.6' and then logs the numeric equivalent of the string to the console.

var x = '10';
console.log(Number(x));
10

Code readability

Programs are parsed and executed by machines as we all know, however written and read by humans. Computers can read complex 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 actual writer of the code!

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 nicely 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 JavaScript engine, you'll definitely have a hard time understanding this code.

Only by adding a couple of spaces between words, and placing different statements on separate lines, we can make this same code much much more readable:

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!