JavaScript Overview:
JavaScript is a scripting language for web browsers. It was developed at Netscape Communication Corporation and was originally named “LiveScript”. It was later changed to “JavaScript” after an agreement with Sun Microsystems, the developers of Java.
JavaScript is a versatile, dynamic language primarily used for web development. It is lightweight and most commonly used as a part of web pages, whose implementations allow client-side script to interact with the user and make dynamic pages. It is an interpreted programming language with object-oriented capabilities.
JavaScript is a scripting language that can be used to create web pages that are highly interactive. Java and JavaScript are not the same. Java and JavaScript are two completely different languages in both concept and design! JavaScript however has the same syntax as Java, a very popular programming language for the Internet.
JavaScript is used in millions of Web pages to improve the design, to add functionality, validate forms, detect browsers, create cookies and much more. It is the most popular scripting language on the internet, works in all major browsers such as Internet Explorer, Mozilla Firefox, and opera.
JavaScript is interpreted by the client program, the browser. JavaScript code is placed within an HTML document. When the page that contains the script is loaded, the web browser’s built-in interpreter takes the code and executes the instructions.
JavaScript has built in objects such as Navigator, Window, Date. Through these objects JavaScript can access many of the browser elements like windows, links, images etc.
JavaScript is a case-sensitive, object-oriented scripting language which can be used for the following:
· User interaction with form elements (input fields, text area, buttons, radio buttons, check boxes, and selection lists)
· Access java Applet methods
· Validate form-processing the data on the client side before submission to the server.
· Animation and live image swapping.
What is JavaScript?
· JavaScript was designed to add interactivity to HTML pages
· JavaScript is a scripting language
· A scripting language is a lightweight programming language
· JavaScript is usually embedded directly into HTML pages
· JavaScript is an interpreted language (means that scripts execute without preliminary compilation)
· Everyone can use JavaScript without purchasing a license
What can a JavaScript do?
JavaScript gives HTML designers a programming tool: JavaScript is a scripting language with a very simple syntax. Almost anyone can put small “snippets” of code into their HTML pages.
JavaScript can put dynamic text into an HTML page– A JavaScript statement like this: document.write(“<h1>” + name + “</h1>”) can write a variable text into an HTML page.
JavaScript can react to events – A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element.
JavaScript can read and write HTML elements– A JavaScript can read and change the content of an HTML element.
JavaScript can be used to validate data – A JavaScript can be used to validate form data before it is submitted to a server. This saves the server from extra processing.
JavaScript can be used to detect the visitor’s browser– A JavaScript can be used to detect the visitor’s browser, and – depending on the browser – load another page specifically designed for that browser.
JavaScript can be used to create cookies –A JavaScript can be used to store and retrieve information on the visitor’s computer.
Advantages of Java Script (Pros of JavaScript)
- Client-Side Interactivity: One of the most significant advantages of JavaScript is its ability to add interactivity to web pages directly within the browser. With JavaScript, developers can create dynamic user interfaces, respond to user actions in real-time, validate input, and provide feedback without needing to reload the entire page.
- Cross-platform Compatibility: JavaScript is supported by all modern web browsers, including Chrome, Firefox, Safari, and Edge, making it a highly cross-platform language. This enables developers to write code once and have it run consistently across different devices and operating systems.
- Scalability: JavaScript is highly scalable, allowing developers to build both small, lightweight scripts and large, complex applications. Modern JavaScript frameworks and tools offer features like component-based architecture, state management, and code splitting to facilitate scalability and maintainability.
- Platform Extension: JavaScript can be used not only for web development but also for building mobile apps (using frameworks like React Native or Ionic), desktop applications (using frameworks like Electron), and even Internet of Things (IoT) devices. This versatility extends the reach of JavaScript beyond traditional web development.
- Rich Ecosystem: JavaScript benefits from a vast and active ecosystem comprising libraries, frameworks, and tools that streamline development tasks. Popular frameworks like React, Angular, and Vue.js provide robust solutions for building complex web applications, while libraries like jQuery simplify common tasks such as DOM manipulation and AJAX requests.
Disadvantages of Java Script (Cons of JavaScript)
- Security Risks: JavaScript’s client-side execution exposes it to various security vulnerabilities, including cross-site scripting (XSS) attacks, data tampering, and code injection.
- Client-Side Dependency: JavaScript executes on the client-side, meaning that users must have a compatible browser and JavaScript enabled for web applications to function correctly. This reliance on client-side execution can lead to inconsistent behavior if users have older browsers or disable JavaScript, affecting accessibility and usability.
- Browser Compatibility Issues: Despite efforts to standardize JavaScript across different browsers, inconsistencies in browser implementations can still occur, leading to compatibility issues.
- Lack of Strong Typing: JavaScript is dynamically typed, meaning that variable types are determined at runtime rather than compile time. While this flexibility can be advantageous for rapid prototyping and flexibility, it can also lead to errors and bugs due to type mismatches, especially in large codebases.
- Maintainability Concerns: As JavaScript applications grow in size and complexity, maintaining code quality and scalability becomes increasingly challenging. Without proper modularization, organization, and documentation, JavaScript codebases can become difficult to navigate and prone to bugs and regressions over time.
JavaScript and HTML are two distinct technologies used in web development, each serving different purposes. Here are the key differences between JavaScript and HTML:
- Purpose: HTML (Hypertext Markup Language) is a markup language used for structuring and presenting content on the web. It defines the structure of web pages using elements such as headings, paragraphs, lists, and links, While JavaScript is a scripting language used for adding interactivity, behavior, and dynamic functionality to web pages.
- Syntax: HTML uses a tag-based syntax, where elements are enclosed within opening and closing tags (e.g., <p> for paragraphs, <img> for images), while JavaScript uses a C-like syntax with variables, operators, functions, and control structures such as loops and conditionals.
- Static vs. Dynamic: HTML is static in nature, meaning that the structure and content defined in the HTML document remain unchanged unless manually edited, while JavaScript enables dynamic behavior, allowing web pages to respond to user actions, update content dynamically, and interact with external data sources in real-time.
- Role: HTML provides the basic structure and content of web pages, defining elements such as text, images, links, and multimedia, while JavaScript enhances the functionality and behavior of web pages, enabling tasks such as form validation, DOM manipulation, event handling, and asynchronous communication with servers.
- Execution: HTML is executed by the web browser to render the structure and content of web pages visually, while JavaScript is executed by the web browser’s JavaScript engine to add interactivity and dynamic behavior to web pages, running scripts in response to user interactions or events.
Basic way to run a JavaScript program:
JavaScript can be implemented using JavaScript statements that are placed in an HTML file. In order to embed the the JavaScript code in the HTML file , the <script> ……. </script> tags are used. The code within this tag is ignored by the browser’s HTML parser and is passed on to the Browser’s JavaScript interpreter.
We can place the <script> tags, containing JavaScript anywhere within the web page but it is normally recommended that we should keep it within the <head> tags. The <script> tag alerts the browser program to start interpreting all the text between these tags as a script.
A simple syntax of JavaScript will appear as follows.
<script>
JavaScript code
</script>
Note: Although the HTML tags are not case sensitive, JavaScript code is case sensitive.
The script tag takes two important attributes:
Language: This attribute specifies what scripting language are using. Typically, its value will be JavaScript. Although recent versions of HTML (and XHTML, its successor) have phased out the use of this attribute.
Type: This attribute is what is now recommended to indicate the scripting language in use and its value should be set to “text/javascript”.
JavaScript syntax will look as follows:
<script language= “javascript” type= “text/javascript”>
JavaScript code
</script>
Example:
<html>
<head>
<script language=”JavaScript”>
document.write (“<font color= ‘red’>Welcome to JavaScript World</font>”)
</script>
</head>
</html>
Output:
Welcome to JavaScript World
Comments in JavaScript:
These are commands that comment out text in the script. JavaScript supports both C-style and C++ style comments. In JavaScript single line comment as well as multi-line comments can be used. To indicate a comment entry, double slash (//) is used at the beginning of the line. The double slash is called a single line comment. We have to have double slashes at the beginning of each new line. Multiple comment lines are denoted by using /* at the beginning and */ at the end.
· JavaScript also recognizes the HTML comment opening sequence <!– JavaScript treats this as a single-line comment, just as it does the // comment.
· The HTML comment closing sequence –> is not recognized by JavaScript so it should be written as //–>.
VARIABLES:
A variable is a storage location in the memory of the computer where the data can be stored and retrieved as required. Variables are “containers” for storing information. JavaScript variables are used to hold values or expression. Variables are used to store values temporarily in the memory of the computer.
JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data type. Unlike many other languages, you don’t have to tell JavaScript during variable declaration what type of value the variable will hold. The value type of a variable can change during the execution of a program and JavaScript takes care of it automatically.
A variable can have a short name, like x, or a more descriptive name, like rollnumber.
Rules for JavaScript variable names:
· Variable names are case sensitive (y and Y are two different variables)
· Variable names must begin with a letter or the underscore character
Note: Because JavaScript is case-sensitive, variable names are case-sensitive.
Declaring (Creating) JavaScript Variables:
Variables should be declared with the var keyword
var x;
var name;
We can assign values to the variables when we declare them. Storing a value in a variable is called variable initialization.
var x=10;
var name= “Binoy”;
Note: When we assign a text value to a variable, we use quotes around the value.
Example:
<html>
<body>
<script language= “javascript”>
var name, roll;
name=”Eliza”;
roll=1;
document.write(“Name: “,name);
document.write(“<br>”);
document.write(“Roll Number: “,roll);
</script>
</body>
</html>
Output:
Name: Eliza
Roll Number: 1
JavaScript Variable Scope:
The scope of a variable is the region of program in which it is defined. JavaScript variables have only two scopes.
Global Variables: A global variable has global scope which means it can be defined anywhere in your JavaScript code.
Local Variables: A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.
DATA TYPES:
One of the most fundamental characteristics of a programming language is the set of data types it supports. These are the type of values that can be represented and manipulated in a programming language.
Numbers: Numbers are values that can be processed and calculated. We don’t enclose them in quotation marks. The numbers can be either positive or negative
Strings: Strings are a series of letters and numbers enclosed in quotation marks. JavaScript uses the string literally; it doesn’t process it. We use strings for text we want displayed or values we want passed along.
Boolean: Boolean (true/false) lets you evaluate whether a condition meets or does not meet specified criteria.
Null: Null is an empty value. null is not the same as 0. 0 is a real, calculable number, whereas null is the absence of any value.
Data types |
Examples |
Number |
Any number, such as 100,-99.99, 0.00001 |
Strings |
“welcome”, “4500” |
Boolean |
Either true or false |
Null |
A special keyword with a null value (that is, nothing) |
Control Statements
Control statements in JavaScript are used to manage the flow of code execution based on specific conditions or loops. Here are some key control statements in JavaScript:
Conditional Statements:
Conditional statements allow us to execute different blocks of code based on whether a specified condition evaluates to true or false.
if Statement:
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
Example: Program to check if the number is even or odd
<html>
<head>
<script>
// take input from the user
var num= prompt(“Enter a number: “);
//check if the number is even
if(num%2==0)
document.write(num + ” is an Even Number”);
else
document.write(num + ” is an Odd Number”);
</script>
</head>
<body>
</body>
</html>
else if Statement:
if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition2 is true
} else {
// Code to be executed if no conditions are true
}
Example: Program that checks if the number is positive, negative or zero
<html>
<head>
<script>
// input from the user
const number = parseInt(prompt(“Enter a number: “));
// check if number is greater than 0
if (number > 0) {
document.write(“The number is positive”);
}
// check if number is 0
else if (number == 0) {
document.write(“The number is zero”);
}
// if number is less than 0
else {
document.write(“The number is negative”);
}
</script>
</head>
</html>
switch Statement:
switch (expression) {
case value1:
// Code to be executed if expression equals value1
break;
case value2:
// Code to be executed if expression equals value2
break;
default:
// Code to be executed if expression doesn’t match any case
}
Looping Statements:
All programming languages support looping techniques. Looping is a technique where a set of statements is repeatedly executed for a specified of times or it is repeatedly executed as long as condition is true. Loop statements allow us to repeatedly execute a block of code.
Loops in JavaScript are used to execute the same block of code a specified number of times or while a specified condition is true.
JavaScript supports different kinds of loops:
- for loop: loops through a block of code a number of times
- for…in : loops through the properties of an object
- for…of : loops through the values of an iterable object
- while : loops through a block of code while a specified condition is true
- do…while: also loops through a block of code while a specified condition is true
For Loop:
For loop is used when we know in advance how many times the script should run. A for loop repeats some series of statements until some condition is met.
The for loop structure is given below:
for([initial expression]; [condition];[update expression])
{
code to be executed
}
Example:
for (var i = 0; i < 5; i++) {
// Code to be executed in each iteration
}
The initial expression is simply an assignment of value to the control variable. In the second expression, the condition is executed once for each pass through the loop. If the expression evaluates true, then the block of expressions is executed. If the expression results false the for loop is completed and the interpreter jumps down to the next expression after the loop. The update expression is evaluated after each pass through the loop.
Example: The example below defines a loop that starts with i=1. The loop will continue to run as long as i is less than, or equal to 10. i will increase by 1 each time the loop runs.
<html>
<body>
<script language=”javascript”>
var i=1;
for(i=1;i<=10;i++)
{
document.write(“The number is ” + i);
document.write(“<br>”);
}
</script>
</body>
</html>
Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10
While Loop:
The while loop is used when you want the loop to execute and continue executing while the specified condition is true.
Here is the standard syntax for a while loop:
while (condition)
{
code to be executed
}
Example: The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 10. i will increase by 1 each time the loop runs.
<html>
<body>
<script language=”javascript”>
var i=1;
while (i<=10)
{
document.write(“The number is ” + i);
document.write(“<br>”);
i=i+1;
}
</script>
</body>
</html>
Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10
do-while Loop:
do {
// Code to be executed at least once, and then as long as the condition is true
} while (condition);
Functions:
A function (also known as a method) is a self-contained piece of code that performs a particular task. A function represents a set of code, which can be called into execution repeatedly. A function is a reusable code-block that will be executed by an event, or when the function is called.
We may call a function from anywhere within the page. A function contains code that will be executed by an event or by a call to that function. Functions can be defined both in the <HEAD> and in the <BODY> section of a document. Normally function is placed between <HEAD> and </HEAD> tag.
Coding functions is very useful in developing easy-to-maintain applications. Like a variable, a function is identified by a name. A function is coded starting with the keyword function and the set of statements that represent the function are enclosed within flower brackets or braces.
In JavaScript, functions are blocks of reusable code that perform a specific task. Functions can be broadly categorized into built-in functions, which are provided by the JavaScript language, and user-defined functions, which are created by the developers.
Built-in Functions:
alert():The alert() method displays a pop-up a dialog box with a specified message and an OK button.
alert(“Hello, World!”);
prompt(): The prompt() method displays a dialog box that prompts the user for input.
var variable_name=prompt(“ Text on the gray box”, “Text in the white box”)
var roll=prompt(“What is your Roll Number?”, “101”)
confirm(): Displays a dialog box with a specified message and OK/Cancel buttons. Confirm method is used to ask the confirmation of the user before proceeding. Confirm dialog box has two buttons okay and cancel. Okay returns true and cancel returns false.
var userConfirmed = confirm(“Are you sure?”);
Example:
<html>
<head>
<title>Popup Boxes in JavaScript</title>
<script>
alert(“This is an example of alert box!”);
confirm(“It is a Confirm popup box!”);
var myvar=prompt(“This is a prompt box!”, “Enter someting….”);
alert(“You have entered: “+myvar);
</script>
</head>
<body>
<div style=”text-align:center;”>
<h1>JavaScript Example to Demonstrate Popup Boxes!</h1>
</div>
</body>
</html>
User-Defined Functions:
User-defined functions provide developers with the flexibility to create custom logic and encapsulate code for reuse, making the code more modular and maintainable.
Function Declaration:
Declares a function using the function keyword.
function functionname(var1,var2,…,varn)
{
body of the function
}
var1, var2, etc are variables or values passed into the function. The { and the } defines the start and end of the function.
A function with no parameters must include the parentheses () after the function name:
function functionname()
{
body of the function
}
Example:
<html>
<head>
<script language=”javascript”>
function displaymsg()
{
alert(“Hello JavaScript”);
}
</script>
</head>
<body>
<form>
<input type=”button” value=”Click me!”
onclick=”displaymsg()” >
</form>
</body>
</html>
The return Statement:
The return statement is used to specify the value that is returned from the function. So, functions that are going to return a value must use the return statement.
Example:
<html>
<head>
<title> The Return Statement</title>
</head>
<body>
<h3>JavaScript’s return statement </h3>
<script>
function sum(x, y)
{
return x + y;
}
var result = sum(12, 30);
document.write(result);
</script>
</body>
</html>
Arrays:
An array is collection of data elements. It is a way of organizing data into groups. An array can contain any number of elements, and each element can be any type of data including another array. The entire group of elements will have one name and each element in the group can be referenced through the name and the element number. The element number is the index or subscript of the element. The starting index is 0.
To create an array of five elements:
var x=new Array(5)
The array is named x and its elements are:
x[0], x[1], x[2], x[3] and x[4]
Array can be created without specifying the number of elements and then subsequently assigning values.
var x=new Array()
x[3]= “HELLO”
An array can be initialized as it is created.
var x=new Array(“welcome”, “To, “Assam”)
will create an array of 3 elements
Array Property:
length: The length property gives the number of elements in the array.
for(i=0; i<x.length;i++)
document.write(“<br>” + x[i]);
Example:
<html>
<body>
<script>
var i, n=5, sum=0;
arr = new Array(20, 22, 13, 15, 19);
for(i=0; i<n; i++)
sum = sum + arr[i];
document.write(“Sum of 5 numbers: ” + sum);
</script>
</body>
</html>
FAQ
What are the fundamental differences between HTML and Javascript?
The most basic difference is that JavaScript is a scripting language while HTML is a markup language that allows us to structure web content and control the layout of web content. Whereas JavaScript allows dynamic content manipulation and controls the behavior of the page. For a dynamic web page building, we could use JavaScript, while for a static page, we could use HTML.