JavaScript Syntax


JavaScript Keywords

JavaScript keywords are some reserved words that can’t be used as identifier and are used to identify actions to be performed e.g., the var keyword tells the browser to declare variables in JavaScript.

Here is the list of JavaScript keywords:

abstract arguments await boolean
break byte case catch
char class const continue
debugger default delete do
double else enum eval
export extends false final
finally float for function
goto if implements import
in instanceof int interface
let long native new
null package private protected
public return short static
super switch synchronized this
throw throws transient true
try typeof var void
volatile while with yield

Whitespace and Line Breaks in JavaScript

JavaScript ignores spaces, tabs, and newline characters that appear in JavaScript programs.

Spaces, tabs, and newlines can be used freely.

This allows you to format and indent the programs in a neat and consistent way that increases readability.

Optional Semicolons in JavaScript

Generally the statements in JavaScript are followed by a semicolon.

However, JavaScript also allows you to omit this semicolon if each of the statements is placed on a separate line.

For example, the following code snippet can be written without semicolons:

But when written in a single line as follows, semicolons must be used

Case Sensitivity

JavaScript is case-sensitive which means that the JavaScript keywords, variables, function names, and any other identifiers must always be typed maintaining a consistent capitalization of letters.

So the identifiers DATE, date and Date will convey different meanings in JavaScript.

Comments in JavaScript

  • Anything written between a // and the end of a line is treated as a comment and is not executed by JavaScript.
  • Any text between the characters /* and */ is treated as a multiple line comment.
  • JavaScript recognizes the HTML comment opening <!–. JavaScript treats this as a single-line comment, just like the // comment.
  • The HTML comment closing sequence –> is not considered as a comment by JavaScript so it must be written as //–>.

JavaScript Inclusion in HTML File

Javascript in Internal File

  1. You can place JavaScript code on HTML pages anywhere within<html> tags(within <body>tag as well as <head> tag)
  2. JavaScript code must be inside <script> tag for aninternal placement.

Within <head> tag

Within <body> tag

External JavaScript

To use JavaScript from an external file source, all JavaScript source code must be written in a text file with the extension “.js” and then include that file as shown below:

For example, if the following content is already written in the file_name.js file the function  Show can be invoked in your HTML file after including the file_name.js file.

Note: The correct path (using ./ or ../ in front of the filename in src attribute) should be mentioned while including the external .js file otherwise it will throw an error and the file will not be included into the current HTML script.

External JavaScript Advantages

Placing scripts in external files is more advantageous than that of in an internal file:

  • It separates HTML and JavaScript code
  • It makes both HTML and JavaScript code easier to read and maintain
  • Cached JavaScript files can speed up page loading

Absolute Path

External scripts can be included with a full URL which is known as Absolute path. Consider the following example:

<script src=”https://www.abcd.co.in/js/file_name.js”></script>

Relative Path

External scripts can also be referenced with a path relative to the current web page which is known as Relative path. Consider the following example:

<script src=”/js/file_name.js”></script>

JavaScript Introduction

What is Javascript?

Javascript (JS) is a high-level, interpreted programming language used in web development.

It is a language which is also known as dynamic, loosely typed and multi-paradigm.

Along with HTML and CSS, Javascript is one of the three main technologies of the World Wide Web.

Brief history of Javascript

JavaScript was created by Brendan Eich(a Netscape Communications Corporation programmer) in 1995.

Eich took only 10 days to develop the scripting language known as Mocha.

When it was first delivered, it was made for Netscape Navigator and quickly became popular as LiveScript.

The name was changed to JavaScript later on to reflectNetscape’s support of Java within its browser.

It was a “marketing strategy” to connect a brand new language (JavaScript) to a widely popular language (Java), regardless of that JavaScript and Java have nothing in common.

At that time, there were two dominating web browsers i.e., Netscape Navigator (with JavaScript) and Internet Explorer (with JScript).

By 1996, JavaScript’s popularity grew so much that it was handed over to an international standards scripting language body called ECMA (European Computer Manufacturers Association) that is responsible for the development and upkeep of this language.  

So the scripting language was officially named as ‘ECMAScript’. However people still call it JavaScript.

