Basics of JavaScript
Basics of JavaScript
Overview
JavaScript Introduction
External JavaScript
JS Comment
JS Variable
JS Global Variable
JS Data Types
JS Operators
JS Conditional Statement
JS Switch
JS Loop
JS Function
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
JavaScript is the world's most popular programming language.
JavaScript is the programming language of the Web.
JavaScript is easy to learn.
Features of JavaScript
All popular web browsers support JavaScript as they provide built-in execution
environments.
JavaScript follows the syntax and structure of the C programming language. Thus, it
is a structured programming language.
JavaScript is an object-oriented programming language that uses prototypes rather
than using classes for inheritance.
It is a light-weighted and interpreted language.
It is a case-sensitive language.
JavaScript is supportable in several operating systems including, Windows, macOS,
etc.
It provides good control to the users over the web browsers.
Application of JavaScript
JavaScript is used to create interactive websites. It is
mainly used for:
Client-side validation,
Dynamic drop-down menus,
Displaying date and time,
Displaying pop-up windows and dialog boxes (like an
alert dialog box, confirm dialog box and prompt dialog
box),
Displaying clocks etc.
JavaScript Example
<html>
<body>
<h2>Welcome to JavaScript</h2>
<script>
document.write("Hello JavaScript by JavaScript");
</script>
</body>
</html>
JavaScript Example contd…
Javascript example is easy to code. JavaScript provides 3 places to put the
JavaScript code: within body tag, within head tag and external JavaScript
file.
<script type="text/javascript">
document.write("JavaScript is a simple language");
</script>
message.js
function msg(){
alert("Hello Javatpoint");
}
index.html
<html>
<head>
<script type="text/javascript" src="message.js"></script> </
head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
Advantages of External JavaScript
It helps in the reusability of code in more than one HTML
file.
It allows easy code readability.
It is time-efficient as web browsers cache the external js files,
which further reduces the page loading time.
It enables both web designers and coders to work with html
and js files parallelly and separately, i.e., without facing any
code conflictions.
The length of the code reduces as only we need to specify the
location of the js file.
Disadvantages of External JavaScript
There are the following disadvantages of external files:
The stealer may download the coder's code using the url of the js file.
If two js files are dependent on one another, then a failure in one file may
affect the execution of the other dependent file.
The web browser needs to make an additional http request to get the js code.
A tiny to a large change in the js code may cause unexpected results in all its
dependent files.
We need to check each file that depends on the commonly created external
javascript file.
If it is a few lines of code, then better to implement the internal javascript
code.
JavaScript is Case Sensitive
Unlike HTML, JavaScript is case sensitive
JavaScript Statements
A JavaScript statement is a command to a browser.
document.write("Hello Dolly");
JavaScript Code
JavaScript code (or just JavaScript) is a sequence of
JavaScript statements.
<script type="text/javascript">
document.write("<h1>This is a heading</h1>");
document.write(“<h1>Hello Document</h1>”);
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>");
</script>
JavaScript Blocks
Blocks start with a left curly bracket {, and ends with a
right curly bracket }.
JavaScript Comments
<script type="text/javascript">
/*
This is an example of
Multi Line comments
*/
document.write("<h1>This is a heading</h1>");
// Example of Single Line comments
document.write("<p>This is a paragraph.</p>");
</script>
JavaScript Variable
A JavaScript variable is simply a name of storage location.
There are two types of variables in JavaScript :
Local variable
Global variable
There are some rules while declaring a JavaScript variable (also
known as identifiers).
Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $
) sign.
After first letter we can use digits (0 to 9), for example value1.
JavaScript variables are case sensitive, for example x and X are different
variables.
var x = 10;
var _value="sonoo";
Assigning Values to Undeclared JavaScript
Variables
If you assign values to variables that have not yet been
declared, the variables will automatically be declared.
x=5;
carname=“Honda";
have the same effect as:
var x=5;
var carname=“Honda";
= x=y x=5
variablename=(condition)?value1:value2
Example
x=5+5;
document.write(x);
x="5"+"5";
document.write(x);
x=5+"5";
document.write(x);
x="5"+5;
document.write(x);
Result
10
55
55
55
Insert Special Characters
The backslash (\) is used to insert apostrophes, new lines, quotes, and other
special characters into a text string.
Code Outputs
\' single quote
\" double quote
\& ampersand
\\ backslash
\n new line
\r carriage return
\t tab
\b backspace
\f form feed
Conditional Statements
Very often when you write code, you want to perform
different actions for different decisions. You can use
conditional statements in your code to do this.
In JavaScript we have the following conditional statements:
Syntax
if (condition)
{
code to be executed if condition is true
}
If...else Statement
Use the if....else statement to execute some code if a condition is true and another code if
the condition is not true.
Syntax
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
Example of If statement
<html>
<body>
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
</body>
</html>
Example of If else statement
<html>
<body>
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
</body>
</html>
If...else if...else Statement
Use the if....else if...else statement to select one of several blocks of code to be executed.
Syntax
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 condition1 and condition2 are
not true
}
<html>
<body>
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
</body>
</html>
The JavaScript Switch Statement
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
<!DOCTYPE html>
<html>
<body>
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade"; }
document.write(result);
</script>
</body>
</html>
JavaScript Loops
1. for loop
2. while loop
3. do-while loop
4. for-in loop
The for Loop
The for loop is used when you know in advance how many times the script should run.
Syntax
for (var=startvalue;var<=endvalue;var=var+increment)
{
code to be executed
}
•This loop will execute the block of code ONCE, and then it will repeat the loop
as long as the specified condition is true.
Syntax
do
{
code to be executed
}
while (var<=endvalue);
Example of do.. While loop
<!DOCTYPE html>
<html>
<body>
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
</body>
</html>
The break Statement
The break statement will break the loop and continue executing the code that follows after
the loop (if any).
Example
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
The continue Statement
The continue statement will break the current loop and continue with the next value.
Example
<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3)
{
continue;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
JavaScript Functions
JavaScript functions are used to perform operations. We
can call JavaScript function many times to reuse the code.
Advantage of JavaScript function
There are mainly two advantages of JavaScript functions.
•You may call a function from anywhere within a page (or even from
other pages if the function is embedded in an external .js file).
Example
<html>
<head>
<script type="text/javascript">
function product(a,b)
{
return a*b;
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(product(4,3));
</script>
</body>
</html>
JavaScript Popup Boxes
JavaScript has three kind of popup boxes: Alert box,
Confirm box, and Prompt box.
Alert Box
An alert box is often used if you want to make sure information comes through
to the user.
When an alert box pops up, the user will have to click "OK" to proceed.
Syntax
alert("sometext");
Confirm Box
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel"
to proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box
returns false.
Syntax
confirm("sometext");
Alert example
<html>
<body>
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Confirm Box</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
if (confirm("Press a button!")) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
JavaScript Popup Boxes
Prompt Box
A prompt box is often used if you want the user to input a value before entering
a page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel"
to proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel"
the box returns null.
Syntax
prompt("sometext","defaultvalue");
<!DOCTYPE html>
<html>
<head>
<title>Factorial Demo</title>
<script language="javascript">
var x=parseInt(prompt("Enter a number",""));
var fact=1,i;
for(i=1;i<=x;i++)
fact*=i;
document.write("<h1>Factorial of "+x+" is : "+fact+"</h1>");
</script>
</head>
<body>
</body>
</html>