0% found this document useful (0 votes)
43 views146 pages

SL Unit-1

Uploaded by

Priyanka Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views146 pages

SL Unit-1

Uploaded by

Priyanka Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 146

Unit-1

Introduction to Scripting Languages


• All scripting languages are programming languages.
• The scripting language is basically a language where
instructions are written for a run time environment.
• A scripting language is a programming language designed for
integrating and communicating with other programming
languages.
• They do not require the compilation step and are rather
interpreted.
• There are many scripting languages some of them are
• bash:
1.It is a scripting language to work in the Linux interface.
2. It is a lot easier to use bash to create scripts than other programming
languages.
3 It describes the tools to use and code in the command line and create
useful reusable scripts.
• Node js:
1.It is a framework to write network applications using JavaScript.
2. Corporate users of Node.js include IBM, LinkedIn, Microsoft,
Netflix, PayPal, Yahoo for real-time web applications.
• Ruby:
1.It is a scripting and object oriented programming language.
2. Ruby’s flexibility has allowed developers to create innovative software.
3. It is a scripting language which is great for web development.
• Python:
1. It is easy, free and open source.
2. It supports procedure-oriented programming and object-
oriented programming.
3. Python is an interpreted language with dynamic semantics
language and huge lines of scripted code it comes with build
in functions.
• Perl:
1. A scripting language with innovative features to make it
different and popular. Found on all windows and Linux servers.
2. It helps in text manipulation tasks. High traffic websites that use
Perl extensively include priceline.com, IMDB.
Application of Scripting Languages:

Scripting languages are used in many areas:


• Scripting languages are used in web applications.
• They are used in server side as well as client side.
• Server side scripting languages are: JavaScript, PHP, Perl etc. and
client side scripting languages are: JavaScript, perl,AJAX, jQuery
etc.
• Scripting languages are used in system administration. For example:
Shell, Perl, Python scripts etc.
• It is used in Games application and Multimedia.
• It is used to create plug-in and extensions for existing applications.
Advantages of scripting languages:

• Easy learning: The user can learn to code in scripting languages


quickly, not much knowledge of web technology is required.

• Fast editing: It is highly efficient with the limited number of data


structures and variables to use.

• Interactivity: It helps in adding visualization interfaces and


combinations in web pages. Modern web pages demand the use of
scripting languages. To create enhanced web pages, fascinated visual
description which includes background and foreground colors and
so on.
• Functionality: There are different libraries which are part of
different scripting languages. They help in creating new applications
in web browsers and are different from normal programming
languages.
WHAT IS A SCRIPTING LANGUAGE
• Scripting Languages are programming languages that are
generally interpreted at runtime.
• Scripting languages help in automating various software apps,
web pages in a browser, shell usage of an OS (operating
system), etc.
• The scripting languages like VBScript, Perl, JavaScript, etc.,
do not require compilation.
• They have less access to any computer’s native abilities. It is
because these rather run on an original programming
language’s subset. An example here could be that the
Javascript won’t have the ability to access your file system.
• A scripting language is interpreted. It doesn’t primarily focus
on building applications- but it can render behavior to an
application that already exists.
• It basically helps in writing codes for targeting a software
system. Thus, it can also automate a given operation on any
software system. So basically, scripts act as a set of
instructions that target any software system.
• Scripting languages support "script," which is small program
written for a specific runtime environment.
Programming language
• programming languages are set of instructions or code which tells a
computer what it needs to do.
• Programming languages are high-level languages that need to be
converted into machine level language because a computer can only
understand machine level language or binary language (0 and 1).
• we write the instructions in human-readable form and then we hit
the compile button to convert this into machine level language
which a computer can understand and then the computer performs
the task. This conversion is done by the compiler which scans the
complete code in one go and if it finds any error it immediately
throws all errors.
• Examples are Java, C, C++, C#. Programming languages are most
widely used to make software or drivers.
Applications of Programming languages

• Programming languages are mainly used to create