Usage of JavaScript

  • Client-side validation
  • Dynamic drop-down menu
  • Displaying date and time at any moment
  • Validate user input in an HTML form before form submission(sendingthe data to a server)
  • Build forms that respond to user input without involving a serverrequest
  • Change the appearance of HTML elements
  • Open, close and redirection of new windows or frames
  • Manipulate HTML layers  likehiding, moving, and allowing the user to drag them around a browser window
  • Build complete client side programs
  • Displaying popup windows and dialog boxes (e.g., alert dialog box,confirm dialog box and prompt dialog box)
  • Displaying clocks

Advantages of JavaScript

  • Speed. Client-side JavaScript is very fast because it can be run without  server-side access.
  • Simplicity: JavaScript is easier to learn and implement.
  • Popularity:  JavaScript is used almost everywhere in web design and development industry. StackOverflow and GitHub have many projects using Javascript. The language has gained a lot of traction in the industry in recent years.
  • Interoperability: JavaScript can be inserted into any web page regardless of the file extension or inside scripts written in other languages like Perl and PHP.
  • Server Load: Being client-side reduces the demand on the website server thereby decreasing overall load.
  • Rich interfaces: Drag and drop components or slider gives a rich interface to your website with the use of JavaScript.
  • Extended Functionality: Third party add-ons like Greasemonkey has enabled JavaScript developers to write of JavaScript snippets that can be executed on desired web pages to extend its functionality.
  • Versatility: There are many ways to use JavaScript through Node.js server nowdays e.g., if it is bootstrap node.js with Express, a document database like mongodb must be used. JavaScript is also used in the front-end for clients. It is possible to develop an entire app from front to back end using only JavaScript.
  • Updates: Since the advent of EcmaScript 5, ECMA International has dedicated to continue updating JavaScript annually.

Disadvantages of JavaScript

  • Client-Side Security: As the code is executed on the users’ computer, in some cases it can be exploited for malicious purposes which are not desirable.
  • Browser Support: JavaScript is interpreted differently by different browsers whereas server-side scripts will always produce the same output. Client-side scripts can be a little unpredictable.

Note: There are services out there that will allow you to test your code automatically on check in of an update to make sure all browsers support your code.

Latest version of JavaScript

The latest version of JavaScript (ES7) is supported by the updated versions of Google Chrome and Mozilla Firefox.

Concatenate & Buffer File in Java

Concatenate: It is possible to concatenate two or more files and save in a different file.

In java, by using SequenceInputStream class we can concatenate two or more files.

Buffer Files: In java, we can create a buffer to store temporary data that is read from & written to a stream and this process known as i/o buffer operation.

Buffer is  sit between programmer and source/destination file.

Buffer can be created by using following classes:

  • BufferedInputClass
  • BufferedOutputClass

Example: write a program to concatenate two file A & B and concatenated data print on output screen.

Suppose we have a File “A.txt”

Hello students I am aditya.  

 and                         File “B.txt”

Hello  

Output: Hello students I am aditya.                                                                                           Hello

Example: Write a program to copy the content of one file to another file using buffer/BufferReader.                                                                

Suppose we have a File “A.txt”                               

Hello students I am aditya.  

Output:                                              File “B”

Hello students I am aditya.  

Note: If there is no file “B” it will be create automatically.

Example: Write a program to concatenate two file A & B and save the concatenated data on a file C.

Suppose we have a File “A.txt” and File “B.txt”

Hello students I am aditya.  
Hello  

Output:               File “C”

Hello students I am aditya. Hello  

Note: Ifthere is no file “C” it will be create automatically.

DataInputStream and DataOutputStream for primitive data

In java, basic input-output stream provides a method for reading & writing bytes or character in a file.

If we want to read-write primitive data typa (such as int , float etc.) than we can use filter classes to filter data in the original stream.

DataInputStream & DataOutputStream are two filter classes used for creating “data streams” for handling primitive data type.

1 DataInputStream Class

In java DataInputStream class is used to allow application to read primitive data from different sources.

DataInputStream is a sub type of FilterInputStream.

A. DataInputStream Constructor

Sr NoConstructor
1DataInputStream​(InputStream in)
Take InputStream object to create DataInputStream

Constructor call of DataInputStream

FileInputStream i = new FileInputStream("A.txt"); //open file A for read        
DataInputStream I = new DataInputStream(i);

