0% found this document useful (0 votes)
47 views40 pages

JavaScript Notes

Uploaded by

Gungun tyagi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
47 views40 pages

JavaScript Notes

Uploaded by

Gungun tyagi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 40

What is Scripting?

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

API ➔ lib ➔ predefine programs


What scripting interfaces are available?
The most basic scripting interface developed at W3C is the DOM, the Document Object
Model which allows programs and scripts to dynamically access and updates the
content, structure and style of documents. DOM specifications form the core of
DHTML.

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-sidescript: 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

✓ In 1995, JavaScript was created by a Netscape developer named


“Brendan Eich”. First, it was called Mocha. Later, it was renamed
LiveScript.

✓ Netscape first introduced a JavaScript interpreter in Navigator2.

Mocha(1995) ➔LiveScript➔ JavaScript(1997)

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.
ECMAScript/ES JS
✓ Later JavaScript became an ECMA(European Computer Manufacturers
Association Script) (ES)standard in 1997. ECMAScript is the official name
of the language.

✓ JavaScript is implementation of ES; ES is the specification of JavaScript.


RBI ➔ SBI, HDFC,ICICI➔ customer
ES ➔JS ➔ Programmer

✓ JavaScript is originally it’s not programming language.


AJAX
JQuery
JSON
JavaScript
Angular
NodeJS
ReactJS
These tech & frameworks using JavaScript as their PL

➢ JavaScript is a Speed, light weight, Interoperability, Extended


Functionality, dynamic, loosely typed, single threaded, free ware
and open-source.

✓ JavaScript is an object-based or prototype-based programming.

✓ JavaScript is client-side (browser-side) programming. That means it


executes on the browser.
✓ It can also be used in server-side by using NodeJS
✓ JavaScript is a case sensitive programme.
✓ To work with JavaScript, we don’t need to install any software.
✓ JavaScript is “interpreter-based” programming, means the code will be
converted into machine language line-by-line. JavaScript interpreter is
already embedded in Browsers.
✓ JavaScript Translator is responsible to translate the JavaScript code
which is embedded in browser.
Parser’s:
Html code (high) => html parser => machine code
Css code (high) =>css parser => machine code
JS code (high) =>js parser => machine code

Every browser they have own JS engine:


V8 ➔Chrome and Opera.
SpiderMonkey➔Firefox.
Chakra➔IE
JavaScriptCore, and SquirrelFish➔ Safari
V8 ➔ Edge

Why we Use JavaScript?

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;

1. Client-side JavaScript does not allow reading and writing of files.


2. It cannot be used for networking applications.
3. It doesn't have any multithreading or multiprocessing capabilities.
4. it doesn't support db connections.

JavaScript Versions

Version Officeal Name Release Date


1 ECMAScript 1 June-1997

2 ECMAScript 2 June-1998

3 ECMAScript 3 Dec-1998
4 ECMAScript 4 2004 (not released)

5 ECMAScript 5 Dec-2009

5.1 ECMAScript 5.1 June-2011

6 ECMAScript June-2015

7 ECMAScript June-2016

8 ECMAScript June-2017

how many ways to imp js?


JS we can develop/imp in 3 ways, but in 4place.
those are:
➢ inline scripting
➢ internal scripting
➢ external scripting

> inline scripting


inline script nothing but writing code within the tag, by using event/dynamic
attributes
for this we need tag & event attribute
onclick, onsubmit, onfocus, oninput, onload, etc..
Syn: <tag attributes event="js code" event=”js” event=”js”>

>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>
<scripttype="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>

> external scripting


> external script is nothing but html code and javascript code designed in
separate files
>type js code in sep file and save that file with "filename.js"
>re-use
>while writing external script don’t use <script> tag and event attribute.

fun-name();

External file Syn:


function fun-name()
{
Steps
}
OR

{
Steps
}

Note: external file should be saved with an extension “.js”


>we canaccess external script by using <script> tag from html.
> from either head nor body section
Syn:
<script src="filename1.js"></script>
<script src="filename2.js"></script>
Comments in JavaScript
Comment is nothing but it is a statement which is not display on browser
window. It is useful to understand which code is written for what purpose.
Comments are useful in every programming language to deliver message.
It is used to add information about the code, warnings or suggestions so
that the end user or other developer can easily interpret the code.
Types of Comments:
There are two types of comments are in JavaScript
1. Single-line Comment ex: //comment
2. Multi-line Comment ex: /* comments */

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>

JS➔ operators, keyword/reserve words, functions/methods, classes,


objects

DOM => loading page


Window, document & console both are implicit objects created by
browser, @time loading a web page.
“window” is base object for all JS objects.
“window” object used for interacting with browser window.
“document” is the sub object of window.
“document” object used for interacting with web page/web document.
“console” object used for interacting with browser console. F12