different software and applications such as MS Excel,
PowerPoint, etc.
• These are used for transforming the data, for
example, solving a set of equations from a set of
conditions.
Differences between Scripting and Programming Languages

Parameters Scripting Language Programming Language

Language Type The scripting languages The programming


are interpreter-based languages are compiler-
languages. based languages.

Use The scripting languages The programming


help in combining the languages help in
existing components of an developing anything from
application. scratch.

Running of Language A user needs to run Programming languages


scripting languages inside are program-independent.
an existing program. Thus,
it’s program-dependent.
Parameter Scripting language Programming languages

Conversion Scripting languages convert Programming languages help in


high-level instructions into converting the full program
machine language. into the machine language (at
once).

Compilation You don’t need to compile These languages first need a


these languages. compilation.

Design These make the coding process These provide full usage of the
simple and fast. languages.

File Type Scripting languages don’t Programming languages create


create any file types. .exe files.

Complexity These are very easy to use and These are pretty complex in
easy to write. terms of writing and usage.
Type of Coding Scripting languages help Programming languages
write a small piece of an help write the full code
Parameter Scripting language Programming languages
entire code. concerning a program.

Developing Time These take less time because These take more time
they involve lesser code. because a programmer must
write the entire code.

Interpretation We usually interpret a The compile results of a


scripting language in programming language are
another program. stand-alone. No other
program needs to interpret
it.

Requirement of Host Scripting languages require Programming languages are


hosts for execution. self-executable. They don’t
require any host.

Length of Codes These involve very few and These require numerous
short coding lines. lines of coding for a single
function.
Web Scripting
• The process of creating and embedding scripts in a web page is
known as web-scripting.
• A script or a computer-script is a list of commands that are
embedded in a web-page normally and are interpreted and executed
by a certain program or scripting engine.
• Scripts may be written for a variety of purposes such as for
automating processes on a local-computer or to generate web pages.
• The programming languages in which scripts are written are called
scripting language, there are many scripting languages available
today.
• Common scripting languages
are VBScript, JavaScript, ASP, PHP, PERL, JSP etc.
Types of Script
• Scripts are broadly of following two type :
Client-Side Scripts , Server-Side Scripts
Client-Side Scripts :
1. Client-side scripting is responsible for interaction within a web
page.
2. The client-side scripts are firstly downloaded at the client-end and
then interpreted and executed by the browser (default browser of the
system).
3. The client-side scripting is browser-dependent. i.e., the client-side
browser must be scripting enables in order to run scripts.
4. Client-side scripting is used when the client-side interaction is used.
Some example uses of client-side scripting may be :
1. To get the data from user’s screen or browser.
2. For playing online games.
3. Customizing the display of page in browser without reloading or
reopening the page.
• Here are some popular client-side scripting languages VBScript,
JavaScript, Hypertext Processor(PHP).
Server-Side Scripts :
1. Server-side scripting is responsible for the completion or
carrying out a task at the server-end and then sending the result
to the client-end.
2. In server-side script, it doesn’t matter which browser is being
used at client-end, because the server does all the work.
3. Server-side scripting is mainly used when the information is
sent to a server and to be processed at the server-end.
4.Some sample uses of server-scripting can be :
• Password Protection.
• Browser Customization (sending information as per the
requirements of client-end browser)
• Form Processing
• Building/Creating and displaying pages created from a database.
• Dynamically editing or adding content to a web-page.

5. Here are some popular server-side scripting languages PHP, Perl, ASP
(Active Server Pages), JSP ( Java Server Pages).
JAVA SCRIPT
• JavaScript is the Programming Language for the
Websites.
• The first scripting language was introduced by
Brendan Eich in 1996
• JavaScript is an object-based scripting language
which is lightweight and cross-platform.
• JavaScript can update and change both HTML and
CSS.
• JavaScript can calculate, manipulate and validate
data.
Features of JavaScript

There are following 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 a weakly typed language, where certain
types are implicitly cast (depending on the
operation).
• 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 - Syntax