B Methods in DataInputStream

Following are the methods of DataInputStream

Sr NoMethod
1public final int read(byte[] b) throws IOException
Reads number of bytes from input stream and store in buffered array b
2public final int read(byte[] b, int off, int len) throws IOException
Reads up to len bytes from input stream and store in buffered array b
3public final boolean readBoolean() throws IOException
Reads one input byte and return true if byte is non zero, else false
4public final byte readByte() throws IOException
Reads and return one input byte
5public final char readChar() throws IOException
Reads two input byte and return a char
6public final double readDouble() throws IOException
Reads eight input byte and return a double value
7public final float readFloat() throws IOException
Reads four input bytes and return a float value
8public final void readFully(byte[] b) throws IOException
Reads some bytes from input stream and store in buffer array b
9public final int readInt() throws IOException
Reads four input bytes and return a integer value
10public final long readLong() throws IOException
Reads eight input bytes and returns a long value
11public final short readShort() throws IOException
Reads one input bytes and returns a short value
12public final int readUnsignedByte() throws IOException
Reads two byte and return unsigned byte value
13public final String readUTF() throws IOException
Reads a string that has been encoded in modified utf-8 format
15public static final String readUTF(DataInput in) throws IOException
Reads from a stream that has been encoded in modified utf-8 format
16public final int skipBytes(int n) throws IOException
Makes attempt to skip n bytes of data from input stream

Example: Write a program to write & read a primitive data on a same file.

Character Stream I/O in Java

In a java programming, like a Byte stream Character stream is also used for input-output for 16 bit. But Byte streams are used to perform input and output of 8-bit.

Most common Character streams classes are, FileReader and FileWriter.

 FileReader- FileReader uses for reads two bytes at a time.

 FileWriter– FileWriter uses for writes two bytes at a time.

Example: Write a program, to copy the content of file A into file B using Byte stream class.

Note: if there is only file A in which data is written and no file B then, file B will be create automatically.

Suppose we have a File “A”

Hello students I am aditya.  

Output: When we run above program one new file create with Name “B” and content of file “A” will be copy into file “B”.

            File “B”

Hello students I am aditya.  

Byte Streams in Java

In java programming, to perform input and output of 8-bit, Byte stream is used.

Most common byte streams classes are, FileInputStream and FileOutputStream.

FileInputStream : FileInputStream is used for reads one byte at a time .

FileOutputStream : FileOutputStream is used for writes one byte at a time

Writing Bytes

Example: Write a program, to write a bytes to a  file using Byte stream class.

Result

checking file A.txt it will show following content.

Note: If there is no file A then, file A will be create automatically

Reading bytes from a file

Suppose we have a file “A.txt”

Hello Students I am Aditya

Example: Write a program, to read a bytes from file A using Byte stream class and print on output screen.

Example: Write a program, to copy the content of file A into file B using Byte stream class.

Note: if there is only file A in which data is written and no file B then, file B will be create automatically.

Suppose we have a File “A”

Hello students I am aditya.  

Output: When we run above program one new file create with Name “B” and content of file “A” will be copy into file “B”.

File “B”

Hello students I am aditya.  

File and Input Output in Java

In Java programming, to perform the input-output in file handling  Java has a java.io package which contain contains nearly every class you might ever need.

In file handling streams represent an input source and an output destination.

Stream

In java programming, a sequence of data defined as a “stream”.

Simply  there are two type of streams:

  1. InputStream −  To read data from a source InputStream is used.
  2. OutputStream-  To write a data to a destination OutputStream is used.

Stream Classes

In java,  package “java.io”  contains a large number of stream classes and these classes can be divided into two groups:

  1. Byte stream
  2. Character stream

Thread isAlive() and join() Methods in Java

There are two ways  to determine whether a thread has finished or not.

  •   isAlive()
  •   join()

isAlive():  isAlive() method is used to check whether a thread is in the running or not .

                                                or

In a another word, this method determines thread is live or dead. 

isAlive( )method returns true if the thread is still running otherwise  it returns false.

join(): This method wait for the specified thread to terminate.

Result

Thread suspend() and resume() method in Java

suspend() : This method suspend a thread for sometime but do not kill/terminate it.

resume() : This method revives the suspended thread.