Course: JavaScript

Progress (0%)

  1. Foundation

  2. Numbers

  3. Strings

  4. Conditions

  5. Loops

  6. Arrays

  7. Functions

  8. Objects

  9. Exceptions

  10. HTML DOM

  11. CSSOM

  12. Events

  13. Drag and Drop

  14. opt Touch Events

  15. Misc

  16. Project: Analog Clock

JavaScript Basics

Chapter 4 1 hr 23 mins

Learning outcomes:

  1. Working with numbers and arithmetic
  2. What are strings
  3. Working with variables
  4. Dialog boxes — alert(), confirm() and prompt()
  5. Conversion to a number
  6. What is code readability

Introduction

All programming languages have some sort of basic concepts attached to them that form their very foundation. And JavaScript isn't any way behind.

In this chapter, and in the next ones, we shall look into some of the very basic ideas of JavaScript. These include things such as obtaining user input; performing output; getting introduced to variables; using comments; working with statements and expressions; and much more.

There is a lot to learn in this chapter, all of which is essential for the upcoming part of this course. So, without wasting further time, let's get learning.

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 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 part, 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 type for numbers.

There aren't separate types for integers and floats, as there are in other languages. Every number is essentially just a number in JavaScript.

Internally, all numbers in JavaScript are represented in the format of a floating-point number. We'll see the exact details to this approach in the JavaScript Numbers unit.

Basic arithmetic

Let's now perform some basic arithmetic over numbers — the very basic ones such as addition, subtraction, multiplication, division, modulo, 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?

What does 50 % 11 return?

  • 4
  • 4.545454545454546
  • 6
  • 22

What does 4 ** 3 return?

  • 7
  • 12
  • 16
  • 64

Now let's consider a more complex expression:

10 - 6 * 10 + 2

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

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, based purely on the very principles of mathematics.

In the dictionary of programming, this behavior is formally referred to as operator precedence.

The multiplication operator (*) has a higher precedence than the addition (+) and subtraction (-) operators, hence it's performed first when they all appear in a given arithmetic expression.

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

To enforce a particular operation to be done before the other, we can use a pair of parentheses (()) to group that operation. This is standard across most, if not all, mainstream programming languages.

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

(10 - 6) * 10 + 2
42

Simple, as always.

We could use as many groups as we want. There's just no limit!

((10 - 6) * 10) + 2
42
( ((10 - 6) * 10) + 2 )
42

The only thing to be wary of is that we must keep the ( balanced with the corresponding ) characters and use () only where they could be used. If we fail to do so, we would simply run into a syntax error:

((10 - 6) * 10) + 2 )
Uncaught SyntaxError: Unexpected token ')'
(10 - 6 * 10 + 2)()
Uncaught TypeError: -48 is not a function

In the first statement, we have an unbalanced ) right at the end. The parser easily detects it and raises a syntax error right away.

In the second statement, however, the parentheses are balanced, yet we still get an error. That's because the () at the end act as calling the preceding expression (just as () calls document.write in document.write()) which turns out be a non-callable value, i.e. a number.

We'll learn more about callable and non-callable values once we learn about functions in JavaScript Data Types and then in JavaScript Functions.

Strings

It won't be wrong to say, even though graphical processing has seriously taken the charge in recent years, that 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 all 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 way to represent a string. We call it the simplest because typing a pair of single quotes requires less work than typing a pair of double quotes.

The piece of text that we want to represent literally in JavaScript goes between the quotes. And then the whole value, along with the quotes, is referred to as a string. Simple?

As we shall see later on, the quotes aren't actually part of the string. They are only used to help the parser distinguish literal text from literal code.

For example, suppose we want to output the text 'How are you?' out on the HTML document. We'd do so by using document.write() and an elementary string.

The code below shows how to make this output:

document.write('How are you?');

Carefully notice every part of the string value 'How are you?' here. The text that we want to denote goes as is between the pair of quote (''), and then we're done. It's that simple.

Running the code produces the following output:

How are you?

Super basic and super important.

Now, let's suppose we want to log the text 'Sorry, nothing here!' to the console. This time you should determine what to do.

Well, we'll just call console.log() with a string containing the desired text, as shown below:

console.log('Sorry, nothing here!');
Sorry, nothing here!

This is easy, isn't it?

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

This can be confirmed by both of the outputs produced above — in neither case do we notice any literal ' characters in the text displayed, thus confirming the fact that the ' character at the beginning and end of the strings isn't part of the actual data represented by them.

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

