Javascript Module-1
Javascript Module-1
JavaScript is the world's most popular Web programming language. JavaScript was initially created to
“make web pages alive”. The programs in this language are called scripts. They can be written right in a web
page’s HTML and run automatically as the page loads.
Scripts are provided and executed as plain text. They don’t need special preparation or compilation to run.
Today, JavaScript can execute not only in the browser, but also on the server, or actually on any device that
has a special program called the JavaScript engine. The browser has an embedded engine sometimes
called a “JavaScript virtual machine”. Different engines have different “codenames”. For example: V8 – in
Chrome, Opera and Edge, SpiderMonkey – in Firefox , …There are other codenames like “Chakra” for IE,
“JavaScriptCore”, “Nitro” and “SquirrelFish” for Safari, etc.
Why is it called JavaScript?
When JavaScript was created, it initially had another name: “LiveScript”. But Java was very popular at that
time, so it was decided that positioning a new language as a “younger brother” of Java would help.
But as it evolved, JavaScript became a fully independent language with its own specification called
ECMAScript, and now it has no relation to Java at all.
Code editors
A code editor is the place where programmers spend most of their time. There are two main types of code
editors: IDEs and lightweight editors. Many people use one tool of each type.
IDE : The term IDE (Integrated Development Environment) refers to a powerful editor with many features
that usually operates on a “whole project.” As the name suggests, it’s not just an editor, but a full-scale
“development environment.” An IDE loads the project (which can be many files), allows navigation between
files, provides autocompletion based on the whole project (not just the open file), and integrates with a
version management system (like git), a testing environment, and other “project-level” stuff. If you haven’t
selected an IDE yet, consider the following options:
Visual Studio Code (cross-platform, free).
WebStorm (cross-platform, paid).
For Windows, there’s also “Visual Studio”, not to be confused with “Visual Studio Code”. “Visual Studio” is a
paid and mighty Windows-only editor, well-suited for the .NET platform. It’s also good at JavaScript. There’s
also a free version Visual Studio Community. Many IDEs are paid, but have a trial period. Their cost is usually
negligible compared to a qualified developer’s salary, so just choose the best one for you.
Lightweight editors : “Lightweight editors” are not as powerful as IDEs, but they’re fast, elegant and
simple. They are mainly used to open and edit a file instantly. The main difference between a “lightweight
editor” and an “IDE” is that an IDE works on a project-level, so it loads much more data on start, analyzes the
project structure if needed and so on. A lightweight editor is much faster if we need only one file. In practice,
lightweight editors may have a lot of plugins including directory-level syntax analyzers and autocompletes, so
there’s no strict border between a lightweight editor and an IDE.
There are many options, for instance:
Sublime Text (cross-platform, shareware).
Notepad++ (Windows, free).
Vim and Emacs are also cool if you know how to use them.
JavaScript Output
JavaScript Display Possibilities - JavaScript can "display" data in different ways:
Using innerHTML : To access an HTML element, JavaScript Using document.write() - For testing purposes, it is
can use the document.getElementById(id) method. convenient to use document.write():
The id attribute defines the HTML element. The innerHTML property defines <html>
the HTML content: <body>
<html> <h2>My First Web Page</h2>
<body> <p>My first paragraph.</p>
<h2>My First Web Page</h2> <p>Never call document.write after the document has finished loading
<p>My First Paragraph.</p> It will overwrite the whole document.</p>
<p id="demo"></p> <script>
<script> document.write(5 + 6);
document.getElementById("demo").innerHTML = 5 + 6; </script>
</script> </body>
</body> </html>
</html>
<html>
<body>
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<script>
alert(5 + 6);
</script>
</body>
</html>
JavaScript Print JavaScript Statements - JavaScript statements are composed
JavaScript does not have any print object or print methods. Values, Operators, Expressions, Keywords, and Comments.
You cannot access output devices from JavaScript. <!DOCTYPE html>
The only exception is that you can call the window.print() method in the <html>
browser to print the content of the current window. <body>
<html> <h2>JavaScript Statements</h2>
<body> <p>JavaScript statements are separated by semicolons.</p>
<h2>The window.print() Method</h2> <p id="demo1"></p>
<p>Click the button to print the current page.</p> <script>
<button onclick="window.print()">Print this page</button> let a, b, c;
</body> a = 5;
</html> b = 6;
c = a + b;
document.getElementById("demo1").innerHTML = c;
</script>
</body>
</html>
Comments in JavaScript
JavaScript supports both C-style and C++-style comments, Thus −
Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript.
Any text between the characters /* and */ is treated as a comment. This may span multiple lines.
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 //-->.
<h1 id="myH"></h1>
<p id="myP"></p>
<script>
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
*/
document.getElementById("myH").innerHTML = "JavaScript Comments";
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>
</body>
</html>
function sayHello()
{
alert("Hello World")
}
JavaScript Variables
4 Ways to Declare a JavaScript Variable:
• Using var
• Using let
• Using const
• Using nothing
In this example, x, y, and z, are In this example, x, y, and z, are In this example, x, y, and z
variables, declared with variables, declared with When to Use JavaScript const? undeclared variables:
the var keyword: the let keyword:
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);
document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);
document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);
document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);
document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);
a = ++a;
document.write("++a = ");
result = ++a;
document.write(result);
document.write(linebreak);
b = --b;
document.write("--b = ");
result = --b;
document.write(result);
document.write(linebreak);
//-->
</script>
Example
The following code shows how to use comparison operators in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
Example
Try the following code to understand how the Conditional Operator works in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
if statement
The if statement is the fundamental control statement that allows JavaScript to make decisions and execute
statements conditionally.
Syntax
The syntax for a basic if statement is as follows −
if (expression) {
Statement(s) to be executed if expression is true
}
<html> <html>
<body> <body>
<h2>JavaScript if</h2> <script>
<p>Display "Good day!" if the hour is less than var a=20;
18:00:</p> if(a%2==0){
<p id="demo">Good Evening!</p> document.write("a is even number");
<script> }
if (new Date().getHours() < 18) else{
{ document.getElementById("demo").innerHTML = document.write("a is odd number");
"Good day!"; }
} </script>
</script> </body>
</body> </html>
</html>
Create a JavaScript Calculator using If... Else...If statement and display using the
prompt dialog box.
<html>
<body>
<script>
// program to create a simple calculator using the if...else...if in JavaScript.
// take the operator from the user through prompt box in JavaScript.
const operator = prompt('Enter operator to perform the calculation ( either +, -, * or / ): ');
// accept the number from the user through prompt box
const number1 = parseFloat(prompt ('Enter the first number: '));
const number2 = parseFloat(prompt ('Enter the second number: '));
let result; // declaration of the variable.
// use if, elseif and else keyword to define the calculator condition in JavaScript.
if (operator == '+') { // use + (addition) operator to add two numbers
result = number1 + number2;
}
else if (operator == '-') { // use - (subtraction) operator to subtract two numbers
result = number1 - number2;
}
else if (operator == '*') { // use * (multiplication) operator to multiply two numbers
result = number1 * number2;
}
else {
result = number1 / number2; // use / (division) operator to divide two numbers
}
// display the result of the Calculator
window.alert(" Result is" + result);
</script>
<body>
</html>
JavaScript Switch Statement
The objective of a switch statement is to give an expression to evaluate and several different
statements to execute based on the value of the expression. The interpreter checks
each case against the value of the expression until a match is found. If nothing matches,
a default condition will be used.
switch (expression) {
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
case condition n: statement(s)
break;
default: statement(s)
}
1. The switch is a conditional statement like if statement.
2. A switch statement includes literal value or is expression based
3. A switch statement includes multiple cases that include code blocks to execute.
4. A break keyword is used to stop the execution of case block.
5. A switch case can be combined to execute same code block for multiple cases.
<html> <html> <html>
<body> <body> <body>
<h1>Demo: switch case</h1> <h1>Demo: combined switch
<h2>JavaScript switch</h2> cases</h1>
<script>
var a = 3; <p id="demo"></p> <script>
var a = 2;
switch (a) { <script>
case 1: let day; switch (a) {
alert('case 1 executed'); switch (new Date().getDay()) { case 1:
case 2: case 0: case 2:
alert("case 2 executed"); day = "Sunday"; case 3:
break; break; alert("case 1, 2, 3
case 3: case 1: executed");
alert("case 3 executed"); day = "Monday"; break;
break; break; case 4:
case 4: case 2: alert("case 4 executed");
alert("case 4 executed"); day = "Tuesday"; break;
break; break; default:
default: case 3: alert("default case
alert("default case executed"); day = "Wednesday"; executed");
} break; }
case 4: </script>
</script> day = "Thursday"; </body>
</body> break; </html>
</html> case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
document.getElementById("demo").innerHTML
= "Today is " + day;
</script>
</body>
</html>