Saturday, December 16, 2017

Maven For Beginners

Maven is a powerful build tool for Java software projects. Actually, you can build software projects using other languages too, but Maven is developed in Java, and is thus historically used more for Java projects.

What is a Build Tool?

A build tool is a tool that automates everything related to building the software project. Building a software project typically includes one or more of these activities:
  • Generating source code (if auto-generated code is used in the project).
  • Generating documentation from the source code.
  • Compiling source code.
  • Packaging compiled code into JAR files or ZIP files.
  • Installing the packaged code on a server, in a repository or somewhere else.

Installing Maven

To install Maven on your own system (computer), go to the Maven download page and follow the instructions there. In summary, what you need to do is:
  1. Set the JAVA_HOME environment variable to point to a valid Java SDK (e.g. Java 8).
  2. Download and unzip Maven.
  3. Set the M2_HOME environment variable to point to the directory you unzipped Maven to.
  4. Set the M2 environment variable to point to M2_HOME/bin (%M2_HOME%\bin on Windows, $M2_HOME/bin on unix).
  5. Add M2 to the PATH environment variable (%M2% on Windows, $M2 on unix).
  6. Open a command prompt and type 'mvn -version' (without quotes) and press enter.
After typing in the mvn -version command you should be able to see Maven execute, and the version number of Maven written out to the command prompt.

Maven Overview - Core Concepts

Maven is centered around the concept of POM files (Project Object Model). A POM file is an XML representation of project resources like source code, test code, dependencies (external JARs used) etc. The POM contains references to all of these resources. The POM file should be located in the root directory of the project it belongs to.
Here is a diagram illustrating how Maven uses the POM file, and what the POM file primarily contains:
Overview of Maven core concepts.
Overview of Maven core concepts.

These concepts are explained briefly below to give you an overview, and then in more detail in their own sections later in this tutorial.




POM Files
When you execute a Maven command you give Maven a POM file to execute the commands on. Maven will then execute the command on the resources described in the POM.

Build Life Cycles, Phases and Goals
The build process in Maven is split up into build life cycles, phases and goals. A build life cycle consists of a sequence of build phases, and each build phase consists of a sequence of goals. When you run Maven you pass a command to Maven. This command is the name of a build life cycle, phase or goal. If a life cycle is requested executed, all build phases in that life cycle are executed. If a build phase is requested executed, all build phases before it in the pre-defined sequence of build phases are executed too.

Dependencies and Repositories
One of the first goals Maven executes is to check the dependencies needed by your project. Dependencies are external JAR files (Java libraries) that your project uses. If the dependencies are not found in the local Maven repository, Maven downloads them from a central Maven repository and puts them in your local repository. The local repository is just a directory on your computer's hard disk. You can specify where the local repository should be located if you want to (I do). You can also specify which remote repository to use for downloading dependencies. All this will be explained in more detail later in this tutorial.

Build Plugins
Build plugins are used to insert extra goals into a build phase. If you need to perform a set of actions for your project which are not covered by the standard Maven build phases and goals, you can add a plugin to the POM file. Maven has some standard plugins you can use, and you can also implement your own in Java if you need to.

Build Profiles
Build profiles are used if you need to build your project in different ways. For instance, you may need to build your project for your local computer, for development and test. And you may need to build it for deployment on your production environment. These two builds may be different. To enable different builds you can add different build profiles to your POM files. When executing Maven you can tell which build profile to use.

Maven POM Files

A Maven POM file (Project Object Model) is an XML file that describe the resources of the project. This includes the directories where the source code, test source etc. is located in, what external dependencies (JAR files) your projects has etc.
Here is a minimal POM file:
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                      http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.jenkov</groupId>
    <artifactId>java-web-crawler</artifactId>
    <version>1.0.0</version>
</project>

The above groupIdartifactId and version elements would result in a JAR file being built and put into the local Maven repository at the following path (directory and file name):
MAVEN_REPO/com/jenkov/java-web-crawler/1.0.0/java-web-crawler-1.0.0.jar

Effective POM

With all this POM inheritance it may be hard to know what the total POM file looks like when Maven executes. The total POM file (result of all inheritance) is called the effective POM. You can get Maven to show you the effective POM using this command:
mvn help:effective-pom

