JavaScript for .NET Developers

5 (1 reviews total)
By Ovais Mehboob Ahmed Khan
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. JavaScript for Modern Web Applications

About this book

If you want to improve responsiveness or the UX in your ASP.NET applications, JavaScript can be a life saver. In an age where server-side operations have shifted to the client, being able to handle JavaScript with confidence and fluency is vital for ASP.NET developers. There’s no point trying to fight it, so start learning with this book. Make sure your projects exceed user expectations.

Begin by getting stuck into the basics of JavaScript, and explore the language in the context of ASP.NET Core. You’ll then find out how to put the principles into practice, as you learn how to develop a basic ASP.NET application using Angular 2 and TypeScript. You’ll also develop essential skills required to develop responsive apps, with a little help from AJAX, ensuring that you’re building projects that can be easily accessed across different devices.

With guidance on Node.js and some neat techniques to test and debug a range of JavaScript libraries in Visual Studio, you’ll soon be well on your way to combining JavaScript with ASP.NET in a way that’s capable of meeting the challenges of modern web development head-on.

Publication date:
July 2016
Publisher
Packt
Pages
390
ISBN
9781785886461

 

Chapter 1. JavaScript for Modern Web Applications

The growth in web development evolved with a rapid pace in recent years. Most of the business applications that developed on a desktop platform are now shifted to the web platform, and the reason is the ease of access and continuous addition of rich capabilities on the web platform. Typically, any web application that provides the characteristics of the desktop applications is considered as rich web application. Thus, it involves extensive use of JavaScript and its frameworks and libraries.

JavaScript plays an important role in developing rich applications and allows developers to do less server-side post-backs and call server-side functions through ajaxified requests. Not only this, but now many companies and communities are developing good frameworks such as Angular, Knockout, ReactJS, and so on to bring state-of-the-art and groundbreaking capabilities. Microsoft has also released the WinJS library to access mobile native device features such as camera, storage, and so on from a web application running on mobile browsers. myNFC is also a great JavaScript library that allows developers to create applications for smartphones.

 

Importance of JavaScript


All the client-side frameworks are based on JavaScript. Being an ASP.NET developer, we should have solid concepts of JavaScript before using or integrating them in our applications. JavaScript is the client-side scripting language and one of the most popular programming languages of all times that run on top of a browser. When working on a web development project, this language serves you in many better ways to make user interface (UI) responsive. With JavaScript, you can manipulate HTML page Document Object Model (DOM) elements, call server-side code through ajaxified requests and bring new rich experience to your customers. There are many innovations being done at the core JavaScript library, and different frameworks and various libraries have been developed.

What is JavaScript?

JavaScript is a programming language created in 1995 by Brenden Eich. Initially, it was only supported by Netscape Browser, but later they decided to release a standard known as ECMA specification to let other browsers implement and provide engines to execute JavaScript on their browsers. The reason for providing the standard is to have the complete specification details for the party to follow and provide consistent behavior.

Earlier it was only targeted to execute on browsers and perform client-side operations that work with HTML pages and provide features such as manipulating DOM elements and defining event handlers and other functionalities. Later, and in recent years, it has become a powerful language and not only bounded to the client-side operations. With Node.js, we can use JavaScript on server side and there are various modules and plugins provided by Node to perform I/O operations, server-side events, and more.

Comparing runtimes

As this book is targeted for .NET developers, let's compare the JavaScript runtime with .NET runtime. There are a few things in common, but the basic runtime is different.

In .NET, Common Language Runtime (CLR) does the just-in-time (JIT) compilation on the code that is running and provides memory management. JIT compilation is done on the Intermediate Language (IL) code that is generated once you build your project.

In the JavaScript world, browser engine is the runtime for the JavaScript language. Every browser interprets JavaScript in its own way, but follows the ECMA scripting standards. Different browsers have different implementations, for example, Microsoft Edge uses Chakra engine, Chrome uses V8, and Firefox has Monkey engines. Initially, JavaScript was implemented as an interpreted language, but few modern browsers now perform JIT compilation. Every engine provides a set of services such as memory management, compilation, and processing.

The following diagram shows the comparison between both the architectures:

The JavaScript parser parses and tokenizes the JavaScript code into a syntax tree. All the browsers, except Google V8, parse the syntax tree and generate a bytecode that finally converts into a machine code through JIT compilation. On the other hand, Google V8 engine parses the syntax tree and instead of generating a bytecode first, it directly generates the machine code.

The .NET source code is compiled by its own language compiler, such as C# or VB.NET compiler and passes through the several stages of the compiler pipeline to generate an IL code. This IL code is then read by the JIT compiler that generates the native machine code.

 

Setting up your environment


Before going through this book, let's set up your environment. There are many renowned editors available in the market to create JavaScript projects such as Sublime Text, Komodo IDE, NetBeans, Eclipse, and more, but we will use Visual Studio 2015 that came up with some good improvements, helping developers to work on JavaScript in a better way than before.

To proceed, let's download and install Visual Studio 2015. You can download the Visual Studio 2015 community edition from https://www.visualstudio.com/, it's a free version and provides certain improvements as described in the following section.

New editing experience of JavaScript in Visual Studio 2015 IDE