• JavaScript can be implemented using JavaScript statements


that are placed within the <script>... </script> HTML tags in a
web page.
• You can place the <script> tags, containing your JavaScript,
anywhere within your web page, but it is normally
recommended that you should keep it within the <head> tags.
• The <script> tag alerts the browser program to start
interpreting all the text between these tags as a script.
• A simple syntax of your JavaScript will appear as follows.
<script ...> JavaScript code </script>
<script language = "javascript" type = "text/javascript">
JavaScript code </script>
The script tag takes two important attributes −
• Language − This attribute specifies what scripting language
you are using. Typically, its value will be javascript.
• Type − The text/javascript is the content type that provides
information to the browser about the data.
• Its value should be set to "text/javascript".
JavaScript Example
program1:
<html>
<body>
<h2>Welcome to JavaScript</h2>
<script>
document.write("Hello JavaScript ");
</script>
</body>
</html>
Output:
Welcome to JavaScript
Hello JavaScript
JavaScript provides 3 places to put the JavaScript code:

1.Between the body tag of html

2.Between the head tag of html

3. In .js file (external JavaScript)


JavaScript Example : code between the body tag

P2:
<html>
<body>
<script type="text/Javascript">
alert("Hello JavaScript");
</script>
</body>
</html>
Output:
JavaScript that displays alert dialog box.
Output screen
2) code between the head tag

• In this example, we are creating a function


msg(). To create function in JavaScript, you
need to write function with function_name as
given below.
• To call function, you need to work on event.
Here we are using onclick event to call msg()
function.
Program3:

<html>
<head>
<script type="text/javascript">
function msg()
{
alert("Hello Javascript");
}
</script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
Output screen
External JavaScript file

• We can create external JavaScript file and


embed it in many html page.
• It provides code re usability 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.
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>
message.js

function msg(){
alert("Hello Javascript");
}
Output screen
Advantages of External JavaScript

• There will be following benefits if a user creates an


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 parallels 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.
JavaScript Comment

There are two types of comments in JavaScript.