Maven Settings File

Maven has two settings files. In the settings files you can configure settings for Maven across all Maven POM files. For instance, you can configure:
  • Location of local repository
  • Active build profile
  • Etc.
The settings files are called settings.xml. The two settings files are located at:
  • The Maven installation directory: $M2_HOME/conf/settings.xml
  • The user's home directory: ${user.home}/.m2/settings.xml
Both files are optional. If both files are present, the values in the user home settings file overrides the values in the Maven installation settings file.

Running Maven

When you have installed Maven and have created a POM file and put the POM file in the root directory of your project, you can run Maven on your project.
Running Maven is done by executing the mvn command from a command prompt. When executing the mvn command you pass the name of a build life cycle, phase or goal to it, which Maven then executes. Here is an example:
mvn install
This command executes the build phase called install (part of the default build life cycle), which builds the project and copies the packaged JAR file into the local Maven repository. Actually, this command executes all build phases before install in the build phase sequence, before executing the install build phase.
You can execute multiple build life cycles or phases by passing more than one argument to the mvncommand. Here is an example:
 mvn clean install
This command first executes the clean build life cycle, which removes compiled classes from the Maven output directory, and then it executes the install build phase.
You can also execute a Maven goal (a subpart of a build phase) by passing the build phase and goal name concatenated with a : in between, as parameter to the Maven command. Here is an example:
mvn dependency:copy-dependencies
This command executes the copy-dependencies goal of the dependency build phase.

Maven Directory Structure

Maven has a standard directory structure. If you follow that directory structure for your project, you do not need to specify the directories of your source code, test code etc. in your POM file.
Here are the most important directories:
- src
  - main
    - java
    - resources
    - webapp
  - test
    - java
    - resources

- target

Project Dependencies

You specify your project dependencies inside the dependencies element in the POM file. Here is an example:
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.jenkov.crawler</groupId>
    <artifactId>java-web-crawler</artifactId>
    <version>1.0.0</version>
    
      <dependencies>

        <dependency>
          <groupId>org.jsoup</groupId>
          <artifactId>jsoup</artifactId>
          <version>1.7.1</version>
        </dependency>

        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.8.1</version>
          <scope>test</scope>
        </dependency>

      </dependencies>
    

    <build>
    </build>

</project>

Snapshot Dependencies

Snapshot dependencies are dependencies (JAR files) which are under development. Instead of constantly updating the version numbers to get the latest version, you can depend on a snapshot version of the project. Snapshot versions are always downloaded into your local repository for every build, even if a matching snapshot version is already located in your local repository. Always downloading the snapshot dependencies assures that you always have the latest version in your local repository, for every build.
You can tell Maven that your project is a snapshot version simply by appending -SNAPSHOT to the version number in the beginning of the POM (where you also set the groupId and artifactId). Here is a versionelement example:
<version>1.0-SNAPSHOT</version>

Maven Repositories

Maven repositories are directories of packaged JAR files with extra meta data. The meta data are POM files describing the projects each packaged JAR file belongs to, including what external dependencies each packaged JAR has. It is this meta data that enables Maven to download dependencies of your dependencies recursively, until the whole tree of dependencies is download and put into your local repository.
Maven repositories are covered in more detail in the Maven Introduction to Repositories, but here is a quick overview.
Maven has three types of repository:
  • Local repository
  • Central repository
  • Remote repository
Maven searches these repositories for dependencies in the above sequence. First in the local repository, then in the central repository, and third in remote repositories if specified in the POM.
Here is a diagram illustrating the three repository types and their location:
Maven Repository Types and Location.
Maven Repository Types and Location.

Maven Build Life Cycles, Phases and Goals

When Maven builds a software project it follows a build life cycle. The build life cycle is divided into build phases, and the build phases are divided into build goals. Maven build life cycles, build phases and goals are described in more detail in the Maven Introduction to Build Phases, but here I will give you a quick overview.

Build Life Cycles
Maven has 3 built-in build life cycles. These are:
  1. default
  2. clean
  3. site