The new Visual Studio 2015 IDE provides many rich features for developing web applications and various templates are available to create projects on different frameworks and application models. The earlier version already supported IntelliSense, colorization, and formatting but the new Visual Studio 2015 IDE has some more improvements that are as follows:

  • Added support for the ECMAScript 6 scripting language, which is formally known as ES2015. With the new ES2015, many features have been added, you can now define classes, lambdas, spread operator, and proxy objects. So, with Visual Studio 2015, you can get all IntelliSense using these features in your JavaScript code.

  • Support for popular JavaScript client-side frameworks such as Angular, ReactJS, and so on.

  • Documentation comments that help you add comments to your JavaScript methods and show the description when you use them:

  • IntelliSense for new JavaScript APIs such as touch event and Web Audio API.

  • You can use tokens such as //TODO, //HACK, and //UNDONE, and it gives you a listing in the Task List window that helps to trace the to-do items:

  • With JavaScript files, Visual Studio 2015 provides the same navigation bar we used to see when writing classes in any .NET language. Selecting and navigating to different methods of JavaScript is far easier with this feature:

 

Programming in JavaScript


JavaScript is one of the most powerful languages that plays a vital role in any web development project and delivers client-side support and rich functionality. In this section, we will discuss the core concepts of writing programs in JavaScript and use them in web applications.

Core fundamentals of JavaScript

Like any other programming language, JavaScript also has statements, expressions, operators, and specific syntax to write and run programs. We will go through the following topics in this section:

  • Adding JavaScript to an HTML page

  • Statements

  • Literals and variables

  • Data types

  • Expressions and operators

Adding JavaScript to an HTML page

Every modern browser has a JavaScript engine that compiles your JavaScript defined on the page. JavaScript can be placed in the <head> or <body> sections of your HTML page. Any statement that is defined under <script></script> tags will be considered a JavaScript statement and will be processed and understood by the browser's engine.

The following code snippet shows a simple HTML page containing the <script></script> tags defined within the <head></head> section:

<html>
  <head>
    <script>
      alert("This is a simple text");
    </script>
  </head>
</html>

When the page loads, it will show the pop-up message and a text as This is a simple text. The browser's JavaScript engine executes any script that is defined under the <script> tag and runs the statements defined within this block. Any statement that is defined directly under the scripting tag is executed every time the page is loaded.

Similarly, we can also define the JavaScript within the <body> section of the HTML page:

<html>
  <body>
    <script>
      alert("hello world");
    </script>
  </body>
</html>

Tip

It is a good idea to place scripts at the bottom of the page because the compilation can slow down the page loading.

Normally, in every project, irrespective of the project size, separating the <script> section from HTML makes the code look cleaner and easy to maintain. JavaScript file extensions are named .js and you can also create these files separately in some scripts folder and reference them in our HTML page.

In Visual Studio, you can easily create a JavaScript file using the Add | JavaScript File option as shown in the following:

Once the file is created, we can directly write the JavaScript syntax without any <script></script> tags. JavaScript files can be referenced in your HTML page using the src attribute of <script></script> tags. Here we referenced test.js in the HTML page:

<script src="~/test.js">
</script>

Placing the <script> tag either in the <head> or in the <body> section depends on the page. If your page referencing some large JavaScript files takes a long time to load, it is better to define them at the end of the <body> section. This is a better approach, so when the browser starts parsing your page, it is not stuck downloading your scripts and delaying the rendering. On the other hand, we can define JavaScript files in the <head> section only if they do not impact the performance or page life cycle. Scripts defined at the bottom get parsed when the whole page loads. There are also a few attributes such as async and defer that we can use within the <script> tag and most of the browsers support this.

The following is an example showing the use of async in the <script> tag:

<script src="~/test1.js" async></script>
<script src="~/test2.js" async></script>

Scripts defined with async are executed asynchronously without blocking the browser to load the page. However, if multiple scripts are there, then each script will be executed asynchronously and at the same time. This may lead to the possibility of completing the second script before the first one gets completed and might throw some errors if one is dependent on the other. For example, when working with some client-side frameworks, such as Angular framework, JavaScript code that is using Angular components is dependent on AngularJS library, and in this case, if our custom JS files are loaded before the AngularJS library on which they are dependent, they will throw an exception.

To overcome this scenario, we can use defer to execute scripts in a sequence. We can use defer as follows:

<script src="~/test1.js" defer></script>
<script src="~/test2.js" defer></script>

The basic difference between async and defer is that async downloads the file during HTML parsing and pauses the HTML parser to execute it until it is completely downloaded, whereas defer downloads the file during the HTML parsing and executes it after the HTML parser is completed.

Statements in JavaScript

Statements are the collection of words, expressions, and operators to perform a specific task. Like other programming languages, statements in JavaScript could also be assigning a value to the variable, performing arithmetic operations, implementing conditional logic, iterating through collection, and so on.

For example:

var a; //variable declaration
a = 5; //value assignment
a = 5 * b; //value assignment
a++; // equivalent to a= a+1
a--; // equivalent to a= a-1
var method = function () { … } // declare function
alert("Hello World") // calling built-in function
if(…) {…} else {…}
for (…) {…}
while(…) {…}

However, you can use semicolons with the do while loop:

