JavaScript for .NET Developers - Ovais Mehboob Ahmed Khan - E-Book

JavaScript for .NET Developers E-Book

Ovais Mehboob Ahmed Khan

0,0
41,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Unlock the potential of evergreen browsers and increase the efficiency of your ASP.NET applications by learning how to write JavaScript

About This Book

  • Boost your skillset and start bringing JavaScript into your web development projects
  • Leverage your existing ASP.NET knowledge to develop dynamic and responsive SPAs
  • Learn effective design patterns for sustainable, and scalable web development

Who This Book Is For

This book is for ASP.NET developers that want to bring JavaScript into their skillset to build applications that are truly dynamic and responsive. It's for developers who are focused on developing for users who want to deliver a great end product and a fantastic experience.

What You Will Learn

  • Get to grips with the basic to advanced concepts of JavaScript
  • Learn how to use JavaScript on server side using Node.js
  • Develop web applications in ASP.NET using JavaScript
  • Get to know with industry-wide best practices and design patterns that provide maintainability and scalability
  • Build an ASP.NET application using Angular 2 with TypeScript and Web API
  • Explore WinJS and see how to use mobile capabilities from web applications
  • Use JavaScript to develop scalable ASP.NET applications
  • See how to test and debug JavaScript

In Detail

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.

Style and approach

This book will build the skillset of every .NET developer, so they can build stronger and more responsive web apps with confidence.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 382

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