Build Phases
Each build life cycle is divided into a sequence of build phases, and the build phases are again subdivided into goals. Thus, the total build process is a sequence of build life cycle(s), build phases and goals.
Build PhaseDescription
validateValidates that the project is correct and all necessary information is available. This also makes sure the dependencies are downloaded.
compileCompiles the source code of the project.
testRuns the tests against the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed.
packagePacks the compiled code in its distributable format, such as a JAR.
installInstall the package into the local repository, for use as a dependency in other projects locally.
deployCopies the final package to the remote repository for sharing with other developers and projects.

Build Goals
Build goals are the finest steps in the Maven build process. A goal can be bound to one or more build phases, or to none at all. If a goal is not bound to any build phase, you can only execute it by passing the goals name to the mvn command. If a goal is bound to multiple build phases, that goal will get executed during each of the build phases it is bound to.

Maven Build Profiles

Maven build profiles enable you to build your project using different configurations. Instead of creating two separate POM files, you can just specify a profile with the different build configuration, and build your project with this build profile when needed.
You can read the full story about build profiles in the Maven POM reference under Profiles. Here I will give you a quick overview though.
Maven build profiles are specified inside the POM file, inside the profiles element. Each build profile is nested inside a profile element. Here is an example:
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.jenkov.crawler</groupId>
  <artifactId>java-web-crawler</artifactId>
  <version>1.0.0</version>

  <profiles>
      <profile>
          <id>test</id>
          <activation>...</activation>
          <build>...</build>
          <modules>...</modules>
          <repositories>...</repositories>
          <pluginRepositories>...</pluginRepositories>
          <dependencies>...</dependencies>
          <reporting>...</reporting>
          <dependencyManagement>...</dependencyManagement>
          <distributionManagement>...</distributionManagement>
      </profile>
  </profiles>

</project>

A build profile describes what changes should be made to the POM file when executing under that build profile. This could be changing the applications configuration file to use etc. The elements inside the profile element will override the values of the elements with the same name further up in the POM.
Inside the profile element you can see a activation element. This element describes the condition that triggers this build profile to be used. One way to choose what profile is being executed is in the settings.xml file. There you can set the active profile. Another way is to add -P profile-name to the Maven command line.

Maven Plugins

Maven plugins enable you to add your own actions to the build process. You do so by creating a simple Java class that extends a special Maven class, and then create a POM for the project. The plugin should be located in its own project.

Maven" is really just a core framework for a collection of Maven Plugins. In other words, plugins are where much of the real action is performed, plugins are used to: create jar files, create war files, compile code, unit test code, create project documentation, and on and on. Almost any action that you can think of performing on a project is implemented as a Maven plugin.
Plugins are the central feature of Maven that allow for the reuse of common build logic across multiple projects. They do this by executing an "action" (i.e. creating a WAR file or compiling unit tests) in the context of a project's description - the Project Object Model (POM). Plugin behavior can be customized through a set of unique parameters which are exposed by a description of each plugin goal (or Mojo).
One of the simplest plugins in Maven is the Clean Plugin. The Maven Clean plugin (maven-clean-plugin) is responsible for removing the target directory of a Maven project. When you run "mvn clean", Maven executes the "clean" goal as defined in the Clean plug-in, and the target directory is removed. The Clean plugin defines a parameter which can be used to customize plugin behavior, this parameter is called outputDirectory and it defaults to ${project.build.directory}.

What is a Mojo ?

A Mojo is really just a goal in Maven, and plug-ins consist of any number of goals (Mojos). Mojos can be defined as annotated Java classes or Beanshell script. A Mojo specifies metadata about a goal: a goal name, which phase of the lifecycle it fits into, and the parameters it is expecting.
Mojo term was introduced in Maven 2 as a complete rework on how to write plugins (see below for more details on Maven 1.x plugins comparison).
MOJO is a play on POJO (Plain-old-Java-object), substituting "Maven" for "Plain".

Custom Plugin can be created with the help of MOJO.


Saturday, October 28, 2017

what's use of "$" in Javascript