• Single-line Comment(It is represented by double forward
slashes (//). It can be used before and after the statement).
• Multi-line Comment
<html>
<body>
<script>
// It is single line comment
document.write("hello javascript");
</script>
</body>
</html>
JavaScript Multi line Comment

Synyax
/* your code here */
<html>
<body>
<script>
/* It is multi line comment.
It will not be displayed */
document.write("example of javascript multiline comment");
</script>
</body>
</html>
JavaScript Display Possibilities
JavaScript can "display" data in different ways:
• Writing into an HTML element, using innerHTML.
• Writing into the HTML output using document.write().
• Writing into an alert box, using window.alert().
• Writing into the browser console, using console.log().

Using innerHTML
• To access an HTML element, JavaScript can use
the document.getElementById(id) method.
• The id attribute defines the HTML element. The innerHTML property
defines the HTML content:
• The innerHTML property can be used to write the dynamic html on the
html document.
• It is used mostly in the web pages to generate the dynamic html such as
registration form, comment form, links etc.
innerHTML

<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
Output:
My First Web Page
My First Paragraph.
11
Properties of document object
Methods of document object
document.write()
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
document.write(5 + 6);
</script>

</body>
</html>
Javascript -
document.getElementById() method
<script type="text/javascript">
function getcube()
{
var number=document.getElementById("number").value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>
Using window.alert()
• You can use an alert box to display data:

<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
window.alert(5 + 6);
</script>

</body>
</html>
JavaScript Debugging

• Sometimes a code may contain certain mistakes. Being a scripting


language, JavaScript didn't show any error message in a browser.
But these mistakes can affect the output.
• The best practice to find out the error is to debug the code. The code
can be debugged easily by using web browsers like Google Chrome,
Mozilla Firebox.
Here, we will find out errors using built-in web browser debugger.
To perform debugging, we can use any of the following approaches:
• Using console.log() method
• Using debugger keyword
Using console.log() method

• The console.log() method displays the result in the console of the


browser. If there is any mistake in the code, it generates the error
message.
Example :
<script>
x = 10;
y = 15;
z = x + y;
console.log(z);
console.log(a);//a is not initialized
</script>
Using debugger keyword

• In debugging, generally we set breakpoints to examine each


line of code step by step. There is no requirement to perform
this task manually in JavaScript.
• JavaScript provides debugger keyword to set the breakpoint
through the code itself. The debugger stops the execution of
the program at the position it is applied. Now, we can start
the flow of execution manually. If an exception occurs, the
execution will stop again on that particular line.
<script>
x = 10;
y = 15;
z = x + y;
debugger;
document.write(z);
document.write(a);
document.write(y);
</script>
JavaScript Variable Scope

• The scope of a variable is the region of your program in


which it is defined. JavaScript variables have only two
scopes.
• Global Variables − A global variable has global scope
which means it can be defined anywhere in your
JavaScript code.
• Local Variables − A local variable will be visible only
within a function where it is defined. Function
parameters are always local to that function.
<script>
function abc(){
var x=10;//local variable
}
</script>
A JavaScript local variable is declared inside
block or function. It is accessible within the
function or block only.
JavaScript global variable

A JavaScript global variable is accessible from


any function. A variable i.e. declared outside
the function or declared with window object is
known as global variable. For example:
<script>
var data=200;

//gloabal variable
function a(){
document.writeln(“data from a function”data);
}
function b(){
document.writeln(“data from b function “+data);
}
a();//calling JavaScript function
b();
</script>
JavaScript Variable

• The value stored in a variable can be changed during program


execution.
• A variable is only a name given to a memory location, all the
operations done on the variable effects that memory location.
• In JavaScript, all the variables must be declared before they can be
used.
• Three Ways to Declare a JavaScript Variable:
using var
using let
using const
Variables declared with var
<html>
<body>
<h1>JavaScript Variables</h1>
<p>In this example, x, y, and z are variables.</p>
<script>
var x = 5;
var y = 6;
var z = x + y;
document.write("The value of z is: " + z);
</script>
</body>
</html>
Variables declared with let
<html>
<body>
<h1>JavaScript Variables</h1>
<p>In this example, x, y, and z are variables.</p>
<script>
let x = 5;
let y = 6;
let z = x + y;
document.write("The value of z is: " + z);
</script>
</body>
</html>
When to Use JavaScript var?
Always declare JavaScript variables with var ,let , or const.

• The var keyword is used in all JavaScript code from 1995 to 2015.
• The let and const keywords were added to JavaScript in 2015.
• If you want your code to run in older browsers, you must use var.

When to Use JavaScript const?

• If you want a general rule: always declare variables with const.


• If you think the value of the variable can change, use let.
• In this example, price1, price2, and total, are variables:
Variables declared with const
<html>
<body>
<h1>JavaScript Variables</h1>
<p>In this example, price1, price2, and total are variables.</p>
<script>
const price1 = 5;
const price2 = 6;
//price2= 30;
let total = price1 + price2;
document.write("The total is: " + total);
</script>

</body>
</html>
JavaScript Identifiers
• All JavaScript variables must be identified with unique names.
• These unique names are called identifiers.
• Identifiers can be short names (like x and y) or more descriptive
names (age, sum, totalVolume).

The general rules for constructing names for variables


(unique identifiers) are:

• Names can contain letters, digits, underscores, and dollar signs.


• Names must begin with a letter.
• Names can also begin with $ and _
• Names are case sensitive (y and Y are different variables).
• Reserved words (like JavaScript keywords) cannot be used as
names.
JavaScript Let
• Variables defined with let cannot be Redeclared.
• Variables defined with let must be Declared before use.
• Variables defined with let have Block Scope.
Example:
let x = “ram";
let x ; // Syntax Error: 'x' has already been declared
NOTE: Re-initialization is possible with let keyword.
JavaScript var
• Variables defined with var can be redeclared.
Example: var x = “ram";
var x = 0;
• Redeclaring a JavaScript variable with var is allowed anywhere in a
program
<html>
<body>
<script>
let x = 5;
let x = 10;
//x=10; re assignment is possible but re-declaration is not
possible
document.write("The x value is: " + x);
</script>
</body>
</html>
// SyntaxError: 'x' has already been declared
<html>
<body>
<script>
var price1 = 5;
var price1 = 10;// Re-declaration is
possible
document.write("The total is: " + price1);
</script>
</body>
</html>
JavaScript Const
• Variables defined with const cannot be Redeclared.
• Variables defined with const cannot be Reassigned.
• Variables defined with const have Block Scope.
• const PI = 3.141592653589793;
PI = 3.14; // This will give an error
PI = PI + 10; // This will also give an error
• JavaScript const variables must be assigned a value when they are
declared:
const PI = 3.14159265359;
• Incorrect
const PI;
PI = 3.14159265359;
Scope in JavaScript

• The scope of a variable is the region of your program in which it is


defined. JavaScript variables have only three scopes.
• There are three types of scope in JavaScript.
1.Global scope
2.Local scope
3.Block scope
• Global Scope: In the global scope, the variable can be accessed
from any part of the JavaScript code.
• Local Scope: In the local scope, the variable can be accessed within
a function where it is declared.
• Block scope: All variables that have been declared within curly
brackets { } are restricted to be accessed within that block and inside
blocks of that block only.
<html>
<body>
<script>
var value=50;//global variable
function a()
{
alert(value);
}
function b()
{
alert(value);
}
a();
</script>
</body>
</html>
<html>
<body>
<script>
function m()
{
window.value=100;//declaring global variable by window object here value is varaible
}
function n()
{
alert(window.value);//accessing global variable from other function
}
m();
n();
</script>
</body>
</html>
<html>
<body>
<script>
var $var12 = 200;
function example()
{
var $var12 = 300;
document.write("Inside example() function = " + $var12);
}
document.write("Outside example() function = " + $var12);
document.write("<br>");
example();
</script>
</body>
</html>
<html>
<body>
<script>
function greet()
{
var a = 2;

if(a == 2)
{
var b = 3;
document.write(a + ' ' + b);
}
document.write(a + ' ' + b);
}
greet();
</script>
</body>
</html>
NOTE

The block scope does not work with the var keyword. You can either use let or
const keywords for that.
<html><body>
<script>
{
var a="hey";
let b="welcome to";
const c="class";
console.log(a);
console.log(b);
console.log(c);
}
console.log(a);
//console.log(b);
//console.log(c);
</script>
</body>
</html>
JavaScript Data Types

• JavaScript provides different data types to hold different types of


values. There are two types of data types in JavaScript.
1.Primitive data type
2.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. You need to use var here to specify the data type.
It can hold any type of values such as numbers, strings etc.
Examples :
var a=40;//holding number
var b="Ram";//holding string
JavaScript primitive data types

There are five types of primitive data types in JavaScript. They are
as follows
Data Type Description

String represents sequence of characters e.g.


"hello"
Number represents numeric values e.g. 100
Boolean represents boolean value either false
or true
Undefined represents undefined value
Null represents null i.e. no value at all
JavaScript non-primitive data types

Data Type Description

Object represents instance through which


we can access members

Array represents group of similar values

RegExp represents regular expression


Number
let n = 123;
n = 12.345;
• The number type represents both integer and floating point numbers.

BigInt
• In JavaScript, the “number” type cannot safely represent integer
values larger than (253-1) (that’s 9007199254740991), or less than -
(253-1) for negatives.
String
In JavaScript, there are 3 types of quotes.
1. Double quotes: "Hello".
2. Single quotes: 'Hello'.
3. Backticks: `Hello`.
• Double and single quotes are “simple” quotes. There’s practically no
difference between them in JavaScript.
• Backticks are “extended functionality” quotes. They allow us to
embed variables and expressions into a string by wrapping them
in ${…}
let name = "John";
// embed a variable
alert( `Hello, ${name}!` ); // Hello, John!
// embed an expression
alert( `the result is ${1 + 2}` ); // the result is 3
• The expression inside ${…} is evaluated and the result becomes a
part of the string.
<html>
<body>
<script>
let i=10;
var str=`hello,${i}`;
document.write(str);
</script>
</body>
</html>
<html>
<body>
<script>
let name="john";
var str=`hello,${name}`;
document.write(str);
</script>
</body>
</html>
String Length
To find the length of a string, use the built-in length property:
Boolean (logical type)
• The boolean type has only two values: true and false.
• This type is commonly used to store yes/no values: true means “yes,
correct”, and false means “no, incorrect”.
The “null” value
• The special null value does not belong to any of the types.
• It forms a separate type of its own which contains only
the null value:
let age = null;
• It’s just a special value which represents “nothing”, “empty” or
“value unknown”.
• The code above states that age is unknown.
The “undefined” value
• It makes a type of its own, just like null.
•The meaning of undefined is “value is not assigned”.
•If a variable is declared, but not assigned, then its value is undefined:
Example:
let age;
alert(age); // shows "undefined"
Technically, it is possible to explicitly assign undefined to a variable
JavaScript Date Objects

Creating Date Objects:


• Date objects are created with the new Date() constructor.
• There are 9 ways to create a new date object:
new Date()
new Date(date string)
new Date(year,month)
new Date(year,month,day)
new Date(year,month,day,hours)
new Date(year,month,day,hours,minutes)
new Date(year,month,day,hours,minutes,seconds)
new Date(year,month,day,hours,minutes,seconds,ms)
new Date(milliseconds)
JavaScript new Date()

• A new Date() creates a date object with the current date and time:

<html>
<body>
<h1>JavaScript Dates</h1>
<h2>Using new Date()</h2>
<p>Create a new date object with the current date and time:</p>
<p id="demo"></p>
<script>
const d = new Date();
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>
output
JavaScript Array

• JavaScript array is an object that represents a collection of similar


type of elements.
• There are 3 ways to construct array in JavaScript
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
1) JavaScript array literal
• The syntax of creating array using array literal is given below:
var arrayname=[value1,value2.....valueN];
<html>
<body>
<script>
var emp=[‘Rama’,’Raj’,’Ratan’];
for (i=0;i<emp.length;i++)
{
document.write(emp[i] + "<br/>");
}
</script>
</body>
</html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<script>
const a = ["ram","raj" ,"ravi"];
Document.write(a);
</script>
</body>
</html>
2) JavaScript Array directly (new keyword)
• The syntax of creating array directly is given below:
var arrayname=new Array();
• Here, new keyword is used to create instance of array.
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
3) JavaScript array constructor (new keyword)
• Here, you need to create instance of array by
passing arguments in constructor so that we
don't have to provide value explicitly
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
Output:
Jai
Vijay
Smith
JavaScript Operators

