JS Basics Notes
JS Basics Notes
JS Basics Notes
A script is program code that doesn’t need pre-processing (e.g. compiling) before
being run. In the context of a Web browser, scripting usually refers to program code
written in JavaScript that is executed by the browser when a page is loaded, or in
response to an event triggered by the user.
Scripting can make Web pages more dynamic. For example, without reloading a new
version of a page it may allow modifications to the content of that page, or allow
content to be added to or sent from that page. The former has been called DHTML
(Dynamic HTML), and the latter AJAX (Asynchronous JavaScript and XML).
Modifications of the content using the DOM by the user and by scripts trigger events
that developers can make use of to build rich user interfaces.
Types of script: Scripts are classified into the following two types.
Client-side script
Server-side script
Client-side script: These scripts are getting executed within the web Browser
(client). Here we don’t need any software. These scripts are used for client-side
validations (data verification & data validations)
Ex: JavaScript, VBScript, typescript, etc…
Server-side script: A script which executes in server machine with support of the
web-server/app-server software’s like IIS(Internet information services), Tomcat,
JBOSS, etc.These scripts are used for server-sidevalidations (authentication &
authorization).
Ex:php, jsp, asp.net, nodeJS, cgi, perletc…
What are the differences between script and language?
Script Language
Weakly or loosely typed programming Strong or closely typed programming and HW
And lightweight
Easy to understand compare to PL Complex to understand compare to Script
External libraries not required Required
No special compiler required Special compiler mandatory
Client side validation Server/client side validation/verifications
Ex: JavaScript, VBScript,TypeScript, Perl, Shell Ex: C, CPP, vb.net, Java etc.
etc.
JavaScript Introduction
Using HTML/CSS, we can only design a web page but it’s not supported to
perform logical operations such as calculations, decision making and
repetitive tasks, dynamically displaying output, reading inputs from the
user, and updating content on webpage at client side. Hence to perform
these entire tasks at client side we need to use JavaScript.
Where it is used?
There are so many web applications running on the web that are using
JavaScript like Google, Facebook,twitter, amazon, YouTube etc.
It is used to create interactive websites. It is mainly used for:
1. Client-side verifications and validation
2. Dynamic drop-down menus
3. Displaying date and time
4. Build forms that respond to user input without accessing a server.
5. Displaying popup windows and dialog boxes (like alert dialog box,
confirm dialog box and prompt dialog box)
6. Manipulate HTML "layers" including hiding, moving, and allowing the
user to drag them around a browser window.
etc...
Limitations of JavaScript
Client-SideJavaScript have some limitations which are given below;
JavaScript Versions
Version Officeal Name Release Date
1 ECMAScript 1 June-1997
2 ECMAScript 2 June-1998
3 ECMAScript 3 Dec-1998
6 ECMAScript June-2015
7 ECMAScript June-2016
8 ECMAScript June-2017
>internal scripting
Internal script is nothing but html code and javascript code both are placed in the
same file, but not in same line.
Internal script must be implemented inside <script> tag, <script> is a paired tag.
> scripting in head sec
head is first executed part of html, hence javascript is also executes first.
<head>
<script type="text/javascript”>
JS code
</script>
</head>
> scripting in body sec
body level script is executed after head section
<body>
<script type="text/javascript”>
JS code
</script>
</body>
fun-name();
{
Steps
}
Single-line Comment
It is represented by double forward slashes //. It can be used before any
statement.
Example:
<script>
// It is single line comment
document.write("Hello Javascript");
</script>
Multi-line Comment
It can be used to add single as well as multi line comments.
It is represented by forward slash / with asterisk * then asterisk with
forward slash.
Example:
<script>
/* It is multi line comment.
It will not be displayed */
document.write("Javascript multiline comment");
</script>
Example:
<html>
<head>
<script type='text/javascript'>
document.write("<h1>hello world!</h1><p> have a nice day ! </p>");
</script>
</head>
</html>
Note: You have to place writeln() in pre tag to see difference between
write() and writeln().
Writeln() actually produces the output in new line (\n) but browser will
not detect the \n as linebreak, hence to show it correctly and keep
format as it is we will use pre tag.
Example:
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
document.write("<h1 style='color:blue; font-size:30px; font-
family:tahoma'> Welcome To JS</h1>");
document.write("<font color='green' size='16px' face='Arial'> Welcome
To JS</font>");
</script>
</head>
<body>
</body>
</html>
Note:
the above type of code is known as DHTML
In JavaScript a string should be in single or double quotes.
Double quotes inside using single quotes are valid, single quotes
inside using double quotes valid.
Example
<!DOCTYPE html>
<html>
<body>
<script>
document.write("JavaScript is client side script");
document.write("<br>");
document.write("JavScript is 'ECMA' Implementation<br>");
document.write('JavScript released by NetScape<br>');
document.write('NetScape release "Mocha"<br>');
//document.write('NetScape release 'Mocha'<br>'); Error
//document.write("NetScape release "Mocha"<br>"); Error
</script>
</body>
</html>
document.write();
| |
page method
ex:
<head>
<script type='text/javascript'>
window.document.write("livescript is javascript");
document.write("<br>");
document.write('livescript is javascript');
</script>
</head>
JavaScript semicolon(;):
In javascript every statements ends with semicolon(;). It is an optional
notation.
ex:
<head>
<script type='text/javascript'>
document.write=("livescript is javascript");
</script>
</head>
ex:
<head>
<script type='text/javascript'>
document.write("javascript");
document.write('livescript');
document.write('livescript is javascript');
</script>
</head>
Note:
1) In the above script semicolon(;) is mandatory.
2) It is a good programming practice to use the semicolon.
ex:
<head>
<script type='text/javascript'>
document.write("welcome to head section");
</script>
</head>
<body>
<script language="javascript">
document.write("welcome to the body section");
</script>
</body>
External javascript:
Javascript can also be placed in a external files,these files contains
javascript code. This code we can apply on different webpages. External
javascript files extensions is .js
Note:
1) External script cann't contain the <script></script> tags.
2) To use an external script,point to the .js file in the "src" attribute of the
<script> tag.
Java script did not provide any data types for declaring variables and a
variable in javascript can store any type of value. Hence java script is
loosely typed programme.
for example:
var eid; var 1a;
var total; var a1;
var _b; var book id;
var a@; var studentid;
var #b; var case;
var book_id; var a$1
<script>
var a=10;
var b=20;
var c=a+b;
document.write(c);
</script>
Output 30
Types of Variable in JavaScript
Local Variable
Outer/Global Variable
Local Variable
For example:
<script>
functionabc()
{
var x=10; //local variable
}
</script>
or
Example
<script>
If(10<13)
{
var y=20;//javascript local variable
}
</script>
Global Variable
var is declared with in script tag but outside function & block those are
global variables.
these global variables are accessible from anywhere in program.
declared with window object is known as global variable.
For example:
<script>
var value=10;//global variable
function a()
{
alert(value);
}
function b()
{
alert(value);
}
</script>
For example:
function m()
{
window.value=200; //declaring global variable by window object
}
function n()
{
alert(window.value); //accessing global variable from other function
}
Scripts are able to support implicit declaration but languages are only
explicit declaration.
Note: Explicit declaration is always recommended as a good programming
practice.
Javascript datatypes:
In javascript data types are classified into the following two cat.
1. Primitive datatypes
2. non-primitive datatypes
Dynamic data types: Javascript has dynamic types.This means that the
same variable can be used as different types.
ex:
var x; //now x is undefined
var x=5; // now x is a number
var x="ram"; // now x is a String
JavaScript operators
operator is a symbol (special char) and it is used to perform certain
operation(task).
every operator is a symbol, but every symbol is not operator.
every operator requires some values, those are called as operands.
Ex:
Expression
Its combination of one operator and some operands
Cat:
Unary it req one operand
Binary it req two operands
o Arithmetic
o Relational
o Logical
o Bitwise
o Assignment
o Concatenation
Ternary it req three operands
operators are:
operator Description example
+ addition j+12
- subtraction j-22
* multiplication j*7
/ division j/3
% modulus j%6
** power x**y xy
And Or Not
Cond1 Cond2 Result Cond1 Cond2 Result Cond Result
T T T T TT T F
T F F T F T F T
F T F F T T
F F F F FF
Alert box: An alert box is often used if you want to make sure information
comes through the user. When an alert box pops up, the user will have to
click "ok" to proceed.
Syn: window.alert("message"/expr);
ex:
<body>
<script type='text/javascript'>
alert("invalid entry");
</script>
</body>
Note:html tags we can’t use in alert() function.
confirm box:
It is often used, if you want the user to verify and 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: window.confirm("message");
ex:
<head>
<script type='text/javascript'>
confirm("click ok or cancel");
</script>
</head>
ex:
<head>
<script type='text/javascript'>
var x=confirm("click ok or cancel");
alert("user selected option is:"+x);
</script>
</head>
ex:
<head>
<script type='text/javascript'>
var x=confirm("click ok or cancle");
alert("user selected option is:"+x);
if(x==true) {
alert("user clicked on OK button");
}
else{
alert("user clicked on cancel button");
}
</script>
</head>
Dynamic
o While execute of program(after webpage open) assigning
values to vars
o This given by user
o This always changing, means data changing the data
execution to execution
o We can take the data from user, in two ways:
Html input elements (UI/html forms)
Prompt dialog
Prompt Box: It is used to, if you want the user to input a value while
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 value/empty. If the user clicks "cancel" the
box returns "null".
Syntax: window.prompt("sometext", defaultvalue);
ex:
<head>
<script type='text/javascript'>
prompt("Enter Any Number:");
</script>
</head>
ex:
<head>
<script type='text/javascript'>
varMyVal=prompt("Enter Any Number:");
alert("User Entered value is:"+MyVal);
</script>
</head>
parseFloat()
predefine function => window
text based float converts into number-based float
“100" 100.0
"10.78" 10.78
"rama" NaN (Not a Numeric)
Syn:
window.parseFloat("value")
Conditional Statements:
If Statement
The if statement is used to perform decision making operations. means if
condition is true, it executes some statements. if condition is false, it
executes some other statements.
If statement
if is most basic statement of Decision-making statements. It tells to
program to execute a certain part of code only if particular condition or
test case is true.
Example
<script>
var a=10;
if(a>5)
{
document.write("value of a is greater than 5");
}
</script>
if-else statement
In general, it can be used to execute one block of statement among two
blocks.
Syntax
if(expression1)
{
//content to be evaluated if expression1 is true
}
else
if(expression2)
{
//content to be evaluated if expression2 is true
}
else
{
//content to be evaluated if no expression is true
}
Example of if..else if statement
<script>
var a=40;
if(a==20)
{
document.write("a is equal to 20");
}
else if(a==5)
{
document.write("a is equal to 5");
}
else if(a==30)
{
document.write("a is equal to 30");
}
else
{
document.write("a is not equal to 20, 5 or 30");
}
</script>
switch statement
> switch is selection statement, but it's not decision making.
> its better performance.
Syn:
switch(var/expr)
{
case value: statements...
break;
case value: statements...
break;
case ...
default: statements...
}
Looping Statement
Set of instructions given to the interpreter to execute until condition
becomes false is called loops. The basic purpose of loop is min code
repetition.
The way of the repetition will be forming a circle that's why repetition
statements are called loops. Some loops are available In JavaScript which
are given below.
while loop (top testing/entry level)
for loop
do-while (bottom testing/exit level)
while loop
When we are working with “while loop” always pre-checking process will
be occurred. Pre-checking process means before evolution of statement
block condition part will be executed. “While loop” will repeat in clock
wise direction or anti-clock wise direction.
do-while loop
In implementation when we need to repeat the statement block at least 1
then go for do-while. In do-while loop post checking of the statement
block condition part will be executed.