I found this interesting story about "$". Hence sharing this information as separate blog.
There is nothing inherently special about '$'. It is a variable name just like any other. In earlier days, people used to write code using document.getElementById. Because JavaScript is case-sensitive, it was normal to make mistake while writing document.getElementById. Should I capital 'b' of 'by'? Should I capital 'i' of Id? You get the drift. Because functions are first class citizens in JavaScript, you can always do this
var $ = document.getElementById; //freedom from document.getElementById!
[EDIT: Looks like in Firefox 3 and Google Chrome, you can't make alias so easily. In IE6 and Firefox2, above technique still works.]
When Prototype library arrived, they named their function, which gets the DOM elements, as '$' to save on typing/readability [When writing JS code, most of the time you start with selecting some DOM elements]. Almost all the JavaScript libraries copied this idea. Prototype also introduced $$ function to select elements using CSS selector.
jQuery not only adapted the '$ function', but expanded to make it accept all kind of 'selectors' to get the elements you want. Now, if you are already using Prototype in your project and wanted to include jQuery, you will be in problem as '$' could either refer to Prototype's implementation OR jQuery's implementation. That's why jQuery has the option of noConflict so that you can include jQuery in your project which uses Prototype and slowly migrate your code. I think this was a brilliant move on John's part! :)

Monday, August 14, 2017

API Driven Development

What is API Driven Development

Simply stated, API driven development involves development where API is the central component. In other words, all development revolves around the API and how it aids in the development process. Essentially, you build an API and then build an application on top of it. And given that APIs provide the building blocks for applications, it makes sense.

All development is API development
Today’s software is built as services. Rather than using web frameworks that invoke services and produce web pages, today's applications are built by consuming and producing APIs. Applications have embraced APIs on the front end for connecting to rich clients; on the backend for integrating with internal systems; on the sides for enabling other applications to access their internal data and processes; and within, as applications are composed of a set of component services, linked together with APIs.
The majority of enterprise software development efforts are focused on building web applications using web frameworks. Java Enterprise Edition, Microsoft .NET, Ruby-on-Rails, PHP, and a variety of other technologies are used to implement web applications using model-view-controller (MVC) design patterns and page template technologies. For a decade, starting in the late 1990s, an entire generation of developers has spent the majority of its time building applications in this model.

APIs open enterprise applications

Integration architectures assume that applications are developed without considering whether to enable other applications to access their internal data and processes. Before the conventions of APIs were widely adopted, this was a prudent strategy. Trying to support application-to-application integration was an undue burden for the developer and was usually left as a project for another team.
The widespread adoption of the basic conventions of API design—RESTful design, JSON-based data, simple versioning, and key-based access control—means that developers can easily build APIs into their applications and support their usage without undue distraction from their central mission of application delivery. And because application delivery already requires an API-centric architecture to enable rich HTML5/JavaScript and mobile clients, APIs will be essential elements of the project scope.
The result: when the time comes for application-to-application integration, the need for separate integration middleware is obviated.

Rather than using web frameworks that invoke services and produce web pages, applications today are built by consuming and producing APIs.
We saw how applications have embraced APIs on the front end for connecting to rich clients; on the backend for integrating with internal systems; and on the sides for enabling other applications to access their internal data and processes.
Resilient and scalable cloud deployment for componentized applications
Modern Java applications are heavily componentized. Using frameworks like Spring or Java CDI, applications are assembled from a set of service components wired together at runtime. The advantages are:
  •  
    complicated applications can be broken down into components that can be developed by disparate teams
  •  
    applications can leverage and reuse existing components
  •  
    components are interconnected without fragile, complex dependencies or tightly-coupled linkages.

Decomposed services and polyglot enterprise development

Rather than leveraging the more complicated traditional enterprise mechanisms (whether the legacy RPC approaches of CORBA and RMI or the cumbersome web services protocols such as SOAP), many developers are finding that the same lightweight API services that have proven to be resilient, scalable, and agile for front-end, back-end, and application-to-application scenarios can also be leveraged for application assembly. This is the essence of the micro services architecture.


Monday, July 10, 2017

Web Services : JAX RS and JAX WS

SOAP
Simple Object Access Protocol (SOAP) is a standard protocol specification for message exchange based on XML. Communication between the web service and client happens using XML messages.

