0% found this document useful (0 votes)
528 views

Basics of JavaScript

The document provides an overview of JavaScript basics, including what JavaScript is, its features, applications, and examples. JavaScript is a scripting language used to add interactivity to HTML pages. It is supported by all major browsers and can be embedded directly into HTML or use external JavaScript files. The document discusses JavaScript variables, data types, operators, conditional statements, and functions.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
528 views

Basics of JavaScript

The document provides an overview of JavaScript basics, including what JavaScript is, its features, applications, and examples. JavaScript is a scripting language used to add interactivity to HTML pages. It is supported by all major browsers and can be embedded directly into HTML or use external JavaScript files. The document discusses JavaScript variables, data types, operators, conditional statements, and functions.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 60

JavaScript Basics

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> 

 The script tag specifies that we are using JavaScript.

 The text/javascript is the content type that provides information to the


browser about the data.

 The document.write() function is used to display dynamic content through


JavaScript. We will learn about document object in detail later.
Where to Put the JavaScript
1. Scripts in <head> 2. Scripts in <body>
3. Using an External JavaScript
<head>
<script type="text/javascript">
....
</script>
</head>
<body>
<script type="text/javascript">
....
</script>
</body>
<head>
<script type="text/javascript" src=“abc.js"></script>
</head>
External JavaScript file
 We can create external JavaScript file and embed it in
many html page.
 It provides code reusability because single JavaScript file
can be used in several html pages.
 An external JavaScript file must be saved by .js extension.
 It is recommended to embed all JavaScript files into a
single file.
 It increases the speed of the webpage.
Example of External file

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

Comments can be added to explain the JavaScript, or to


make the code more readable.
Single Line & Multiline 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";

Redeclaring JavaScript Variables


If you redeclare a JavaScript variable, it will not lose its
original value.
var x=5;
var x;
Example of JavaScript variable
<html> Output
<body> 30
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
</body>
</html>
JavaScript local variable
 A JavaScript local variable
is declared inside block or
function.
 It is accessible within the
 OR
function or block only.
 For example: <script>  
If(10<13){  
<script>  
var y=20;//JavaScript local va
function abc(){   riable  
var x=10;//local variable   }  
}   </script>  
</script>
JavaScript global variable
<script>  
 A JavaScript global
var data=200;//gloabal variable  
variable is accessible
function a(){  
from any function.
document.writeln(data);  
}  
 A variable i.e. declared function b(){  
outside the function or document.writeln(data);  
declared with window }  
object is known as global a();//calling JavaScript function  
variable. b();  
</script>  
 For example:
Javascript Data Types
 JavaScript provides different data types to hold different types
of values. There are two types of data types in JavaScript.
 Primitive data type
 Non-primitive (reference) data type

 JavaScript is a dynamic type language, means you don't need


to specify type of the variable because it is dynamically used
by JavaScript engine.
 Use var to specify the data type. It can hold any type of values
such as numbers, strings etc.
 var a=40;//holding number  
 var b="Rahul";//holding string  
JavaScript primitive data types
 There are five types of primitive data types in JavaScript.
They are as follows:
JavaScript non-primitive data type
JavaScript Operators
 JavaScript operators are symbols that are used to perform
operations on operands. 
 var sum=10+20;  
 There are following types of operators in JavaScript.
 Arithmetic Operators
 Comparison (Relational) Operators
 Bitwise Operators
 Logical Operators
 Assignment Operators
 Special Operators
JavaScript Arithmetic Operators
Given that y=5, the table below explains the arithmetic operators:

Operator Description Example Result

+ Addition x=y+2 x=7

- Subtraction x=y-2 x=3

* Multiplication x=y*2 x=10

/ Division x=y/2 x=2.5

% Modulus (division x=y%2 x=1


remainder)
++ Increment x=++y x=6

-- Decrement x=--y x=4


JavaScript Assignment Operators
Given that x=10 and y=5, the table below explains the assignment operators:

Operator Example Same As Result

= x=y   x=5

+= x+=y x=x+y x=15

-= x-=y x=x-y x=5

*= x*=y x=x*y x=50

/= x/=y x=x/y x=2

%= x%=y x=x%y x=0


JavaScript Comparison Operators
Given that x=5, the table below explains the comparison operators:

Operator Description Example

== is equal to x==8 is false

=== is exactly equal to (value and x===5 is true


type) x==="5" is false

!= is not equal x!=8 is true

> is greater than x>8 is false

< is less than x<8 is true

>= is greater than or equal to x>=8 is false

<= is less than or equal to x<=8 is true


JavaScript Logical Operators
Given that x=6 and y=3, the table below explains the logical operators:

Operator Description Example

&& and (x < 10 && y > 1) is true

|| or (x==5 || y==5) is false

! not !(x==y) is true


JavaScript Bitwise Operations
Example
JavaScript Special Operators
JavaScript Conditional Operator
JavaScript also contains a conditional operator that
assigns a value to a variable based on some condition.
Syntax

variablename=(condition)?value1:value2 

Example

greeting=(visitor=="PRES")?"Dear President ":"Dear ";


The + Operator Used on Strings
The + operator can also be used to add string variables or text
values together. To add two or more string variables together,
use the + operator.
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
After the execution of the statements above, the variable txt3
contains "What a verynice day".
To add a space between the two strings, insert a space into one
of the strings:
txt1="What a very";
txt2="nice day";
txt3=txt1+" "+txt2;
After the execution of the statements above, the variable txt3
contains:
"What a very nice day"
Adding Strings and Numbers
The rule is: If you add a number and a string, the result will be a string!

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:

 if statement - use this statement to execute some code


only if a specified condition is true

 if...else statement - use this statement to execute


some code if the condition is true and another code if the
condition is false

 if...else if....else statement - use this statement to


select one of many blocks of code to be executed

 switch statement - use this statement to select one of


many blocks of code to be executed
If Statement
Use the if statement to execute some code only if a specified condition is true.

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

• The JavaScript loops are used to iterate the piece of code using for, while,


do while or for-in loops. It makes the code compact. It is mostly used in
array.
• There are four types of loops in JavaScript.

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
}

The while loop


The while loop loops through a block of code while a specified condition is true.
Syntax
while (var<=endvalue)
  {
  code to be executed
  }
Example of for loop
<!DOCTYPE html>
<html>
<body>
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
</body>
</html>
Example of While loop
<!DOCTYPE html>
<html>
<body>
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
</body>
</html>
The do...while Loop

•The do...while loop is a variant of the while loop.

•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.

 Code reusability: We can call a function several times so it


save coding.
 Less coding: It makes our program compact. We don’t need to
write many lines of code each time to perform a common task.
JavaScript Functions
•To keep the browser from executing a script when the page loads, you
can put your script into a function.

•A function contains code that will be executed by an event or by a call


to the function.

•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).

•Functions can be defined both in the <head> and in the <body>


section of a document.

•However, to assure that a function is read/loaded by the browser


before it is called, it could be wise to put functions in the <head>
section.
Syntax
function functionname(var1,var2,...,varX)
{
some code
}
JavaScript Function Example
Example
<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!"
onclick="displaymessage()" />
</form>
</body>
</html>
The return Statement
The return statement is used to specify the value that is returned from the function.

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>

You might also like