We could rewrite both the examples above using double quotes. Functionally, there isn't any difference at all between using single quotes or double quotes to denote strings in JavaScript.

Here is the first example rewritten:

document.write("How are you?");
How are you?

And here is the second example rewritten:

console.log("Sorry, nothing here!");
Sorry, nothing here!

As you can see, there is absolutely no difference in the outputs produced in either case.

But if there's no difference between single (') and double quotes ("), then what's the point of providing two ways of creating strings in JavaScript?

Well, double quotes are handy when we want to create a string that has single quotes in itself. Similarly, single quotes are handy when we want to create a string with double quotes in itself.

If we were to create such string using single quotes, then we couldn't directly use single quotes in the string itself, as they'd come in conflict with the single quotes used to denote to string. The same applies to double quotes.

Let's see what this means.

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 our expected output in the console. Instead, we see an error mesage 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 a 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 text "What's up?" in a string.

Here's how the problem arises:

How is the string 'What's up?' invalid?

The first single quote ('What's up?') in the string instructs the JavaScript parser that a string value follows. The parser then waits 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, rather it's considered as actual JavaScript. Putting an identifier or any other value next to a string is invalid, likewise the interpreter flags the character 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.

But then how do we denote a newline in a single-line string 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 the backslash 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, whenever a backslash appears in a single-quoted ('') or double-quoted ("") string in JavaScript, it denotes an escape sequence (together with the character following it).

But on its own, the backslash has no meaning — it has 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 across 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.

We'll aim at solving the same newline problem that we saw above.

Recall that we wanted to show a new line right after the Hello World! sentence in the string. Likewise, here's how we can insert that new line:

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

The ! character is followed by the escape sequence \n which denotes a new line character (yes, that's right, \n is also a character). \n takes the cursor to the next line and therefore whatever follows it 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 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. Using the <br> tag.
  2. Setting 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 new line, although we could still use.

The white-space: pre style declaration instructs the HTML engine to treat whitespaces in the source code just as they are. So, a sequence of five spaces would remain a sequence of five spaces; a newline would remain a newline; a tab would remain a tab; ans so on.

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

Consider the following HTML document, with the CSS that defines white-space: pre and the JavaScript that makes the output using \n:

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

Notice one extremely important thing in the code above. We've placed both the <style> and <script> tags in the <head> section. But why? Is there any reason for it? Yes.

Technically, we can put the <style> and <script> tags inside <body> as well. However, this would lead to an issue.

That is, if the tags are placed inside <body> just as they are written above in <head>, with all the nice indentations, then the space between the tags would be output to the document as well. This is due to the way white-space: pre works and the fact that document.write() writes text inside the <body> element.

Ultimately, the given text would appear after two lines and be awkwardly indented to the right, as shown below:

Hello World! JavaScript is awesome.

Putting the <style> and <script> tags inside <head> solves this spacing issue. This is because with this setup, the <body> element starts empty and so when document.write() puts the given text inside it, that text is the only thing in there.

Problem solved!

Moving on, a fairly common operation performed on strings in nearly all programming languages is that of concatenation.

Concatenation refers to the act of joining together two strings into one single string.

In JavaScript, concatenation is performed by the concatenation operator, which surprisingly turns out to be denoted using the same + symbol that's also used to denote the arithmetic addition operator.

Consider the following code:

console.log('Hel' + 'lo');

When we run it, we get the log shown as follows:

Hello

The expression 'Hel' + 'lo' instructs the engine to take the string 'Hel' and join it with the string 'lo' to ultimately produce the string 'Hello', which is then passed to the console.log() method.

The console snippet below demonstrates a couple of string concatenations:

'Hel' + 'lo' + '!'
'Hello!'
'How' + 'are' + 'you' + "?"
'Howareyou?'
'How ' + 'are' + ' you' + "?"
'How are you?'
'conca' + 'te' + 'nation'
'concatenation'

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 every 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 in a program, referring to a location in memory where some sort of data is stored.

A variable is merely an abstraction over working directly with the memory (as happens in assembly languages that don't have variables).

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.

What is a keyword?

There is a large collection of words in JavaScript that have special meanings. These are formally referred to as keywords of the language.

var, as we learnt just right now, is a keyword. Another keyword that we'll encounter later in this chapter is typeof. To name even more, we have for, while, switch, if, else, and so on.

There are tons and tons of them. We'll encounter most, if not all, of them in this course.

The general syntax of var could be expressed as follows:

var name = value;

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

Note that these italicized words (i.e. name and value) are placeholders for real data in the syntax. You have to replace them with real values in your code. We'll use this syntactic convention throughout the rest of this course.

Here's an example of creating a variable:

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 following var x, i.e. = 10, is commonly referred to as variable initialization.

The term 'initialization comes from the fact that we literally 'initialize' the variable to a given value to start with. In our case, this initial value is 10.

Now after this statement executes, a variable x becomes available in the entire program, 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, as shown below:

20

Always remember that 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 as we did 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
20
x - 2
8
x * 20
200
x / 2
5
x % 7
3
x ** 2
100

As can be seen, the variable x works exactly how 10 would've otherwise worked in each operation.

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, just as we get undefined logged when we write console.log() in the console.

We could change the value of a variable at any time during the execution of a program. This is done using a familiar syntax you've already seen above:

name = value

This is commonly referred to as variable assignment. We literally 'assign' a new value to the variable.

Consider the following example:

var x = 10
undefined
x + 10
20
x - 2
8
x = 60
60
x / 2
30
x % 7
4
x ** 2
3600
x = 150.75
150.75
x - 100.75
50

First, as before, we create a variable x initialized to the value 10 and perform a couple of operations using it. Then we change it to the value 60 and perform more operations. This time the operations get performed with the value 60. Finally, we change x, yet again, to the float 150.75 and then work with it.

This is the true essence of variables — of being able to be changed.

Keep in mind that there is a fine line between variable initialization and assignment. That is, precisely, they don't refer to the exact same thing, however they're surely related to one another.

Variable initialization vs. assignment

Variable initialization is a special kind of variable assignment that happens right at the time of declaring a variable.

Consider the following:

var x = 10;
x = 20;

Here, line 1 depicts variable initialization. Line 2 does NOT depict initialization; it's just a mere assignment statement.

Moving on, we could create as many variables in a program as we want to. There's again no bound!

So, let's make the console snippet above more interesting by introducing another variable y into it.

var x = 10
undefined
var y = 2.5
undefined
x + y
12.5
x - y
7.5
x * y + x
35
y + y * 2
7.5
x % (y + 0.5)
1

And we aren't just limited to storing numbers in variables — we could store anything.

In the following snippet, we store a string inside a variable and then pass the variable to console.log():

var greeting = 'Hello World!'
undefined
console.log(greeting)
Hello World!
undefined

Notice that the word greeting in the console.log() statement isn't surrounded in quotes. This is because it doesn't refer to a string, but instead to a variable.

Dialog boxes

JavaScript provides developers with three different kinds of dialog boxes that they could display to the end users. But what is a dialog box?

A dialog box is basically an UI (User Interface) element created by the browser itself. It serves to ask the user to input something, or notify the user about something.

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

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

Alert dialog

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

Now before we go on to understand alert(), let's first spare a couple of minutes to understand what exactly is meant by a function.

What is a function?

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

A function represents 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 itself, with some code in it (which we can't see). It's simply meant to display an alert dialog box to the user. And this is only done when we call the function.

To call a function, just like to call a method (since a method is also a function), we write a pair of parentheses (()) after the function's name.

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

JavaScript has a large collection of predefined functions. We'll cover the most common ones throughout this extensive course. Apart from these predefined ones, we can even create our own functions.

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 (as calculateTotalBill()) when you actually need to.

The world of functions is just endless!

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

Now coming to the concept of methods, a method, for e.g. document.write() and console.log(), is merely a special kind of a function.

Precisely, a method in JavaScript is a property of an object whose value is a function. (Yes that's right, even methods are properties!) We'll discover more details to methods in the JavaScript Objects unit once we understand properties in detail.

Anyways, from now on, throughout this course, whenever specifying a function or a method, we'll put () at the end of the respective entity to help us differentiate between functions/methods and other values.

Alright, let's get back to alert().

When called, the alert() method displays an alert dialog on the webpage:

alert();

Live Example

Until and unless this dialog is cleared in some way, that is, 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.

Syntax for a function

As we'll be covering a lot of functions and methods in this course, we need a formal way to be able to accurately express how to use those functions and methods.

We need to be able to know things such as how many arguments the function takes, the type of each argument, which arguments are required and which ones are optional, and so on.

Commonly this is referred to as the function's syntax, and sometimes even as the function's signature.

Here's how the syntax of the alert() function would look:

alert(msg)

The name of the function is followed by a pair of parentheses (()), describing each of its arguments, written in italics (indicating that it has to be filled with actual data).

In this case, it's stated that the alert() function takes a single argument called msg. But what is msg? Well, that would always be specified after the syntax snippet in a separate paragraph. In this case, msg is a string representing the message to show in the alert dialog.

Now it would be great if we could somehow indicate the fact that the msg argument is not required, i.e. it's optional and so it's possible to call alert() just as alert() (without anything between the parentheses).

Guess what — there is a pretty conventional way to do so, as described below.

When specifying the syntax of a function/method, enclosing a parameter in square brackets ([]) implies that it is optional.

By this means, we could express alert() more precisely as follows:

alert([msg])

[msg] simply means that the msg argument is optional.

Keep in mind that [ and ] don't have to be included in the actual invocation of 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.

Consider the following:

alert('Hello World!')

Here we aim to show the text 'Hello World!' in the alert message by passing the respective string to alert().

Live Example

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

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

To do so, as we learnt in the What are strings? section above, we could write \n next to the character after which we want a new line.

In the following code, we show two lines of text in the alert, 'Hello' followed by 'World!':

alert('Hello\nWorld!')

Live Example

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 used to obtain confirmation from the end user about a given action. It's represented by the confirm() function.

Here's its syntax:

confirm([msg])

Just like alert(), confirm() takes in a single, optional, msg argument which specifies the text to display in the confirmation dialog box.

Consider the code below:

confirm('This is a confirmation box')

Live Example

Shown below is how this confirmation dialog looks:

A confirmation dialog on Google Chrome for Windows.
A confirmation dialog on Google Chrome for Windows.

The confirmation is provided by selecting one of the two buttons: OK for confirmation and Cancel for denying it.

For the function confirm(), it returns true if the user presses OK, or else false. This return value is essentially how we're able to determine which button the user pressed.

A function's return value

The concept of functions in programming isn't very different from the concept of functions in mathematics. In fact, functions in programming were actually inspired by functions in mathematics.

Suppose you have the mathematical function ::f(x) = 2x::. You might've already worked with such functions from your old maths classes. What would you get when you write something such as ::f(10)::? Well, based on the laws of algebra, you'll get ::20::.

We say that ::20:: is what the function ::f(x):: returns when it's called with ::10:: as an argument.

The return value of a function is its response. After taking in certain inputs (optionally), and then processing them in some way, a function finally returns something, contextually meaningful, to us.

In JavaScript, all functions return something. That's just the way functions have to work.

In the case of alert(), it returns undefined. You encountered this same special value in the previous JavaScript Console chapter when you were exploring the console.log() method. That's because the console.log() method, which is also represented by a function, returns undefined as well.

We'll understand undefined very soon in the JavaScript Data Types chapter

In the case of confirm(), it returns a Boolean (see the next snippet) value specifying exactly which button did the user press on the confirmation dialog.

The return value of a given function effectively replaces its invocation.

For example, consider the following code:

var proceed = confirm('Do you want to proceed');

If we press the OK button on the confirmation dialog displayed as a result of the call to confirm() here, the function would return true.

And then this return value would replace the call to confirm() as illustrated below:

var proceed = true;

Simple.

Just how we could use a variable in every single way in which we could use the value stored inside it, we could use a function invocation in every single way in which we could use the value returned by it.

As a quick example, if we suppose that the function get10() returns the number 10, here are a couple of ways of using it:

get10() + 20
30
2 ** get10()
1024
var num = get10()
undefined
num * get10()
10

We'll see how to concretely define such as get10() function in JavaScript, in the chapter JavaScript Functions.

What is a Boolean?

In programming, a Boolean refers to a true or false value. It's used most commonly in conditional programming, i.e. executing code based on given conditions.

In JavaScript, the two literal Boolean values are true and false (without any quotes surrounding them). In the code below, we create two Boolean variables:

var isRaining = false;
var authenticated = true;

We shall cover Booleans in detail in the chapter JavaScript Conditions — Booleans.

For the curious learner, the name 'Boolean' is used in honour of the prolific English mathematician George Boole who's generally considered as the father of symbolic logic in mathematics.

Confirmation dialogs are not very frequently used in JavaScript applications.

Perhaps their most common use case, which even you might've come across at some point while surfing webpages, is to ask for the user's confirmation when he/she closes the underlying 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. Without confirm(), there's absolutely no way to accomplish the same behavior.

We'll use confirm() in this way, after quite a long while, in the JavaScript Events — Load Events chapter.

Prompt dialog

Last but not the least, we have the prompt dialog.

A prompt dialog is used to obtain input from the user. And it's given by the function prompt().

Syntactically, prompt() is a bit different from alert() and confirm():

prompt([msg[, defaultValue]])

As before, msg is a string to display in the dialog box. But this time, we could provide the function with a second defaultValue argument as well, which is the text to put in the input field of the prompt to begin with.

Both these arguments are optional as specified by the syntax above.

The awkward optional-parameter syntax

Notice the awkward nesting of square brackets ([]) in the snippet above. Once again, this is just that common convention of expressing the syntax of given functions, used all over programming.

Here's how to make intuition of this syntax:

Firstly, the outermost brackets ([msg[, defaultValue]]) imply that both the arguments to confirm() are optional. This is because both of them are inside the pair of brackets.

Secondly, the inner brackets ([msg[, defaultValue]]) imply that once we do specify a value for msg, defaultValue is further optional. That is, we can provide it with a preceding msg argument, or we can leave it.

The possibilities of invoking confirm() are as follows:

  • No arguments at all.
  • Just a msg argument.
  • A msg argument followed by a defaultValue argument.

If the syntax was expressed as [msg, defaultValue] (notice this carefully), without the inner brackets, then it would've meant something else.

In particular, it would've meant that, as before, both the arguments are optional, as they're both written inside the brackets, but if the first msg argument is provided, then it's a MUST to provide the second defaultValue argument as well.

The possibilities in this case would've been:

  • No arguments at all.
  • A msg argument followed by a defaultValue argument.

See how the previous case had three possibilities whereas this one has just two.

Being able to parse these syntaxes is very simple, yet a vital skill that'll continue for long in your programming voyage across other languages as well.

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 we enter 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 — 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 the age response back to the user. The text to output is composed by joining together three string values.

In our case, with age as '20', 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 convert such string values, that hold numbers, into actual numeric values in JavaScript. 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?

Well, 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 we want 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, Number() returns the respective number stored inside the given strings.

In the last two statements, however, it returns a weird value NaN. This is a special kind of a number in JavaScript, and it stands for Not-a-Number. It's returned by the last two expressions 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 = '-50.6';
console.log(Number(x));
-50.6

Code readability

As we all know, programs are parsed and executed by machines. However, typically, they are written and read by humans. (Some programs are also written by machines, but we won't be concerned with them for now.)

Computers can read complex and messy code, however we can't.

We need clean and nicely laid out code which can suffice us in reading and understanding it easily. No one is ever able to understand cluttered code, even not the actual writer of the code!

This is exactly what code readability is all about — our code should be readable.

From these very beginning stages, you should try your level best to write code that is easily readable and understandable by you yourself and then by other developers as well. No one should have to battle with your code in order to make the least sense of it.

Producing readable code is an indispensable and ingenious art, and there isn't any silver bullet to do it. There are numerous things that we could do in order to make a given piece of code more readable, including, but not limited to, choosing intuitive names, following conventions, applying design patterns, employing software architectures, and much more.

One of these is nicely formatting out your code.

Formatting refers to the way we structure out our code. It accounts for all the indentations, line breaks, and code conventions that we use in our code in order to make it look neat and readable.

For instance, consider the code below which is not well-formatted:

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

Unlike the JavaScript engine, we'll definitely have a hard time understanding this code. It's all squeezed in one single line and so it'll be a strenuous activity on our end to distinguish between different statements.

But just by adding a couple of spaces between words, and placing the statements on separate lines, we could make this same piece of code much more readable, as follows:

var x = 10;

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

See how serene this snippet looks.

We'll understand what is meant by if, in the code above, later on in the chapter JavaScript Control Flow.

Henceforth, from now on, whenever and wherever you write your code, make sure to follow certain code formatting guidelines as outlined below:

  • Put spaces between individual words, operators, expressions, and the like.
  • Put separate statements on separate lines.

In conclusion

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

In the coming chapters, we will get into a bit more detail of some concepts shown here and from there to even more details. Let's continue the journey.