JavaScript for .NET Developers
Credits
About the Author
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. JavaScript for Modern Web Applications
Importance of JavaScript
What is JavaScript?
Comparing runtimes
Setting up your environment
New editing experience of JavaScript in Visual Studio 2015 IDE
Programming in JavaScript
Core fundamentals of JavaScript
Adding JavaScript to an HTML page
Statements in JavaScript
Literals and variables
Data types
Array in JavaScript
What is JSON?
Simple objects in JSON
Declaring arrays in JSON
Nesting data in JSON
Conversions in data types
Elements of JavaScript
Constants in JavaScript
Comments
Case sensitivity
Character set
Expressions
The this keyword
Sequence of code execution in JavaScript
Using the this keyword on a calling method
The function statement and expression
Class statement and expression
Grouping operator
new
super
Operators
Assignment operators
Arithmetic operators
Unary operators
Comparison operators
Strict equal operator
Strict not equal operator
Logical operators
Logical AND
Logical OR
Logical NOT
Bitwise operators
Bitwise AND
Bitwise OR
Bitwise NOT
Bitwise XOR
Bitwise shift operators
Bitwise left shift
Bitwise right shift
The typeof operator
The void operator
The delete operator
Miscellaneous operators
Conditional operators
Spread operator
Built-in display methods in JavaScript
Displaying messages
Alert box
Confirm box
Prompt box
Writing on a page
Writing into the browser's console window
Browser Object Models in JavaScript
Window
Document
Navigator
Properties
Screen
Properties
History
Methods
Location
Properties
Methods
Summary
2. Advanced JavaScript Concepts
Variables – scope and hoisting
Declaring let
Conditions where let is efficient to use
Functions in loops
Events in JavaScript
Function arguments
Object-oriented programming in JavaScript
Creating objects
Defining objects using object literal notation
Defining objects using a constructor pattern
Using the class keyword
Properties
Defining properties using object literal notation
Defining properties using a constructor pattern
Defining properties using setters/getters in ECMAScript 6
JavaScript property descriptors
Display property descriptors
Managing property descriptors
Using getters and setters
Methods
Defining methods through object literal notation approach
Defining objects using the constructor function approach
Extending properties and methods
Private and public members
Inheritance
Chaining constructors in JavaScript
Inheritance using Object.create()
Predefined properties of Object.create()
Defining inheritance using class
Encapsulation
Abstraction
new.target
Namespace
Exception handling
Error
RangeError
ReferenceError
SyntaxError
TypeError
URIError
Closures
Practical use
JavaScript typed arrays
Typed array architecture
The array buffer
Creating a buffer
Maps, sets, weak maps, and weak sets
Maps and weak maps
Sets and weak sets
The strict mode
Summary
3. Using jQuery in ASP.NET
Getting started with jQuery
Using a content delivery network
The use of CDN
The document ready event
The jQuery selectors
Selecting the DOM elements using the ID
Selecting the DOM elements using TagName
Selecting nodes by the class name
Selecting by the attribute value
Selecting input elements
Selecting all the elements
Selecting the first and last child elements
The contains selector in jQuery
Selecting the even and odd rows selectors
Manipulating DOM
Modifying an element's properties
Creating new elements
Removing elements and attributes
Event handling in jQuery
Registering events in jQuery
Binding events using on and off
Using the hover events
Summary
4. Ajax Techniques
Introducing Ajax
How Ajax works
Ajax requests using the classic XHR object
XHR methods
XHR events
XHR properties
Making an Ajax request using jQuery
jQuery.ajax()
Ajax properties
Pre-filtering Ajax requests
Setting default values for all future Ajax requests
Loading data through the get functions in jQuery
Using jQuery.get()
Using jQuery.getJSON()
Using jQuery.getScript()
Posting data to server using the post function
Ajax events
Local events
Global events
Cross-origin requests
JSON-P
Using JSON-P
CORS
Specifying the CORS policy at services level
Enable CORS at the Configure method
Calling WCF services from JavaScript
Summary
5. Developing an ASP.NET Application Using Angular 2 and Web API
TypeScript
Compilation architecture of TypeScript
Advantages of TypeScript
Superset of JavaScript
Support for classes and modules
Static type checking
ECMAScript 6 feature support
Optional typing
Declaring types in TypeScript
Core elements of TypeScript
Declaring variables
Types
Classes and interfaces
Defining interfaces
Deriving classes and interfaces
Generic classes
Functions
Generic functions
Iterators
Modules and namespaces
Introduction to Angular 2
Angular 2 architecture
Events of component life cycle
Modules
Components
Core properties of Angular 2 components
Templates and selectors
Inputs and outputs
Using inputs
Using outputs
Directives
Creating a simple Hello World directive
Structural directives
Attribute directive
Providers
Dependency injection in Angular
Routing in Angular
Developing a to-do application in ASP.NET Core
Creating a Common project
Creating a TodoServiceApp project
Enabling MVC in a Web API project
Installing Entity Framework
Adding AppSettings to store a connection string
Configuring AppSettings in the Startup class
Adding data access in Web API
Enabling CORS in the ASP.NET Web API
Running database migration
Creating a controller
Creating a TodoWebApp project
Configuring Angular 2 in the TodoWebApp project
Dependencies
Development dependencies
Configuring TypeScript
Configuring Gulp
Adding Angular components
Adding the to-do service component
Adding a to-do view component
Creating the main to-do page
Creating a custom to-do tag helper
Adding a to-do MVC controller
Generating views for the TodoController action methods
Developing the Create Todo component
Summary
6. Exploring the WinJS Library
Introduction to WinJS
WinJS features
JavaScript coding and language patterns
Stylesheets
Windows runtime access
Security
App model
Databinding
Controls
Utilities
Usage of WinJS
Adding the WinJS library in the ASP.NET application
CDN
NPM
NuGet
Getting started with WinJS
Using WinJS in the ASP.NET application
Existing Windows app template in Visual Studio
Exploring WinJS core fundamentals
Classes and namespaces
Defining classes in WinJS
Deriving classes in WinJS
Namespaces in WinJS
Mixin
Events in WinJS
Databinding
One time databinding
One way databinding
Two way databinding
A databinding working model
Promises
Other operations of promises
Chaining promises and handling errors
Canceling promises
Joining promises
Checking promise
Wrapping non-promise into promise
Exploring WinJS controls and styles
Adding WinJS controls
Setting properties of WinJS controls
Using Windows runtime features
Hosted apps and accessing the camera
Creating the ASP.NET core application
Converting an ASP.NET application into Windows application using the Hosted app concept
Summary
7. JavaScript Design Patterns
Creational patterns
Singleton design pattern
Factory pattern
Abstract factory pattern
Prototype pattern
Structural patterns
Adapter pattern
Decorator pattern
Facade pattern
Bridge pattern
Behavioral pattern
Chain of responsibility pattern
Observer pattern
Pub/sub pattern
Promises
Summary
8. Node.js for ASP.NET Developers
Introduction to Node.js
Request processing by the Node.js web server
Comparison of Node.js with .NET
NPM
Installing Node.js
Using Node.js with Visual Studio 2015
Simple console application using Node.js
Web applications with Node.js
Creating blank Node.js applications
Using the Express framework for web applications in Node.js
Extend simple Node.js to use Express
Express view engines
EJS view engine
Jade view engine
Routing in the Express application
Middleware
MVC with the Express framework
MVC pattern
Creating a controller
Creating data services
Accessing the Microsoft SQL server in Node.js
Reading a record from the Microsoft SQL server database
Creating a record in the Microsoft SQL server database
Summary
9. Using JavaScript for Large-Scale Projects
Think before proceeding
Developing highly scalable and maintainable applications
Modularization
Implementing the module pattern
Modularizing JavaScript code through RequireJS
Creating modules using the RequireJS API
Bootstrapping RequireJS
Event-driven messaging
Implementing mediator pattern for communication between modules
Encapsulating complex code
Generating documentation
Installing JSDoc3 in ASP.NET Core
Adding comments
Deployment optimization
Summary
10. Testing and Debugging JavaScript
Testing the JavaScript code
Unit testing
Writing unit tests
Jasmine
Karma
Grunt
Developing unit test using Jasmine, Karma, and Grunt
Adding packages
Adding the Grunt file
Adding Karma specifications
Load npm task
Register task
Source JavaScript file
Adding unit test script file
Running test task
Implementing Model-View-ViewModel using Knockout and Run test
Adding the Knockout package
Adding ProductViewModel
Add the Product view
Modifying test configuration
Modifying the product-testing script
Debugging JavaScript
Debugging options in Visual Studio 2015
Debugging from Visual Studio with Internet Explorer
Debugging from Visual Studio with Google Chrome
Developer Tools
Debugging options in Microsoft Edge
Standard breakpoints
Conditional breakpoints
Tracepoints
Event
Add event tracepoint
Add event breakpoints
XHR
Debugging TypeScript
Debugger keyword supported by all browsers
Summary
Index