A simple web service architecture have two components
  • Client 
  • Service provider 


In order to communicate client must know some information for e.g.
  • Location of webservices server 
  • Functions available,signature and return types of function. 
  • Communication protocol 
  • Input output formats 

Service provider will create a standard XML file which will have all above information.So If this file is given to client then client will be able to access web service. This XML file is called WSDL.


What is WSDL?

WSDL stands for Web Service Description Language. It is an XML file that describes the technical details of how to implement a web service, more specifically the URI, port, method names, arguments, and data types. Since WSDL is XML, it is both human-readable and machine-consumable, which aids in the ability to call and bind to services dynamically.using this WSDL file we can understand things like,
  • Port / Endpoint – URL of the web service 
  • Input message format 
  • Output message format 
  • Security protocol that needs to be followed 
  • Which protocol the web service uses 
  • Ways to access web service:


There are two ways to access web service.
1. If Service provider knows client:If service provider knows its client then it will provide its wsdl to client and client will be able to access web service.





2. Service provider register its WSDL to UDDI and client can access it from UDDI:UDDI stands for Universal Description, Discovery and Integration.It is a directory service. Web services can register with a UDDI and make themselves available through it for discovery.So following steps are involved. 
  • Service provider registers with UDDI.
  • Client searches for service in UDDI.
  • UDDI returns all service providers offering that service.
  • Client chooses service provider
  • UDDI returns WSDL of chosen service provider.
  • Using WSDL of service provider,client accesses web service.






All details related to webservices available here:

http://docs.oracle.com/cd/E40938_01/doc.74/e40142/dev_secure_web_srvcs.htm
http://www.journaldev.com/9193/web-services-interview-questions-soap-restful#types-of-web-services


Note-:


What is the use of Accept and Content-Type Headers in HTTP Request?
These are important headers in Restful web services. Accept headers tells web service what kind of response client is accepting, so if a web service is capable of sending response in XML and JSON format and client sends Accept header as “application/xml” then XML response will be sent. For Accept header “application/json”, server will send the JSON response. Content-Type header is used to tell server what is the format of data being sent in the request. If Content-Type header is “application/xml” then server will try to parse it as XML data. This header is useful in HTTP Post and Put requests.



JAX RS


Java API for RESTful Web Services (JAX-RS) is the Java API for creating REST web services. JAX-RS uses annotations to simplify the development and deployment of web services. JAX-RS is part of JDK, so you don’t need to include anything to use it’s annotations.


There are two major implementations of JAX-RS API-:

1. Jersey: Jersey is the reference implementation provided by Sun. For using Jersey as our JAX-RS implementation, all we need to configure its servlet in web.xml and add required dependencies. Note that JAX-RS API is part of JDK not Jersey, so we have to add its dependency jars in our application.

2. RESTEasy: RESTEasy is the JBoss project that provides JAX-RS implementation.

In the web services terms, REpresentational State Transfer (REST) is a stateless client-server architecture in which the web services are viewed as resources and can be identified by their URIs. Web service clients that want to use these resources access via globally defined set of remote methods that describe the action to be performed on the resource.

It consists of two components, REST server which provides access to the resources and a REST client which accesses and modify the REST resources.

In the REST architecture style, clients and servers exchange representations of resources by using a standardized interface and protocol. REST isn't protocol specific, but when people talk about REST they usually mean REST over HTTP.

The response from server is considered as the representation of the resources. This representation can be generated from one resource or more number of resources.




Representational State Transfer refers to transferring "representations". You are using a "representation" of a resource to transfer resource state which lives on the server into application state on the client.




Why called rest?


A RESTful web service (also called a RESTful web API) is a web service implemented using HTTP and the principles of REST. It is a collection of resources, with four defined aspects:
  • the base URI for the web service, such as http://example.com/resources/
  • the Internet media type of the data supported by the web service. This is often XML but can be any other valid Internet media type providing that it is a valid hypertext standard.
  • the set of operations supported by the web service using HTTP methods (e.g., GET, PUT, POST, or DELETE).
  • The API must be hypertext driven

 <servlet>
    <servlet-name>RESTful Jersey CRUD Service</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>com.javapapers.webservices.rest.jersey</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>RESTful Jersey CRUD Service</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