do {…} while (…);
function statement
function (arg) { //to do }

Tip

If multiple statements are defined in the same line, they should be separated by a semicolon, otherwise they will be treated as a single statement. On different lines, a semicolon is not mandatory but a good practice to use.

Literals and variables

There are two types of values in JavaScript: literals or fixed values and variables.

Literals could be number, string, or date objects.

For example:

Numbers
22.30
26
Strings
"John"
"10/Jan/2015"

Variables are used to store values. In JavaScript, we can define variables using the var keyword. JavaScript is not a type-safe language and the type is identified when the value is assigned.

For example:

var x=6;
var x="Sample value";

Data types

Every programming language has certain data types available to hold specific data. For example, in C#, we can use String to hold string values, int to hold 32-bit integer value, DateTime to hold value in the date and time format, and so on. JavaScript does not provide strong data types such as C# and other programming languages, and it's a loosely typed language. As per the latest ECMA 6 standard, JavaScript provides six primitive data types and an object. All primitive data types are immutable, this means that assigning a new value will be allocated into a separate memory. Object is mutable and its values can be changed.

The primitive types are as follows:

  • Boolean: This holds the logical value true or false.

  • Null: This holds the null value.

  • Undefined: This is a variable that does not assign a value and has value as undefined.

  • Number: This holds numeric values. The size of the number type is double-precision 64 bit in which the number (fraction) is stored from 0 to 51 bits, the exponent in 11 bits from 52 to 62, and sign in 1 bit 63.

  • String: This holds any kind of textual value.

Complex types are termed as object. In JavaScript, the object is formulated in a JSON format.

Array in JavaScript

Array is used to store collections of data. You can simply define an array in JavaScript as shown in the following:

var browsers = ["Microsoft Edge", "Google Chrome", "Mozilla Firefox", "Safari"];

You can access them through the array index. The index starts from 0 till the number of items in the array.

We can access the array items as follows:

var a= browsers[0]; //returns Microsoft Edge
var b= browsers[1]; //returns Google Chrome
var c= browsers[3]; //returns Safari

In order to get the total number of items in an array, you can use the length property:

var totalItems = browsers.length;

The following is a list of some of the most commonly used methods:

Method

Description

indexOf()

This returns the first index of an element available within the array equal to the specific value, returns -1 if not found.

lastIndexOf()

This returns the last index of an element available within an array equal to the specified value, returns -1 if not found.

pop()

This deletes the last element from an array and returns that element.

push()

This adds one element to an array and returns the length of an array.

reverse()

This reverses the order of elements in an array. The first element becomes the last and last one becomes the first.

shift()

This deletes the first element and returns that element.

splice()

This is used to add or remove elements from an array.

toString()

This returns all the elements in a string representation.

unshift()

This adds elements to the front of an array and returns the new length.

Tip

Downloading the example code

Detailed steps to download the code bundle are mentioned in the Preface of this book. Please have a look.

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/JavaScript-For-.NET-Developers. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

What is JSON?

JavaScript Object Notation (JSON) is a lightweight, interchangeable format for defining objects in JavaScript. Any kind of object can be defined through JSON and it is used to build universal data structures. Whether it's a simple object, arrays, nested arrays, or complex object, each can handle in the JSON format.

Simple objects in JSON

The following code snippet shows the person object that has three properties, namely name, email, and phone:

var person = {
  "name" : "John Martin",
  "email": [email protected],
  "phone": "201892882"
}

We can access these object properties as follows:

person.name;
person.email;
person.phone;
Declaring arrays in JSON

The following code snippet shows the way of declaring arrays in JSON:

var persons =
[{ 
  "name":"John",
  "email": "[email protected]",
  "phone":"201832882"
},
{
  "name":"Steve",
  "email": "[email protected]",
  "phone":"201832882"
},
{
"name":"Smith",
"email": "[email protected]",
"phone":"201832882"
}]

According to the preceding declaration of an array, it can be accessed as follows:

//returns name of the first item in the collection i.e. John
Persons[0].name
//returns email of the first item in the collection i.e. [email protected]
Persons[0].email
//returns name of the second item in the collection i.e. Steve
Persons[1].name
Nesting data in JSON

The JSON format easily handles nested arrays. Let's look at the complex objects containing an employee object that contains the Experiences array with the nested array to hold projects, and each project has a nested array to hold technologies used in each project:

var employee=
{
  "ID":"00333",
  "Name":"Scott",
  "DateOfJoining":"01/Jan/2010",
  "Experiences":[
    {
      "companyName":"ABC",
      "from":"Nov 2008",
      "to":"Oct 2009",
      "projects" :[
        {
        "title":"Sharepoint Migration",
        "noOfTeamMembers":5,
        "technologyUsed":[{"name":"SharePoint Server"}, {"name":"C#"}, {"name":"SQL Server"}]
        },
        {
        "title":"Messaging Gateway",
        "noOfTeamMembers":5,
        "technologyUsed":[{"name":"ASP.NET"}, {"name":"C#"}, {"name":"SQL Server"}]
        }
      ]
    },
    {
      "companyName":"XYZ",
      "from":"Nov 2009",
      "to":"Oct 2015",
      "projects" :[
        {
        "title":"ERP System",
        "noOfTeamMembers":5,
        "technologyUsed":[{"name":"ASP.NET"}, {"name":"C#"}, {"name":"SQL Server"}]
        },
        {
        "title":"Healthcare System",
        "noOfTeamMembers":4,
        "technologyUsed":[{"name":"ASP.NET"}, {"name":"C#"}, {"name":"SQL Server"}]
        }
      ]
    }
  ]
}

In the preceding script, the array has an employee object containing some properties such as ID, name, and date of joining, and then one experiences property that holds an array of experiences and each experience holds the projects that the employee did in a particular workplace.

Conversions in data types

As the data types in JavaScript are dynamic in nature and data type is determined based on the value assignment, JavaScript does not throw any exception on type conversion and deals in several ways as follows.

For example, the following is the JavaScript code snippet showing the assignment of different expressions.

First assign the string to the res variable:

var res="Hello World";

Then assign numeric to the same res variable:

res= 2;

Finally, concatenate string 3 to the res variable that holds the following numeric, but due to the higher precedence of numerical value, the resultant value becomes 5:

var result = res + "3"

So, no matter what was the type of the variable first assigned to it, it will change its type based on the assignment and dynamically handle the conversions.

Elements of JavaScript

Here are some of the important elements of JavaScript that are essential to learn before we start programming in JavaScript.

Constants in JavaScript

Constants in JavaScript can be defined with a const keyword. Constants are the immutable values that are known at compile time, and values do not change throughout the life cycle of the program.

The following is the JavaScript code showing the assignment of a constant variable. When using const, var is not required and you can declare constant values with only the const keyword:

const pi= 3.42

Comments

Comments can be added with // and /* */. To comment a single line, you can use //, otherwise /* */ for a block of code.

The following is the JavaScript code showing the way of commenting a single line or block of code:

<script type="text/javascript">

function showInformation() {

  //var spObj = window.document.getElementById("spInfo");
  spObj.innerHTML =
    "Available Height: " + screen.availHeight + "<br>" +
    /*"Available Width: " + screen.availWidth + "<br>" +
    "Height: " + screen.height + "<br>" +*/
    "Width: " + screen.width + "<br>"
}

</script>

Case sensitivity

JavaScript is a case-sensitive language and it follows the Pascal naming convention to define variables and methods.

For example, if the method name is doWork(), it can only be accessed by calling it with the exact case, and calling either DoWork() or Dowork() will not work and throw exception.

Character set

JavaScript is based on a Unicode character set and follows the Unicode Standard.

Note

What is the Unicode Standard?

It is a worldwide coding standard that most languages use. C# and VB.NET follow the same Unicode Standard. It provides a unique number for every character, for example, A = 41, a = 61, and so on.

The current version of the Unicode Standard is Unicode 8.0.0 and the documentation can be located at http://www.unicode.org/versions/Unicode8.0.0/.

Expressions

Expression can be recognized as the statement of code that assigns some value to the variable. Expressions are categorized into two types.

The first type of expression can be termed as simple expressions that assigns a value to the variable:

var x = 2;

The preceding example denotes the simple expression of assigning numeric value 2 to an x variable.

The second type of expression can be termed as any arithmetic or string operation to the values on the right and assigning them to any variable. These type of expressions perform the operation first before assigning value to the variable:

var x = 2+3
var x = "Hello" + "World";

This is an example of the second type of expression that adds two numbers and assigns the resultant value to the x variable. Same goes for the second statement that performs the string concatenation operation and assigns the Hello World value to the x variable.

The this keyword

Just like C# and other object-oriented languages, JavaScript has objects and there are certain ways to define classes, functions, and so on that we will study later in this chapter. Just like C#, in JavaScript, we can access the object and its properties through the this keyword. Let's take a look at some examples showing the scope of the this keyword in JavaScript.

The following is a customer object that contains a few properties and the utilization of the this keyword:

var customer =
  {
    name: "John Marting",
    email: "[email protected]",
    mobile: "109293988844",
    show: function () {
      alert("Name: "+this.name + " Email: " + this.email + " Mobile: " + this.mobile);
    }
  }

In the preceding example, we have defined a JavaScript object that contains three properties and a function. To access these properties, we can use the this keyword just like C#. However, we can also access the properties using the customer variable, as shown in the following:

var customer =
  {
    name: "John Marting",
    email: "[email protected]",
    mobile: "109293988844",
    show: function () {
      alert("Name: "+ customer.name + " Email: " + customer.email + " Mobile: " + customer.mobile);
    }
  }

The scope of the this keyword is limited within the boundary of an object. Whereas, the customer variable in the preceding example could be defined somewhere else on the page and may lead to an incorrect behavior. It is a better approach to use the this keyword wherever possible and avoid using object variables directly.

All variables and functions defined directly under the <script> tag are termed as global variables and functions. We can also access them through the this keyword. In this case, this will be referred as the global window object and not the child, that is, the customer object we have used in the previous example:

<script type="text/javascript">
  var name = "";

  function ShowMessage() {
    alert(this.name);
  }
</script>

Unlike this, you can also refer the variables and functions through the window keyword. The following code snippet will show the name of the window in the dialog box:

alert(window.name);

Let's take a look at the complete example, where we have global variables defined, as well as child objects, and the scope of this will be determined based on the context of its call:

<script type="text/javascript">
  var name = "Scott Watson";

  var customer =
    {
      name: "John Marting",
      email: "[email protected]",
      mobile: "109293988844",
      show: function () {
        alert("Name: " + this.name + " Email: " + this.email + " Mobile: " + this.mobile);
      }
    }
  function ShowMessage() {
    alert("Global name is " + this.name);
    alert("Customer info is " + customer.show());
  }
</script>

In this preceding example, we will get two JavaScript alert messages. The first alert will display Scott Watson, which is defined globally, and the second popup shows the customer name, e-mail address, and mobile number. Hence, we can use this in two places, but the scope is determined based on the context from where it is calling from.

Sequence of code execution in JavaScript

When programming in JavaScript, we have to keep the sequence of defining things before they get called. Considering the preceding example, if we define the customer object after the ShowMessage() method, it will not be recognized and nothing will be displayed.

Using the this keyword on a calling method

Let's take a look at the sample HTML page that has a JavaScript function named Multiply and takes two parameters: obj and val. This method will be called when the user enters any input into the textbox and it will pass the reference of the textbox control at the first parameter. This can be passed through the this keyword:

<html>
<head>
  <script type="text/javascript">
    function Multiply(obj, val) {
      alert(obj.value * val);
    }
  </script>
</head>
<body>
  <input type="text" onchange ="Multiply(this, 2);" />
</body>
</html>

The function statement and expression

The function statements are a way of defining methods in JavaScript. Each function has a signature, containing the name and parameters passed in. Functions can be declared in many ways in JavaScript. For example, the following is the sample GetPerson(id) function that returns the person object based on the ID passed as a parameter. This is the normal way of declaring function in JavaScript:

<script>
  
  function GetPerson(id) {
    return service.GetPerson(id);
  }
  
</script>

The function return type is computed at runtime and not part of the function signature. Returning values is not mandatory and you can keep functions without returning any values.

On the other hand, anonymous functions do not have any name and they can either be passed as an argument to other functions or defined without a function name. The following are the examples of anonymous functions:

var showMessage = function(message){
  console.log(message);
}
showMessage("Hello World");

Another example of defining anonymous function and passing it as a parameter is as follows:

function messageLogger(message ,logMessage) {
  logMessage();
}

function consoleMessage() {
  alert("Hello World");
}
messageLogger(consoleMessage());

The function expression is equivalent to function, but the only difference is that it should not start with the function name.

Class statement and expression

With ECMAScript 6, we can create classes in JavaScript. Just like other programming languages, we can create a class using the class keyword. With this, we can write cleaner code than developing functions that were represented as classes in the earlier version of ECMAScript.

Let's take a look at the Rectangle class that calculates an area:

<script>
  class Rectangle {
    constructor(height, width) {
      this.height=height;
      this.width=width;
    }
    get Area() {
      return this.calcArea();
    }
    calcArea(){
      alert("Area is "+ this.height * this.width);
    }
  }
</script>

Each class should have one constructor and give an error if multiple constructors are specified. Class expression is another way of defining classes. Just like anonymous functions, we can define classes in a similar way.

Let's take a look at the example of the same class defined earlier:

<script>
  var Rectangle = class{
    constructor(height, width) {
      this.height=height;
      this.width=width;
    }
    get Area() {
      return this.calcArea();
    }
    calcArea(){
      alert("Area is "+ this.height * this.width);
    }
  }
</script>

The next chapter will cover more details about classes and the attributes and keywords available to structure them.

Grouping operator

For any arithmetic expression, JavaScript uses the BODMAS rule. The precedence will be given to brackets then multiplication, division, addition, and subtraction. The grouping operator is used to give higher precedence to the expression if any of the member in the expression have higher precedence by default.

For example:

var a = 1;
var b = 2;
var c = 3;
var x = a + b * c;

The resultant x will be 7 as multiplication gets the higher precedence. However, what if we need to perform addition first?

We can use grouping operator as follows that gives the result 9:

var x = (a + b) * c;

new

In the same way as C#, the new keyword is used to instantiate any object in JavaScript. In order to create an instance of any user-defined or predefined type, use the new keyword:

var obj=new objectType();

super

The super keyword is used to call methods of the parent object. In C#, we use the base keyword to call the base class method or properties. In JavaScript, we can use it as follows:

super.functionOnParent();

Operators

Operators are the object used to manipulate values of an operand. For example, 1 + 2 results in 3, where 1 and 2 are operands and + is an operator. In JavaScript, we can use almost all the operators to concatenate strings, do arithmetic operations, and so on. In this section, let's see what type of operators we can use when writing programs in JavaScript language.

We will discuss the following operators in this section:

  • Assignment operators

  • Arithmetic operators

  • Unary operators

  • Comparison operators

  • Logical operators

  • Bitwise operators

  • Bitwise shift operators

  • The typeof operator

  • The void operator

  • The delete operator

  • Miscellaneous operators

Assignment operators

Assignment operator is represented as (=) and the assignment is done from right to left.

For example, x=y means that the value of y is assigned to x.

Arithmetic operators

The following is a list of arithmetic operators you can use to perform addition, subtraction, division, and multiplication and use them with the assignment statements:

Name

Operator

Meaning

Addition

x + y

The value of x is added to y

Subtraction

x – y

The value of y is subtracted from x

Division

x / y

The value of x is divided by y

Multiplication

x * y

The value of x is multiplied to y

Remainder

x % y

The value of x is divided by y and the remainder is returned

Addition assignment

x += y

x = x + y

that is, the value of x and y will be added and assigned to x

Subtraction assignment

x -= y

x= x – y

that is, the value of x and y will be subtracted and assigned to x

Multiplication assignment

x *= y

x = x * y

that is, the value of x and y will be multiplied and assigned to x

Division assignment

x /= y

x = x / y

that is, the value of x will be divided by y and assigned to x

Remainder assignment

x %= y

x = x % y

that is, the value of x will be divided by y and the remainder will be assigned to x

Exponentiation assignment

x **= y

x = x ** y

that is, the value of x will be exponentially multiplied twice to y and assigned to x

Unary operators

Unary operator works with only one operand. It can be used for increment, decrement, inversion, and so on:

Name

Operator

Meaning

Increment operator

x++

The value of x will be incremented by 1

Decrement operator

x--

The value of x will be decremented by 1

Logical complement operator

!(x)

This inverts the value of x

Comparison operators

Comparison operator is used to compare operands that returns a Boolean true value if the comparison is true. Operands can be of any data type, have an associativity from left to right, and perform dynamic conversion if they are of different types.

For example, if the value of x is 2 and y is "2". Here, y denotes that it's a string, but in comparison, it will return true:

x==y //returns true

Similar to C# or any programming language, JavaScript supports all these operators, such as equal (==), not equal (!=), greater than (>), and less than(<), but due to the dynamic type binding, it also provides two operators such as strict equal (===) and strict not equal (!===) to confirm if the type is also the same if the value is same and vice versa.

We will now have a look at strict operators. There are the following two types of strict operators:

  • Strict equal operator

  • Strict not equal operator

Strict equal operator

In the previous section, we discussed that JavaScript provides dynamic binding and if the value of two different data types, suppose number and string, are the same, it will return true on comparison. For example, if x is 1 and y is "1", it will return true. Now, what if we have to do the comparison work only if the type is also the same? Here comes the strict equal operator that does not only check the value, but also match the types of both the operands.

The strict equal operator can be represented as ===.

For example, if x = 1 and y = "1" and the comparison is done like (x===y), it will return false as x represents number and y represents string.

Strict not equal operator

Contrary to the strict equal operator, if we want to compare the values of two operands of same type, we can use the strict not equal operator.

The strict not equal operator can be represented as !===.

If x = 1 and y = 2 and the comparison is done like (x!==y), it will return true. This is because the types are the same and the values are different.

Logical operators

Just like C#, JavaScript uses the same types of logical operators to handle logical conditions. Logical operators are used to handle multiple conditions in a logical statement.

Logical AND

Logical AND is represented as && and is used in two or more operands or conditions in statements.

For example, the following is the code snippet that shows the method that takes three parameters and the logic is defined that checks whether number1 is equal to number2 and the summation of number1 and number2 is equal to number3 to return true:

<script>
  function CheckNumbers(number1, number2, number3) {
    if ((number1 == number2) && ((number1 + number2) == number3)) {
      return true;
    }
  }
<script>
Logical OR

Logical OR is represented as || and is used with two or more operands or logical conditions.

For example, the following is the code snippet that shows the method that takes three parameters, and if any of the numbers is equal to the value 10, it will return true:

<script>
  function AnyNumber10(number1, number2, number3) {
    if ((number1 ==10 || number2 == 10 || number3 ==10) {
      return true;
    }
  }
</script>
Logical NOT

Logical NOT is represented as ! and used with conditions that return a Boolean value. For example, if any logical condition returns true, this operator will make it false. It can be used as follows. In the code snippet, if number1, number2, and number3 are equal to 10, the method will return false. If they are different, the return value will be true:

<script>
  function AnyNumber10(number1, number2, number3) {
    return !(number1 ==10 && number2 == 10 && number3==10) {
    }
  }
</script>

Bitwise operators

Bitwise operators consider each number or operand as binary (a combination of 0 and 1). Every number has specific binary corresponding to it. For example, number 1 binary is represented as 0001 and 5 represented as 0101.

Bitwise operators work on 32-bit numbers and any numeric operand is first converted into a 32-bit number and then converted back to JavaScript number.

Bitwise operators perform their operations in binary and return the result as numbers.

For example, x is 1 and y is 9.

1 represented as 0001.

9 represented as 1001.

Bitwise AND

Bitwise AND is represented as & and the following is the comparison of each bit of operand 1 and 9. If both value on each bit is 1, the result will be 1, otherwise 0:

Number = 1

Number = 9

Result

0

1

0

0

0

0

0

0

0

1

1

1

In the JavaScript code, we can use it as follows:

<script>
  var a = "1";
  var b = "9";
  var c = a & b;
</script>

Finally, the resultant value will be 0001, which is equal to 1.

Bitwise OR

Bitwise OR is represented as | and the following is how the bit OR will be operated:

Number = 1

Number = 9

Result

0

1

1

0

0

0

0

0

0

1

1

1

The following code snippet shows the usage in JavaScript:

<script>
  var a = "1";
  var b = "9";
  var c = a | b;
</script>

Finally, the resultant value will be 1001, which is equal to 9.

Bitwise NOT

Bitwise NOT is represented as ~ and it works on a single operand and inverse each bit of the binary.

For example, if the number 9 is represented as 1001, it will be converted to a 32-bit number and then bitwise NOT will make it 11111111111111111111111111110110, which is equal to -10.

The following is the code snippet:

<script>
  var a = ~9;
</script>
Bitwise XOR

Bitwise XOR is represented as ^ and it works with two or more operands.

The following table shows how the bitwise XOR is operated:

Number = 1

Number = 9

Result

0

1

1

0

0

0

0

0

0

1

1

0

The following code snippet shows the usage in JavaScript:

<script>
  var a = "1";
  var b = "9";
  var c = a ^ b;
</script>

Finally, the resultant value will be 1000, which is equal to 8.

Bitwise shift operators

There are three kinds of bitwise shift operators, as follows:

  • Bitwise left shift operator

  • Bitwise right shift operator

Bitwise left shift

It is represented as << and is used to shift a bit from the right side to the binary value of any number.

For example, number 9 is represented as 01001, and if we use bitwise left, the resultant value will be 10010, which shifted one bit from the right.

The following code snippet shows the usage in JavaScript:

<script>
  var a = 9;
  var result = a << 1;
</script>

Finally, the resultant value will be 10010, which is equal to 18.

Bitwise right shift

It is represented as >> and is used to shift a bit from the left side to the binary value of any number.

For example, number 9 is represented as 1001, using bitwise right will give the resultant value as 0100.

The following code snippet shows the usage in JavaScript:

<script>
  var a = "9";
  var result = a >> 1;
</script>

Finally, the resultant value will be 0100, which is equal to 4.

The typeof operator

This is used to check whether the type of the variable is an object, undefined, number, and so on. In JavaScript, we can use this as follows:

<script>
  if (typeof a=="number") {
    alert("this is a number");
  }
</script>

Here is the list of possible values returned by the typeof operator:

Value returned

Description

"number"

If operand is a number

"string"

If operand is a string

"boolean"

If operand is a Boolean

"object"

If operand is an object

null

If operand is null

"undefined"

If operand is not defined

The void operator

The void operator prevents an expression to return any value. It is essential in conditions where you need to evaluate the expression but don't need the return value in the program.

You can write any expression or statement inside the void method.

For example, the following code snippet shows the simple example of using a void operator to display alert message when the link is clicked. Here, the alert expression is evaluated once the user clicks on the link:

<html>
<head></head>
<body>
  <a href="javascript:void(alert('You have clicked!'));">
  </a>
</body>
</html>

When the page runs and the user clicks on the link, it will display an alert message box as shown in the following:

Moreover, passing 0 as an expression within the void method will do nothing:

<html>
<head></head>
<body>
  <a href="javascript:void(0);">
  Do Nothing
  </a>
</body>
</html>

Another example here is using void to add two numbers and returning undefined for the assigned operand:

<script>
  var n1 = 6;
  var n2 = 7;
  var n3;
  var result = void (n3 = n1 + n2);
  alert ("result=" + result + "and n3 =" + n3);
</script>

The delete operator

A delete operator is used to delete objects and its properties, but not the local variables. The following example shows the way you can use the delete operator in JavaScript:

var country = { id: 1, name: "USA" };

  delete country.id;

  alert(country.id);

Calling country.id will return undefined, as this was already deleted in the preceding statement. On the other hand, if we delete the country object, it would not delete and display the country ID as 1:

var country = { id: 1, name: "USA" };

  delete country;

  alert(country.id);

Miscellaneous operators

Here are few other operators that are available in JavaScript.

Conditional operators

Conditional operator is represented as (?:):

expression1 ? expression2: expression3

It works as cross-selector to evaluate expressions. If the first expression is true, the second expression will be executed, otherwise the third will be executed.

The following is the code snippet for using conditional operator to evaluate expression. There is a compareValues() function that takes two parameters, and an alert will be displayed stating whether both the parameters are equal or not equal:

<script>
  function compareValues(n1, n2)
    (n1 == n2) ? alert("Both values are equal") : alert("Passed values are not equal");
</script>
Spread operator

The spread operator is represented as (…). It is used where you expect multiple arguments to be passed in for a function call.

For example, if your function is taking five parameters, you can either pass those values one by one as the parameter value when calling that method or keep them in an array and pass that array through the spread operator.

The following code snippet shows the actual example of using this in JavaScript:

function multipleArgs(a, b, c, d, e){
}
var args = [1,2,3,4,5]
multipleArgs(…args);

Built-in display methods in JavaScript

The following are the display methods available in JavaScript to provide notifications and messages to users in different forms.

Displaying messages

There are the following three types of pop-up dialog boxes:

  • Alert message box

  • Confirmation message box

  • Prompt message box

Alert box

Using window.alert(), we can pop up an alert dialog box:

<!DOCTYPE html>
<html>
<body>

  <h1>My First Web Page</h1>
  <p>My first paragraph.</p>

<script>
  window.alert(5 + 6);
</script>

</body>
</html>
Confirm box

Using window.confirm(), we can pop up a confirm dialog box that returns the event result the user has taken. When a confirm dialog box pops up, it provides two action events: OK and Cancel. If a user click on OK, true will be returned, otherwise false. The following code shows the usage of the confirm dialog box on your HTML page.

The following is the code snippet for using a confirm dialog box to confirm with the user before saving a record:

<!DOCTYPE html>
<html>
<body>

<script>
  var r = window.confirm("are you sure to save record");
  if(r==true){
    alert("Record saved successfully");
  }
  else {
    alert("Record couldn't be saved");
  }
</script>

</body>
</html>
Prompt box

Prompt dialog box is used in cases when you want the user to supply the value. It can be used in conditions where you require user input.

The following code snippet shows the way of using a prompt message box in the JavaScript program:

<!DOCTYPE html>
<html>
<body>

<script>
  var name = window.prompt("Enter your name","N/A");
  if(name !=null){
    alert("hello "+ name "+, how are you today!");
  }
</script>

</body>
</html>

Writing on a page

We can use the document.write() method to write anything on the screen.

The following code snippet shows the way of writing any text on a web page in JavaScript:

<!DOCTYPE html>
<html>
<body>
  <script>
  document.write("Hello World");
  </script>
</body>
</html>

Writing into the browser's console window

Using console.log(), we can write any text into the browser's console window.

The following code snippet shows the way of writing text into the browser console window for tracing or debugging purposes in JavaScript:

<!DOCTYPE html>
<html>
<body>
  <h1>My First Web Page</h1>
  <p>My first paragraph.</p>
  <script>
  console.log("Entered into script execution context");
  </script>
</body>
</html>

Browser Object Models in JavaScript

JavaScript provides some predefined global objects that you can use to manipulate the DOM, close browsers, and so on. The following are the browser objects we can use to perform different operations:

  • Window

  • Navigator

  • Screen

  • History

  • Location

Window

Window object refers to the open window in a browser. If in the HTML markup, some iframes are defined, a separate window object will created. Through the window object, we can access the following objects:

  • All global variables

  • All global functions

  • The DOM

The following shows an example of accessing the DOM from the window object and accessing the textbox control.

Document

window.document returns the document object and we can use its properties and methods for a specific reason:

<html>
<body>
  <input type="text" name="txtName" />
  <script>
  var textbox = Window.document.getElementById("txtName");
  textbox.value="Hello World";
  </script>
</body>
</html>

The window object itself contains many methods and few of them are as follows:

Event

Description

Syntax

Close

To close current window

window.close();

Open

To open new window

window.open();

Move

To move window to the specified position

window.moveTo();

Resize

To resize window to specified width and height

window.resizeTo();

Navigator

This object provides the information about the browser. It is beneficial when you need to run specific scripts based on the browser version or do something specific to the browser. Let's look into the methods it exposes.

Properties

The properties are described as follows:

  • appCodeName: This returns the code name of the browser

  • appName: This returns the name of the browser

  • appVersion: This returns the version of the browser

  • cookieEnabled: This determines whether cookies are enabled in the browser

  • geoLocation: This gets the location of the user accessing the page

  • language: This returns the language of the browser

  • online: This determines whether the browser is online

  • platform: This returns the platform that the browser has compiled

  • product: This returns the engine name of the browser

  • userAgent: This returns the user agent header sent by the browser to the server

The example code is as follows:

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript">
    function showInformation() {
      var spObj = window.document.getElementById("spInfo");
      spObj.innerHTML =
      "Browser Code Name: " + navigator.appCodeName + "<br>" +
      "Application Name: " + navigator.appName + "<br>" +
      "Application Version: " + navigator.appVersion + "<br>" +
      "Cookie Enabled? " + navigator.cookieEnabled + "<br>" +
      "Language: " + navigator.language + "<br>" +
      "Online: " + navigator.onLine + "<br>" +
      "Platform: " + navigator.platform + "<br>" +
      "Product: " + navigator.product + "<br>" +
      "User Agent: " + navigator.userAgent;
      navigator.geolocation.getCurrentPosition(showPosition);
    }
    function showPosition(position) {
      var spObj = window.document.getElementById("spInfo");
      spObj.innerHTML =  spObj.innerHTML + "<br> Latitude: " + position.coords.latitude +
      "<br>Longitude: " + position.coords.longitude;
    }
  </script>
</head>
<body onload="showInformation();">
  <span id="spInfo"></span>
</body>
</html>

The output is shown as follows:

Screen

Through the screen object, you can get information about the user's screen. This is helpful to know from which screen the user is viewing the content. If it's a mobile browser or standard desktop screen, you can get the size and other information and modify the content as required.

Properties

The properties are described as follows:

  • availHeight : This returns the height of the screen

  • availWidth: This returns the width of the screen

  • colorDepth: This returns the bit depth of the color palette for displaying images

  • height: This returns the total height of the screen

  • pixelDepth: This returns the color resolution (in bits per pixel) of the screen

  • width: This returns the total width of the screen

The example code is as follows:

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript">
    function showInformation() {
      var spObj = window.document.getElementById("spInfo");
      spObj.innerHTML =
      "Available Height: " + screen.availHeight + "<br>" +
      "Available Width: " + screen.availWidth + "<br>" +
      "Height: " + screen.height + "<br>" +
      "Width: " + screen.width + "<br>"
    }
  </script>
</head>
<body onload="showInformation();">
  <span id="spInfo"></span>
</body>
</html>

The output is shown as follows:

History

This contains the URLs that the user visited. You can access it through the window.history object.

You can use this object to navigate to the recently visited links.

Methods

The methods are described as follows:

  • Window.history.back(): This loads the previous URL

  • Window.history.forward(): This loads the recent URL in the history list

  • Window.history.go(): This loads a specific URL available in the history list

Location

The location object gives you information about the current URL. Just like history, it can also be accessed through window.location. There are a few methods and properties you can use to perform specific operations.

Properties

The properties are described as follows:

  • window.location.host: This returns the hostname and port number of the URL

  • window.location.hostname: This returns only the hostname of the URL

  • window.location.href: This provides the complete URL

  • window.location.origin: This returns the hostname, port number, and protocol of the URL

  • window.location.pathname: This returns the pathname of the URL

  • window.location.port: This returns only the port number of the URL

  • window.location.protocol: This returns the protocol of the URL, for example, HTTP or HTTPS

  • window.location.search: This returns the query string of the URL

Methods

The methods are described as follows:

  • window.location.assign(): This loads a new document.

  • window.location.reload(): This reloads the current URL.

  • window.location.replace(): This can be used to replace the current URL with the new one. Replace does not refresh the page, it can only change the URL.

 

Summary


In this chapter, we discussed the basic concepts of JavaScript and how to use it in our web applications. We discussed the core fundamentals of declaring variables and implementing arrays, functions, and data types to start writing programs in JavaScript. In the next chapter, we will discuss some advanced concepts about object-oriented programming and working with closures, scopes, and prototype functions with practical implementation.

About the Author

  • Ovais Mehboob Ahmed Khan

    Ovais Mehboob Ahmed Khan is a seasoned programmer and solution architect with more than 15 years of software development experience. He has worked in different organizations across Pakistan, the USA, and the Middle East. Currently, he is working with Microsoft as a Premier Field Engineer and based in Dubai. He specializes mainly in Application development, Cloud technologies and DevOps. He is a prolific writer and published numerous technical articles on different websites, such as MSDN, TechNet, DZone, and also an author of three other books published by Packt: JavaScript for .NET Developers, Enterprise Application Architecture with .NET Core and C# 7.0 and .NET Core 2.0 High Performance.

    Browse publications by this author

Latest Reviews

(1 reviews total)
Seems to be a good book...