JavaScript for .NET Developers

JavaScript for .NET Developers

Copyright © 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: July 2016

Production reference: 1260716

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78588-646-1

www.packtpub.com

Credits

Author

Ovais Mehboob Ahmed Khan

Reviewer

Nicholas Suter

Commissioning Editor

Edward Gordon

Acquisition Editor

Nitin Dasan

Content Development Editor

Deepti Thore

Technical Editors

Pranil Pathare

Deepti Tuscano

Copy Editor

Vibha Shukla

Project Coordinator

Shweta H Birwatkar

Proofreader

Safis Editing

Indexer

Mariammal Chettiyar

Graphics

Disha Haria

Production Coordinator

Nilesh Mohite

Cover Work

Nilesh Mohite

About the Author

Ovais Mehboob Ahmed Khan is a seasoned programmer and solution architect with more than 13 years of software development experience. He has worked in different organizations across Pakistan, the USA, and the Middle East. Currently, he is working for a government entity based in Dubai, and also provides consultancy services to a Microsoft gold partner firm based in New Jersey.

He is a Microsoft MVP in Visual Studio and Development Technologies and specializes mainly in Microsoft .NET and web development. He has authored numerous technical articles on different websites such as MSDN, TechNet, DZone, and personal blog at http://ovaismehboob.wordpress.com.