In short, JAX RS has to declare resource in particular format and then client can access it using set pattern.

Basic Annotations:
@Path, @Pathparam,@GET, @PUT, @POST, @Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)


Two best resource for JAX RS-:

http://javapapers.com/web-service/restful-services-crud-with-java-jax-rs-jersey/
http://www.mkyong.com/tutorials/jax-rs-tutorials/


Security in WEB services
During the past few years, the technology industry has been working on various XML-based security schemes to provide comprehensive and unified security schemes for Web services. These schemes include:
  • XML digital signature 
  • XML Encryption 
  • XKMS (XML Key Management Specification) 
  • XACML (Extensible Access Control Markup Language) 
  • SAML (Secure Assertion Markup Language) 
  • WS-Security (Web Services Security) 
  • ebXML Message Service 
  • The Liberty Alliance Project 
for secuirty topics;
http://www.javaworld.com/article/2073287/soa/secure-web-services.html
http://javaranch.com/journal/200603/WSSecurity.html


SOAP vs REST web services

Parameter
SOAP
REST
Acronym
SOAP stands for simple object access protocol
REST stands for REpresentational State Transfer
Protocol vs Architectural style
 SOAP is a standard protocol to create web services
Rest is architectural style to create web services.
Contract
Client and Server are bind with WSDL contract
There is no contract between client and Server.
Format Support
SOAP supports only XML format
REST web services supports XML, json and plain text etc.
Maintainability
SOAP web services are hard to maintain as if we do any changes in WSDL , we need to create client stub again
REST web services are generally easy to maintain.
Service interfaces vs URI
SOAP uses Service interfaces to expose business logic
Rest uses URI to expose business logic
Security
SOAP has its own security : WS-security
Rest inherits its security from underlying transport layer.
Bandwidth
SOAP requires more bandwidth and resources as it uses XML messages to exchange information
REST requires less bandwith and resources. It can use JSON also.
Learning curve
SOAP web services are hard to learn as you need to understand WSDL , client stub
REST web services are easy to understand as you need to annotate plain java class with JAX-RS annotations to use various HTTP methods.

When to use JAX WS and JAX RS
  • JAX-WS is meant for XML based web services such as SOAP. JAX-RS does not have the same restriction.
  • JAX-WS is generally geared towards server to server interactions with well defined contracts (WSDLs) and usually when the service and client side are from separate groups. It is very resource intensive so it isn't feasible for client-to-server interactions where the network or client device capability is less than optimal.
  • JAX-RS is geared towards client to server interactions, although server-to-server is okay. As it has little service obligations, it can be tuned to whatever the client needs are.
  • However, using RESTful service APIs is akin to doing meta-programming like Ruby and Python which delays problems to run-time as there is no defined schema agreed and technically enforced upon by the two sides. As such I don't recommend RESTful services everywhere, but I would recommend it if I had control of the two sides which normally happens when you do build a web application that uses static HTML/CSS/JS and talks with a RESTful server for the data.

Other link:

Friday, June 30, 2017

Javascript Introduction

JavaScript Can Change HTML Content

JavaScript Can Change HTML AttributesJavaScript Can Change HTML Styles (CSS)

<script> 

In HTML, JavaScript code must be inserted between <script> and </script> tags.

<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>

JavaScript in <head> or <body>

You can place any number of scripts in an HTML document. Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.

External JavaScript

<script src="myScript.js"></script>

NOTE-:External scripts cannot contain <script> tags.


JavaScript Display Possibilities


JavaScript can "display" data in different ways:

  • Writing into an HTML element, using innerHTML.
  • Writing into the HTML output using document.write().
  • Writing into an alert box, using window.alert().
  • Writing into the browser console, using console.log().

JavaScript Programs

  • A computer program is a list of "instructions" to be "executed" by the computer.
  • In a programming language, these program instructions are called statements.
  • JavaScript is a programming language.
  • JavaScript statements are separated by semicolons(Ending statements with semicolon is not required, but highly recommended.).
  • Most JavaScript programs contain many JavaScript statements.
  • The statements are executed, one by one, in the same order as they are written.
  • JavaScript ignores multiple spaces. You can add white space to your script to make it more readable.