• JavaScript operators are symbols that are used to perform


operations on operands. For example:
var sum=10+20;
• Here, + is the arithmetic operator and = is the assignment
operator.
• There are following types of operators in JavaScript.
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
JavaScript Arithmetic Operators

• Arithmetic operators are used to perform arithmetic operations on


the operands. The following operators are known as JavaScript
arithmetic operators.
JavaScript Comparison Operators

• The JavaScript comparison operator compares the two operands.


The comparison operators are as follows:
<html>
<body>
<p id="demonstration"></p>
<script>
var a = 10;
document.getElementById("demonstration").innerHTML = (a == 20);
</script>
</body>
</html>
<!DOCTYPE html>
<html> <body>
<p id="demo"></p>
<script> var x = 10;
document.getElementById("demo").innerHTML = (x === "10");
</script>
</body>
</html>
JavaScript Bitwise Operators

• The bitwise operators perform bitwise operations on operands. The


bitwise operators are as follows:
JavaScript Logical Operators

• The following operators are known as JavaScript logical operators.


JavaScript Assignment Operators

• The following operators are known as JavaScript assignment


operators.
JavaScript Special Operators
JavaScript
Conditional statements
• Conditional statements are used to decide the flow of execution based on
different conditions.
There are three forms of if statement in JavaScript.
1. If Statement
2. If else statement
3. if else if statement
1.JavaScript If statement
It evaluates the content only if expression is true.
Syntax:
if(expression)
{
//content to be evaluated
}
<html>
<body>
<script>
var a=20;
if(a>10)
{
document.write("value of a is greater than 10");
}
</script>
</body>
</html>
Output:
value of a is greater than 10
JavaScript If...else Statement

