Basics of JavaScript – Variables, Arrays and Objects

JavaScript (JS) is a dynamic computer programming language which is most commonly used as part of web browsers to allow client-side scripts to interact with the user, control the browser, communicate asynchronously, and alter the document content that is displayed. JavaScript is however not limited to web browsers and applies to other areas as well like PDF documents, VXML documents and desktop widgets.

JavaScript was formalized in the ECMAScript language standard. ECMAScript is the scripting language standardized by Ecma International in the ECMA-262 specification and JavaScript, JScript and ActionScript can be considered as the implementations for ECMAScript. Some browsers and applications provide additional functionalities than specified in the ECMAScript, but it is always better to comply with ECMAScript.

JavaScript has no relation to Java programming language except for the similarity in name and some similarity in syntax. JavaScript is dynamically typed compared to Java which is strongly typed. JavaScript was originally developed by Brendan Eich of Netscape under the name Mocha, later LiveScript, and finally renamed to JavaScript due to the popularity of Java programming language.

A dynamic web page is created basically using three building blocks and they are HTML, CSS and JavaScript. HTML provides the markup and is static. CSS provides the look and feel independent of the markup; for instance, you can have different look and feel to the same HTML page by changing the CSS associated with it. And finally JavaScript give dynamic features to the page such as allow client-side scripts to interact with the user, control the browser, communicate asynchronously, and alter the HTML content that is displayed.

Enough of theory and explanations; we will quickly go technical and see some useful stuff for working with JavaScript. This article assumes that you are familiar with Java or any programming language and common constructs like variables, arrays etc. Else, please go through ‘Beginning Java Book’.

 

JavaScript “Hello World” program

First we will see a simple “Hello World” program.

Create an HTML file and place the below script tag and contents in its head:

<script type="text/javascript">

            alert("Hello World!")

</script>

You can either type all html tags or use an IDE like eclipse which will create an html page with basic tags. I will add this to an eclipse generated HTML file as:

<!DOCTYPE html>

<html>

<head>

<meta charset="ISO-8859-1">

<title>Hello World</title>

<script type="text/javascript">

            alert("Hello World!")

</script>

</head>

<body>

</body>

</html>

When I open this is a browser, the script within the head is executed and I will get a popup with the test “Hello World!”

Now let us see some important rules and semantics of JavaScript:

  • JavaScript is a case sensitive.

  • JavaScript statements have to be included inside the <script> tags. The script tags can either be added to the head tag or to the body tag.

  • Browsers will need to have a built-in JavaScript engine that interprets and executes the JavaScript on the webpage. Examples of such engines are SpiderMonkey and Rhino.

  • A JavaScript will block the page until they are loaded.

 

Variables in JavaScript

The keyword var is used to declare a variable in JavaScript, followed by the name of that variable:

var val=5;

Until a value is assigned to a variable, the value of the variable will be implicitly set to undefined. Also note that there is no type assigned to the variable and it takes the type of the value assigned to it. JavaScript is dynamically typed compared to Java which is strongly typed.

 

Arrays in JavaScript

A JavaScript array is similar to a C or java array and contains ordered elements with an index for every element. We can declare, provide values and later retrieve values as:

var myArray = [];

myArray[0] = "zero";

myArray[1] = "one";

alert(myArray[1]);

Here the index doesn’t have to be integers and can be even strings:

var myArray = [];

myArray["zero"] = "first";

myArray["one"] = "second";

alert(myArray["one"]);

We can also mix the index and value types:

var myArray = [];

myArray[0] = "first";

myArray["one"] = 1;

alert(myArray[0]);

alert(myArray["one"]);

JavaScript also supports multidimensional arrays like Java.  Multidimensional arrays are arrays that contain arrays:

var myArray1 = [];

myArray1[0] = "first";

myArray1[1] = "second";

var myArray2 = [];

myArray2[0] = "secondfirst";

myArray2[1] = "secondsecond";

var multiArray = [myArray1,myArray2];

alert(multiArray[1][1]);

This will alert with value “secondsecond”.

 

Objects in JavaScript

JavaScript objects are derived from the object-oriented programming concept. But unlike Java, you don’t have to define a class first with properties and methods. Properties can be created as and when required.

var emp = new Object();

emp.name="Heartin";

emp.age=29;

emp.showDetails = function (){

  alert ("Name="+ emp.name+". Age="+emp.age);

}

emp.showDetails();

We also saw how to define a function within an object and how to invoke them.

We can also define objects by using the curly braces:

var emp ={

"name" : "Heartin",

"age" : 29,

"showDetails" : function (){

  alert ("Name="+ this.name+". Age="+this.age);

  },

};

emp.showDetails();

From my experience, this syntax is more prone to errors than the previous one. Also, note that unlike Java, JavaScript won’t give you a stack trace of the error, but will fail silently. So checkout the minute details like missing elements such as comma, semicolon, equalto etc.

 

Calling JavaScript from Java

Until Java SE 7, JDKs shipped with a JavaScript scripting engine based on Mozilla Rhino. Java SE 8 will instead ship with a new engine called Oracle Nashorn, which is based on JSR 292 and invokedynamic. It provides better compliance with the ECMA normalized JavaScript specification and better runtime performance.

 

Reference

http://en.wikipedia.org/wiki/JavaScript

http://www.w3schools.com/js/DEFAULT.asp

http://www.oracle.com/technetwork/articles/java/jf14-nashorn-2126515.html

Quick Notes Finder Tags

Activities (1) advanced java (1) agile (3) App Servers (6) archived notes (2) Arrays (1) Best Practices (12) Best Practices (Design) (3) Best Practices (Java) (7) Best Practices (Java EE) (1) BigData (3) Chars & Encodings (6) coding problems (2) Collections (15) contests (3) Core Java (All) (55) course plan (2) Database (12) Design patterns (8) dev tools (3) downloads (2) eclipse (9) Essentials (1) examples (14) Exception (1) Exceptions (4) Exercise (1) exercises (6) Getting Started (18) Groovy (2) hadoop (4) hibernate (77) hibernate interview questions (6) History (1) Hot book (5) http monitoring (2) Inheritance (4) intellij (1) java 8 notes (4) Java 9 (1) Java Concepts (7) Java Core (9) java ee exercises (1) java ee interview questions (2) Java Elements (16) Java Environment (1) Java Features (4) java interview points (4) java interview questions (4) javajee initiatives (1) javajee thoughts (3) Java Performance (6) Java Programmer 1 (11) Java Programmer 2 (7) Javascript Frameworks (1) Java SE Professional (1) JPA 1 - Module (6) JPA 1 - Modules (1) JSP (1) Legacy Java (1) linked list (3) maven (1) Multithreading (16) NFR (1) No SQL (1) Object Oriented (9) OCPJP (4) OCPWCD (1) OOAD (3) Operators (4) Overloading (2) Overriding (2) Overviews (1) policies (1) programming (1) Quartz Scheduler (1) Quizzes (17) RabbitMQ (1) references (2) restful web service (3) Searching (1) security (10) Servlets (8) Servlets and JSP (31) Site Usage Guidelines (1) Sorting (1) source code management (1) spring (4) spring boot (3) Spring Examples (1) Spring Features (1) spring jpa (1) Stack (1) Streams & IO (3) Strings (11) SW Developer Tools (2) testing (1) troubleshooting (1) user interface (1) vxml (8) web services (1) Web Technologies (1) Web Technology Books (1) youtube (1)