JavaScript Statements

JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.

JavaScript is Case Sensitive

All JavaScript identifiers are case sensitive

JavaScript Type Operators

typeof   -> Returns the type of a variable
instanceof -> Returns true if an object is an instance of an object type

JavaScript Data Types

JavaScript variables can hold many data types: numbers, strings, objects and more:
var length = 16;                               // Numbervar lastName = "Johnson";                      // Stringvar x = {firstName:"John", lastName:"Doe"};    // Object


JavaScript Objects

JavaScript objects are written with curly braces.
Object properties are written as name:value pairs, separated by commas.

Example

var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

Undefined

In JavaScript, a variable without a value, has the value undefined. The typeof is also undefined.

Example

var person;                // Value is undefined, type is undefined

Null

In JavaScript null is "nothing". It is supposed to be something that doesn't exist.

Unfortunately, in JavaScript, the data type of null is an object.

JavaScript Function Syntax


function name(parameter1, parameter2, parameter3) {
    code to be executed
}

Function Invocation

The code inside the function will execute when "something" invokes (calls) the function:
  • When an event occurs (when a user clicks a button)
  • When it is invoked (called) from JavaScript code
  • Automatically (self invoked)

Function Return

When JavaScript reaches a return statement, the function will stop executing.

JavaScript Objects

Object Properties
The name:values pairs (in JavaScript objects) are called properties.
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

Accessing Object Properties

You can access object properties in two ways:
objectName.propertyName
or
objectName["propertyName"]

Accessing Object Methods

You access an object method with the following syntax:
objectName.methodName()


Automatically Global

If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.

Example

myFunction();

// code here can use carName 
function myFunction() {
    carName = "Volvo";
}

JavaScript Debugging

  •  console.log() Method
  • Setting Breakpoints
  •  debugger Keyword

JavaScript Hoisting

  • JavaScript Declarations are Hoisted
  • In JavaScript, a variable can be declared after it has been used.
  • In other words; a variable can be used before it has been declared.

Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).

JavaScript Initializations are Not Hoisted

JavaScript only hoists declarations, not initializations.


Note-: Declare Your Variables At the Top 

Hoisting is (to many developers) an unknown or overlooked behavior of JavaScript. If a developer doesn't understand hoisting, programs may contain bugs (errors). To avoid bugs, always declare all variables at the beginning of every scope.

JavaScript Use Strict

Strict mode makes it easier to write "secure" JavaScript.
  • Strict mode changes previously accepted "bad syntax" into real errors.
  • As an example, in normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable.
  • In normal JavaScript, a developer will not receive any error feedback assigning values to non-writable properties.
  • In strict mode, any assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object, will throw an error.
"use strict";
x = 3.14;                // This will cause an error


Note-: The "use strict" directive is only recognized at the beginning of a script or a function.

Loading JavaScript in HTML

Use simple syntax for loading external scripts (the type attribute is not necessary):
<script src="myscript.js"></script>

Accessing HTML Elements

A consequence of using "untidy" HTML styles, might result in JavaScript errors.
These two JavaScript statements will produce different results:
var obj = getElementById("Demo")

var obj = getElementById("demo")


Never Declare Number, String, or Boolean Objects

Always treat numbers, strings, or booleans as primitive values. Not as objects.

Don't Use new Object()

  • Use {} instead of new Object()
  • Use "" instead of new String()
  • Use 0 instead of new Number()
  • Use false instead of new Boolean()
  • Use [] instead of new Array()
  • Use /()/ instead of new RegExp()
  • Use function (){} instead of new Function()

Document Object Model


When html document is loaded in the browser, it becomes a document object. It is the root element that represents the html document. It has properties and methods. By the help of document object, we can add dynamic content to our web pageThe document object represents the whole html document.


To Understand Javascript engine follow the link

http://developer.telerik.com/featured/a-guide-to-javascript-engines-for-idiots/














Interview Prep: Java full stack

 SOLID principle :  https://www.educative.io/answers/what-are-the-solid-principles-in-java Design Pattern:  Creational:  https://medium.com...