Note: Every method should provided by an object

write() method: The write() method writes HTML expressions or javascript


code to a document without line breaking.
Syn: document.write(val1, val2, val3, …);
document.write(exp1 + exp2 + exp3 + ...);

writeln() method: The writeln() method writes HTML expressions or


javascript code to a document with line breaking.
Syn: document.writeln(exp1, exp2, exp3, ...);
document.writeln(exp1 + exp2 + exp3 + ...);

log() method: The log() method writes HTML expressions or javascript code
on browser’s console (press F12) with line break.
Syn: console.log(exp1,exp2,exp3, ...);
console.log(exp1 + exp2 + exp3 + ...);
Example:
<html>
<head>
<script type='text/javascript'>
document.write("<h1>hello world!</h1><p> have a nice day ! </p>");
</script>
</head>
</html>

Can we use HTML tags in write() method?


Yes, we can use tags in write().

writeln() method: The writeln() method is similar to the write method, with
the addition of writing a newline character after each statement.
Syn:document.writeln(exp1,exp2,exp3 ...)

Example:
<!DOCTYPE html>
<html>
<body>
<pre>
<script type='text/javascript'>
document.writeln("Welcome to JS");
document.writeln("Welcome to JS");
</script>
</pre>
</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>
JavaScript string with escape sequences: An escape character is consisting
of backslash "/" symbol with an alphabet. The following are frequently using
escape characters.
1. \n : inserts a new line
2. \t : inserts a tab space
3. \r : carriage return
4. \b : backspace
5. \f : form feed
6. \' : single quote
7. \”: double quote
8. \\ : Backslash

Difference between window.document.write&document.write:


There is no difference between these two statements,window is highest
level object. It contains child objects & their methods
child object/sub object
|
window.document.write();
| | |
browser page method

document.write();
| |
page method

browser is default object, master object, super object.


write() is a method related to document object

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.

JavaScript place in HTML file:


There is a flexibility given to include javascript code any where in a html
document but the follow ways are most prefered in the live environment.
➢ script in <head>-----</head> section
➢ script in <body>-----</body> section
➢ script in <body>-----</body>&<head>-----</head> section
➢ script in & external file & then include in <head>-----</head> section.

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.

how to run external js:


Creating javascript file:
document.write("<h1 style='color:blue'> welcome to external
javascript....!</h1>");
document.write("<br/>");
document.write("thank u----");
save with example.js extension @any location.

creating html files:


<html>
<head>
<script type="text/javascript" src="example.js"></script>
</head>
<body>
</body>
</html>
save with .html or .htm extensions.
Javascript code: It is a sequence of javascript statements, each statement is
executed by the browser in the sequence they are returned.
<head>
<script type="text/javascript">
document.write("<p>This is paragraph</p>") //js code
</script>
</head>

Javascript blocks: JavaScript sentences can be group together in blocks.


Blocks starts with a left curly bracket { and end with a right curly bracket }.
The purpose of your block is to make the sequence of statement excute
together.
<head>
<script type="text/javascript">
{
document.write(This is a block);
}
</script>
</head>
JavaScript dialog boxes: JavaScript has 3 kinds of dialog boxes.
1. Alert box alert()
2. Confirm box confirm()
3. Prompt box prompt()

window object

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.

How to display multiple line on the alert:


We cann't the use <br> tag here because alert is a method of the windows
object, that can’t be interpret html tag. Instead, we use the new line escape
character.
<head>
<script type="text/javascript">
- alert("javascript \n is\n a\n client-side \n programming \n
language");
</script>
</head>

ex: Alert with functions


<head>
<script type='text/javascript'>
functionmyAlert(){
alert("javascript \n is \n a \n client-side \n programming \n
language");
alert("1 \n \t 2 \n \t \t3");
}
</script>
</head>
<body>
<p> click the button to display alert messages ....</p>
<button onclick="myAlert()"> click me</button>
</body>

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>

ex: confirm with function


<head>
<script type='text/javascript'>
functionmyConfirm(){
var x=confirm("click ok or cancel");
alert("user selected option is:"+x);
if(x==true) {
alert("user clicked on ok button");
}
}
</script>
</head>
<body>
<p> click the button to display the user selected result..</p>
<button onclick="myConfirm()">confirm</button>
</body>

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>

Note: these 3methods are provided by window object.

External JavaScript with popup boxes:


step1: Create a required js file
functionMyAlert(){
alert("welcome to externaljs");
}
functionMyConfirm(){
confirm("click ok or cancel");
}
functionMyPrompt(){
prompt("Enter Any Value");
}

Save with .js extension @ any location....!!


step2: preparing required html file.
<html>
<head>
<script type="text/javascript" src="myscript.js">
</script>
</head>
<body>
<p>Click the button to display alert message..</p>
<button onclick="MyAlert()">Alert</button>
<p>click the button to display confirm message...</p>
<button onclick="MyConfirm()">confirm</button>
<p>click the button to display prompt value..</p>
<button onclick="MyPrompt()">prompt</button>
</body>
</html>
JS Naming Conventions
JS case: mixed
class name ➔TitleCase/Capitalilze
ex: SimlaGreenApple, YellowMango

fun/method ➔1st word is lowercase, rest of words(2-n) are


TitleCase/Capitalilze
ex: wirte(), log(), simlaGreenApple()

variables ➔ 1st word is lowercase, rest of words(2-n) are


TitleCase/Capitalilze
Ex: apple, simlaGreenApple

constants➔ uppercase
Ex: SIMLAGREENAPPLE, PI, EXP

Keyword/reversed ➔ lowercase
Ex: int, for, switch

JavaScript Reserved Words:


The following are reserved words in JavaScript. They cannot be used as JavaScript
variables, functions, methods, loop labels, or any object names.

abstract, boolean, break, byte, case, catch, char,class, const, continue,


debugger, default,delete,do, double, else, enum,export,extends,
false,final, finally,float, for, function, goto, if, implements, import,
instanceof, int, interface, let, long, native, new, null, package, private,
protected, public, return,short,static, super,switch, synchronized, this,
throw, throws,transient,true, try,typeof,var, void, volatile, while, with. 59

Variables
Variable is a reference name of a memory block.
Variables are created or stored in RAM( stack area).
Variables are used to store/to hold a value for reuse purpose.
Variables also used for auto substitution of values.

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.

We can use a variable directly without declaring it in javascript, it’s called


dynamic programming.

how to declare a variable?


we can define vars in JS Three ways, those are:
> by using "var" keyword
Syn: var varname;  declaration
OR
var varname=value; initialization

> by using "let" keyword (since js6) ES6


Syn: let varname;
OR
let varname=value;init

> by using "const" keyword (since js6) ES6


Syn: const varname=value;  initialization

Rules to declaring a variable


• Name should start with analphabet (a to z or A to Z), underscore( _ ),
or dollar($ ) sign.
• After first character we can use digits (0 to 9).
• variables are case sensitive. for example, a and A are different
variables.
• space is not allowed, means name should be single word.
• special chars (symbols) are not allowed in name, except _ and $.
• keywords we can't use as a name.

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

where do we declare variables?


We can declare variables in open script tag, with in function or within
block.

var let

global dec local dec

function scope function scope

no block scope block scope

hoisting sup not sup hoisting

re-definition sup not sup re-definition


Types of Variable in JavaScript

• Local Variable
• Outer/Global Variable

Local Variable

A variable which is declared inside block or function is called local variable.


It is accessible within the function or block only.

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 variablesare 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>

Declaring global variable through window object


The best way to declare global variable in javascript is through the window
object.
Syntax
window.var=value;
Now it can be declared inside any function and can be accessed from any
function.

For example:
function m()
{
window.value=200; //declaring global variable by window object
}
function n()
{
alert(window.value); //accessing global variable from other function
}
In JS we can declare the variables the following two ways.
1. Implicit declaration
2. Explicit declaration

Implicit declaration: In every scripting it is the default declaration.


ex: y=100;

Explicit declaration: All programming languages default declaration


ex: int a=5;

Scripts are able to support implicit declaration but languages are only
explicit declaration.
Note: Explicit declaration is always recommended as a good programming
practice.

Javascriptdatatypes:
In javascript data types are classified into the following two cat.
1. Primitive datatypes
2. non-primitive datatypes

Primitive data types: Primitive data types allow storing data directly.
These data types allow us to store only 1 value @time.
These are popularly known as non-reference
Javascript has a five primitive data types.
1. string Ex: "siva" 'apples123' "Dno: 1-2-3/1a"
2. number Ex: 10 -25 100.56 -3.7
3. boolean Ex: true false
4. undefined Ex: value not assigned or data type is not identified
5. object Ex: null { }

Non-primitivedatatypes: Non-primitive datatypes allow to store


reference(address) of data.
These datatypes allow us to store more than 1 value @time.
These are popularly known as reference or composite data types.
Ex: class, array

var st1 = new String();

Primitive data types:


Strings: In javascript a String should be within a singleordouble quote.
var name="nit";
var name='nit';
Number: Javascript has only one type of numbers,they can be return with
or without decimals
var x1=34.00; with decimals
var x2=34 without decimals

Boolean: It is used to represent a Boolean value,These are as follows.


var x = true //equivalent to true, yes or on
var y = false //equivalent to false, no or off

undefined: It is a value of variable with no value.


var x; //now x is undefined

Null: variables can be emptied by setting the value to null.


ex: var x=null; //now x is null

typeof
typeof is predefine function, and it's used to identify data type of a variable
or value.
Syn: typeof var-name
typeof value
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

<!-- example on variable declaration -->


<!DOCTYPE html>
<html lang="en">
<head>
<title>JS Ex13</title>
</head>
<body>
<h1>Demo on difference between var and let</h1>
<script>
var a=10; //define
document.write(a +"<br>");
var a=20.56; //re-defination
document.write(a +"<br>");
var a="apple"; //re-defination
document.write(a +"<br>");

let n=101; //define


document.write(n +"<br>");
//let n=202; re-defination ==> Error: Identifier 'n' has already been
declared
n=202; //changing value
document.write(n +"<br>");
</script>
</body>
</html>
Non-primitive data types: When a variable is declared with the keyword
new, the variable is an object.
new is used for dynamic memory allocations (for creating objectsand
arrays).
these datatypes are also called as reference datatype.
Ex:
var st=newString();
var x=newNumber();
let y=newBoolean();
let a = [ ];
here LHS are reference variables, and RHS are objects.
reference variables are storing address of dynamic memory (object)

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

Javascript supports the following list of operators:


➢ arithmetic operators
➢ relational operators
➢ logical operators
➢ assignment operators
➢ incre/decre operators
➢ ternary operator
➢ Concatenation operator etc...

Arithmetic operators: using these operators we can perform the basic math
calculations.
operators are:
operator Description example
+ addition j+12
- subtraction j-22
* multiplication j*7
/ division j/3
% modulus j%6
** power x**y

relational operators: these operators are used to provide comparison


between two operands. these are Boolean operators (true/false).
operators are:
operator Description example
== is equal to j==42
!= is not equal to j!=17
> is greater than j>0
< is less than j<100
>= is greater than or equal to j>=23
<= is less than or equal to j<=13
=== a===b
!== a!==b

Logical operators: these operators are used to perform multiple


comparisons @time. these are Boolean operators (true/false).
operators are:
operator Description example
&& And j==1 && k==2
|| OR j<100 || j>0
! Not !(j==k)
assignment operators: these operators are used to store/assign value.
operatoris:
operator Description example
= store a=10
shorthand:
+= addition & assign a+=10
-= subtract & assign a-=5
*= product & assign a*=20
/= division & assign a/=7
%= modulus & assign a%=6
>>= <<= &= |=

unary operators: these operators are used to increment or to decrement a


value. operators are ++ and --
++ (increment) ==> it adding 1 to an existing value Ex: a++ or ++a
-- (decrement) ==> it subtracting 1 from an existing value Ex: a-- or --a

ternary operator: this operator is used to decision making operation.


operator is ?:, this operator also called as conditional operator.
(condition) ? statement1 : statement2

Concatenation operator: this operator is used to concatenation multiple


strings then formed into a single string. one operand should be string to
perform concatenation. Resultant value comes in string format.
operator is +.
Ex: "rama"+"rao” ==> "ramarao"
"mangos"+123 ==> "mangos123"
true+”siva” ➔ “truesiva”
parseInt()

predefine function => window


text based int converts into number format
"100" ➔100
"10.78" ➔10
"rama" ➔NaN (Not a Number)
Syn:
window.parseInt("value")

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")

Note: both are global functions


Control Statement
control statements are used to control(change) execution flow of program
based on user input data.
types:
> Conditional statements (dm)
> loops (iterations)
> Un-conditional (branching)

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.

There are three forms of if statement.


• simple if
• If else
• if else if (ladder if)

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.

Example of ifelse statement


<script>
var a=40;
if(a%2==0)
{
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
Result
a is even number
JavaScript If...else if statement
It evaluates the content only if expression is true from several expressions.

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.

Example of while loop


<script>
var i=10;
while (i<=13)
{
document.write(i + "<br/>");
i++;
}
</script>

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.

Example of do-while loop


<script>
var i=11;
do{
document.write(i + "<br/>");
i++;
}while (i<=15);
</script>
for Loop
For loop is a simplest loop first we initialized the value then check
condition and then increment and decrements occurred.

Steps of for loop

Example of for loop


<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
Unconditional statements
These are used to jump/skip statements execution
Types:
➢ break
➢ continue
➢ return

<noscript> tag: It is used to provide an alternate contains for users when


script is disabled or not supporting, It is a paired tag. It is always declared
within the body section.
syntax: <noscript>------</noscript>
ex:
<head>
<script type='text/javascript'>
alert("welcome to js");
</script>
</head>
<body>
<noscript>
<p style='color:red'>oops your browser not supporting javascript
update/change the script settings and try..</p>
</noscript>
</body>

You might also like