• It evaluates the content whether condition is true of false.


Syntax:
if(expression)
{
//content to be evaluated if condition is true
}
else
{
//content to be evaluated if condition is false
}
<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>
Output: 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 if(expression3)
{
//content to be evaluated if expression3 is true
}
else
{
//content to be evaluated if no expression is 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>
JavaScript Switch

• The JavaScript switch statement is used to execute one code from


multiple expressions. It is just like else if statement. But it is convenient
than if..else..if because it can be used with numbers, characters etc.
Syntax :
switch(expression)
{
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......

default:
code to be executed if above values are not matched;
}
<html>
<body>
<script>
var grade='A';
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>
Loops in JavaScript

• Looping in programming languages is a feature that facilitates the


execution of a set of instructions/functions repeatedly while some condition
evaluates to true.
There are mainly two types of loops:
1. Entry Controlled loops: In these types of loops, the test condition is tested
before entering the loop body. For Loops and While Loops are entry-
controlled loops.
2. Exit Controlled loops: In these types of loops the test condition is tested or
evaluated at the end of the loop body. Therefore, the loop body will execute
at least once, irrespective of whether the test condition is true or false.
The do-while loop is exit controlled loop.
• JavaScript mainly provides three ways for executing the loops. While all
the ways provide similar basic functionality, they differ in their syntax and
condition checking time.
while loop

A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition.
The while loop can be thought of as a repeating if statement.
Syntax :
while (boolean condition)
{
loop statements...
}
• While loop starts with checking the condition. If it is evaluated to be
true, then the loop body statements are executed otherwise first
statement following the loop is executed. For this reason, it is also
called the Entry control loop
• Once the condition is evaluated to be true, the statements in the loop
body are executed. Normally the statements contain an update value
for the variable being processed for the next iteration.
• When the condition becomes false, the loop terminates which marks
the end of its life cycle.
<html>
<body>
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
</body>
</html>
for loop:

for loop provides a concise way of writing the loop structure.

Unlike a while loop, a for statement consumes the initialization, condition,


and increment/decrement in one line thereby providing a shorter, easy-to-debug
structure of looping.
Syntax:

for (initialization condition; testing condition; increment/decrement)


{
statement(s)
}
1.Initialization condition: Here, we initialize the variable in use. It
marks the start of a for loop. An already declared variable can be used
or a variable can be declared, local to loop only.
2.Testing Condition: It is used for testing the exit condition for a loop.
It must return a boolean value. It is also an Entry Control Loop as the
condition is checked prior to the execution of the loop statements.
3.Statement execution: Once the condition is evaluated to be true, the
statements in the loop body are executed.
4.Increment/ Decrement: It is used for updating the variable for the
next iteration.
5.Loop termination: When the condition becomes false, the loop
terminates marking the end of its life cycle.
<html>
<body>
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
</body>
</html>
do-while:
The do-while loop is similar to the while loop with the only difference that it checks for the condition
after
executing the statements, and therefore is an example of an Exit Control Loop.
Syntax:
do {
statements..
} while (condition);

1. The do-while loop starts with the execution of the statement(s). There is no checking of any
condition for the first time.
2. After the execution of the statements, and update of the variable value, the condition is checked for a
true or false value. If it is evaluated to be true, the next iteration of the loop starts.
3. When the condition becomes false, the loop terminates which marks the end of its life cycle.
4. It is important to note that the do-while loop will execute its statements at least once before any
condition is checked, and therefore is an example of the exit control loop.
<html>
<body>
<script>
var i=21;
do {
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
</body>
</html>
JavaScript Functions

• A JavaScript function is a block of code designed to perform a


particular task.
• A JavaScript function is executed when "something" invokes it
(calls it).
JavaScript Function Syntax:

function name(parameter1, parameter2, parameter3)


{
// code to be executed
}
Function Invocation

The code inside the function will execute when


"something" invokes (calls) the function:
• When an event occurs (when a user clicks a button)
• When it is invoked (called) from JavaScript code
• Automatically (self invoked)
Function Return
• When JavaScript reaches a return statement, the function will stop
executing.
• If the function was invoked from a statement, JavaScript will
"return" to execute the code after the invoking statement.
• Functions often compute a return value.
• The return value is "returned" back to the "caller":
<html>
<body>
<h2>JavaScript Functions</h2>
<script>
function myFunction(p1, p2)
{
return p1 * p2;
}
document.write("value of p1*p2 is "+ myFunction(4, 3));
</script>
</body>
</html>
<html>
<body>

<h2>JavaScript Functions</h2>
<p id="demo"></p>
<script>
var x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;

function myFunction(a, b)
{
return a * b;
}
</script>

</body>
</html>
Object
• In JavaScript, an object is a collection of properties, where each
property is defined as a key-value pair.
• The following example defines an empty object using the object
literal syntax:
let emptyobject={}
• The following example defines the person object with two
properties: firstName and lastName.
let person = {
firstName: ’john’,
lastName:’Deo’
};
To access a object’s property, you can use
•The dot notation (.)
•The array-like notation ([]).

console.log(person.firstName);
console.log(person.lastName);
(or)
console.log(person[‘firstName’]);
console.log(person[‘LastName’]);
<html>
<body>
<script>
let person = {
firstName: "john",
lastName:"Deo",
age:22
};

document.write(person.firstName+"<br/>");
document.write(person.lastName+"<br>");
document.write(person.age);
</script>
</body>
</html>
<html>
<body>
<script>
let person = {
firstName: "john",
lastName:"Deo",
age:22
};

document.write(person['firstName']+"<br/>");
document.write(person['lastName']+"<br>");
document.write(person['age']);
</script>
</body>
</html>
<html>
<body>
<script>
let person = {
firstName: "john",
lastName:"Deo",
age:22
};

document.write(person.firstName+"<br/>");
delete person.firstName;
document.write(person.firstName+"<br>");
document.write(person['age']);
</script>
</body>
</html>
JavaScript RegExp(Regular Expression)

• A regular expression is a sequence of characters that forms a search


pattern.
• The search pattern can be used for text search and text to replace
operations.
• A regular expression can be a single character or a more
complicated pattern.
• Regular expressions can be used to perform all types of text search
and text replacement operations.
Syntax:
/pattern/modifiers;
Creating a regular expression:
To create a regular expression in JavaScript, you enclose its
pattern in forward-slash characters (/)
Using String Methods:
• In JavaScript, regular expressions are often
used with the two string
methods: search() and replace().
• The search() method uses an expression to
search for a match and returns the position of
the match.
• The replace() method returns a modified
string where the pattern is replaced.
<html>
<body>
<script>
function fun() {
var str = "hello welcome to javascript hai";
var n = str.search(/hai/i);
document.write(n);
}
fun();
</script>
</body>
</html>
<html>
<body>
<script>
function fun()
{
var str = "hello welcome to javascript hai";
//var n = str.search(/hai/i);
var n=str.replace(/hai/i,"program");
document.write(n);
}
fun();
</script>
</body>
</html>
• The predefined core objects
are Array, Boolean, Date, Function, Math, Number, RegExp,
and String.

You might also like