He is an active speaker and group leader of Microsoft Developers UAE Meetup, Microsoft Technology Practices, and Developers and Enterprise Practices user groups, and has presented various technical sessions in different events and conferences.

In short, Ovais is a passionate developer who is always interested in learning new technologies. He can be reached at <[email protected]> and on Twitter, @ovaismehboob.

I would like to thank my family for supporting. Especially my mother, wife, and brother, who have always encouraged me in every goal of my life. My father, may he rest in peace, would have been proud of my achievements.

About the Reviewer

Nicholas Suter is a .NET software craftsman, focused on patterns, practices, and quality development in a Microsoft environment. He has been nominated for Microsoft .NET MVP since 2014.

He works for Cellenza, a French agile consulting company based in Paris, where he leads, trains, and audits teams more on technical matters than team practices.

He wrote a book in 2013 on web development called Visual Studio 2013, Concevoir et développer des projets Web, les gérer avec TFS 2013, (French) for ENI Editions, and reviewed Entity Framework Tutorial, Second Edition, for Packt Publishing in 2015.

www.PacktPub.com

eBooks, discount offers, and more

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Preface

This is a book about the JavaScript programming language, and is targeted at .NET developers who want to develop responsive web applications using popular client-side JavaScript-based frameworks and create a rich user experience. It is also intended for programmers who have a basic knowledge of the JavaScript programming language and wanted to learn some core and advanced concepts followed by some industry-wide best practices and patterns to structure and design web applications.

This book starts with the basics of JavaScript and helps the reader to gain knowledge about the core concepts and then proceeds towards some advanced topics. There is a chapter that primarily focuses on the jQuery library, which is widely used throughout web application development, followed by a chapter on Ajax techniques that help developers to understand how asynchronous requests can be made. This is followed by the options to make requests either through the plain vanilla JavaScript XHR object or through the jQuery library. There is also a chapter that develops a complete application using Angular 2 and ASP.NET Core, and introduces TypeScript, a superset of JavaScript that supports the latest and evolving features of ECMAScript 2015. We will also explore the Windows JavaScript (WinJS) library to develop Windows applications using JavaScript and HTML and use this library to bring Windows behavior, look, and feel to ASP.NET web applications. There is a complete chapter on Node.js that helps developers to learn how powerful the JavaScript language is on the server side, followed by a chapter on using JavaScript in a large-scale project. Finally, this book will end with a chapter about testing and debugging and discuss what testing suites and debugging techniques are there to troubleshoot and make an application robust.

This book has some very dense topics that require full concentration, hence is ideal for someone having some prior knowledge. All the chapters are related to JavaScript and work around JavaScript frameworks and libraries to build rich web applications. With this book, the reader will get the end-to-end knowledge about the JavaScript language and its frameworks and libraries built on top of it, followed by the techniques to test and troubleshoot the JavaScript code.

What this book covers

Chapter 1, JavaScript for Modern Web Applications, focuses on the basic concepts of JavaScript that involve declaration of variables, datatypes, implementing arrays, expressions, operators, and functions. We will write simple programs in JavaScript using Visual Studio 2015, and see what this IDE offers for writing JavaScript programs. We will also study how JavaScript code can be written and compare the .NET runtime with the JavaScript runtime to clarify the execution cycle of code-compilation process.

Chapter 2, Advanced JavaScript Concepts, covers the advanced concepts of JavaScript and gives developers an insight into the JavaScript language. It will show the extent to which the JavaScript language can be used as far as features are concerned. We will discuss variables hoisting and their scope, property descriptors, object-oriented programming, closures, typed arrays, and exception handling.

Chapter 3, Using jQuery in ASP.NET, discusses jQuery and how to use it in web applications developed in ASP.NET Core. We will discuss the options jQuery provides and the advantages it has when comparing it with the plain vanilla JavaScript for manipulating DOM elements, attaching events, and performing complex operations.

Chapter 4, Ajax Techniques, discusses the techniques of making asynchronous requests known as Ajax requests. We will explore the core concepts of using the XMLHttpRequest (XHR) object and study the basic architecture of how Ajax request is processed and the events and methods it provides. On the other hand, we will also explore what the jQuery library provides in comparison with the plain XHR object.

Chapter 5, Developing an ASP.NET Application Using Angular 2 and Web API, teaches the basic concepts of TypeScript and uses it with Angular 2. We will develop a simple application in ASP.NET Core using Angular 2 as a frontend client-side framework, Web API for backend services, and Entity Framework Core for database persistence. At the time of writing, Angular 2 was in a beta version, and we have used the beta version in this chapter. With the future releases of Angular 2, there are chances of having some changes in the framework, but the basic concepts will almost be the same. For future updates, you can refer to http://angular.io/.

Chapter 6, Exploring the WinJS Library, explores the Microsoft developed WinJS library, which is a JavaScript library to not only develop Windows applications using JavaScript and HTML, but also use it with ASP.NET and other web frameworks. We will discuss the core concepts of defining classes, namespaces, deriving classes, mixins, and promises. We will also look into the data-binding techniques and how to use Windows controls or specific attributes in HTML elements to change the behaviour, look, and feel of the control. Moreover, we will end up using the WinRT API to access a device's camera in our web application and discuss the concepts of a Hosted app through which any web application can be transformed into a Windows application using a Universal Window template in Visual Studio 2015.

Chapter 7, JavaScript Design Patterns, shows that design patterns provide efficient solutions to software design. We will discuss some of the industry-wide best design patterns spread into creational, structural, and behavioral categories. Each category will be covering four types of design patterns that can be used and implemented using JavaScript to solve a particular design problem.

Chapter 8, Node.js for ASP.NET Developers, focuses on the basics of Node.js and how to use it to develop server-side applications using JavaScript. In this chapter, we will discuss view engines such as EJS and Jade and the use of controllers and services to implement the MVC pattern. Moreover, we will end this chapter by performing some examples of accessing a Microsoft SQL Server database to perform, create, and retrieve operations on a database.

Chapter 9, Using JavaScript for Large-Scale Projects, provides best practices of using JavaScript for large-scale applications. We will discuss how to structure our JavaScript-based projects by splitting them into modules to increase the scalability and maintainability. We will see how effectively we can use the Mediator pattern to provide communication between modules and the documentation frameworks that increase the maintainability of your JavaScript code. Finally, we will discuss how the application can be optimized by compressing and merging JavaScript files into a minified version and increase performance.

Chapter 10, Testing and Debugging JavaScript, focuses on the testing and debugging JavaScript applications. We will discuss one of the most popular testing suites of JavaScript code known as Jasmine, and use it with Karma to run the test cases. For debugging, we will discuss some tips and techniques to debug JavaScript with Visual Studio and what Microsoft Edge offers to make debugging easy. In the end, we will study the basic concepts of how Microsoft Edge enables debugging for TypeScript files and the configuration needed to achieve it.

What you need for this book

Throughout the book, we will be using Visual Studio 2015 to practice examples. For the server-side technology, we have used ASP.NET Core for web application development, and used JavaScript on top of it. In Chapter 8, Node.js for ASP.NET Developers, we used Node.js to show how JavaScript can be used on the server side. For Node.js, we will require some extensions for Visual Studio 2015 to be installed, and the details are specified in the chapter.

Who this book is for

This book is targeted at .NET developers who have solid programming experience in ASP.NET Core. Throughout this book, we have used ASP.NET Core for web development and assumed that developers have thorough knowledge or working experience in .NET Core and ASP.NET Core.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "JavaScript can be placed in the <head> or <body> sections of your HTML page."

A block of code is set as follows:

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

Any command-line input or output is written as follows:

dotnet ef database update –verbose

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "When the page loads, it will show the pop-up message and a text as This is a simple text."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

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!

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/JavaScriptForNETDevelopers_ColorImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

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: