JavaScript Basics: Introduction and Features
JavaScript Basics: Introduction and Features
CHAPTER 4
JavaScript Part 1
Topics Covered
4.1 Introduction to JavaScript
4.1.1 History of JavaScript
4.1.2 JavaScript as an Interpreted Language
4.1.3 Features of JavaScript
4.2 Prerequisites for Executing JavaScript Programs
4.3 Introduction to Script Tag
4.3.1 JavaScript Syntax and Rules
4.3.2 Common Errors
4.4 Input and Output from the Script
4.5 Data Types
4.6 Variables
4.7 Operators
4.7.1 Operators Precedence and Associativity
4.8 Inbuilt functions in JavaScript
4.9 Control of flow using Conditional Statements
4.10 Control of flow using Loops
4.1 Introduction to JavaScript
JavaScript is a computer programming language used to make websites and applications
dynamic and interactive. It is unique because it can run directly in your browser and also
on a server. Along with Hypertext Markup Language (HTML) and Cascading Style
Sheets (CSS), JavaScript is one of the most commonly used programming languages of
the Internet.
HTML provides the basic layout, structure, and content of a website. CSS provides
design, fonts, colors, effects, and other visual elements. JavaScript brings dynamism and
interactivity to the website. For example, pop-ups, animations, video and social media
embeds, drop-down menus, and many other website components are created using
JavaScript.
Static Website
A static website is a type of website that delivers the same content to all users. The
content is stored on the web server and is shown on the user’s browser as is, without any
change of content. Static websites are simple to create and host, and are typically used
for informational websites, such as brochure websites or portfolios. They don’t require
any server-side processing or database interactions, making them fast and easy to
maintain.
Dynamic Website
A dynamic website is a type of website that generates content based on user interactions
or other events. It generates custom content for each user based on their actions or
preferences. Dynamic websites are typically created using server-side programming
languages such as PHP, JavaScript, or Python, and they interact with a database to
retrieve and store data. Examples of dynamic websites include social media platforms,
e-commerce sites, and content management systems.
Content of Web pages cannot be changed Content of Web pages can be changed at
at runtime. runtime.
Advantages of JavaScript
1. It is relatively easy to learn and use.
2. It can be used for client-side and server-side i.e. front end and back end.
3. It provides dynamism and interactivity on websites.
4. It runs on multiple platforms and devices. It is supported by all browsers.
5. There are many libraries, frameworks, and APIs available to facilitate tasks
6. It can create visually appealing web projects and to create drag & drop
components like sliders etc to make the website more professional.
1. Language- This attribute specifies the scripting language. Typically, its value will
be JavaScript. The recent versions of HTML have phased out the use of this
attribute and has become optional.
2. Type – This attribute is used to indicate the scripting language and its value
should be set to “text/JavaScript”. All current browsers are updated and are
JavaScript enabled by default. This attribute too is optional.
There are three different places in the HTML document where scripts can be used.
1. Body of the page: In this case when page is loaded in the browser then output is
displayed as the part of the HTML document.
2. Header of the page: In this case code is written in the form of a function (groups
of JavaScript statements but treated as a single unit and referred to in the other
script in the same page).
3. As external file: In this case JavaScript code is written in another file having .js
extension. This file is included in a script tag by specifying the file name.
<script>
[Link](“<i>hello World!</i>”);
// First JavaScript Program to print Hello World on the screen
</script>
Output on the browser : hello World!
1. Open any editor such as notepad and write the above program
2. Save the program with the .html extension in a proper folder or subfolder on a
drive like C:\JavaScript\myprograms.
3. Open the web browser like Google Chrome, I
4. Double Click the file you have created and saved in step 2, and then you can see
the output of your program.
1. Case Sensitivity: JavaScript is case sensitive i.e., uppercase letters and lower-case
letters have different meanings. For example, the word “alert” has a lowercase
“a”. so, if we type the word with an uppercase “A”, then the alert box will not be
displayed and the JavaScript code won't get executed.
2. Whitespace & Line Break: You can use spaces, tabs, and newlines anywhere in
the JavaScript Program. The JavaScript interpreter ignores them. Use tabs &
spaces to neatly format or indent your code. It makes the code easy to read &
understand.
3. Comments: The JavaScript allows us to add single line comments or Multi line
comments.
Single-line comments ( // ) − Any text between a // and the end of a line is
treated
as a comment.
<script>
//This program shows single line comments
</script>
Multi-line comments (/* */) − These comments may span multiple lines.
<script>
/*This is an example of
multiline comment */
</script>
Internal JavaScript: JavaScript can be added directly to the HTML file by writing
the code inside the <script> tag . We can place the <script> tag either inside
<head> or the <body> tag according to the need.
Example:
<html>
<head>
<title>Internal JavaScript</title>
</head>
<script>
/*Internal JavaScript*/
[Link]("Hello Friends!How are you?");
</script>
</html>
External JavaScript: A JavaScript program can be written in a file and saved with
the .js extension. This file can be then linked inside the <HEAD> and </HEAD>
tags of the HTML document in which we want to add this code. The SRC attribute
of the <script> tag allows to give the path of the JavaScript file.
Example:
Open the text editor and type the following:
Open another document in your text editor and type the following code:
<html>
<head>
<script src="[Link]">
</script>
</head>
</html>
Save the above file as [Link] and open it in your browser to see the output.
Output: Good Morning Friends!
1. [Link] method
JavaScript has access to the document property of the window object. The
document property returns the document object of the window which is being
used. When an HTML element is loaded onto the web browser then it becomes a
part of the document object. The document object is the root node of the HTML
page.
One can access the document object either by using [Link] or just
document. For example: [Link]() or [Link]()
The document object has a large range of properties or methods which a
developer can make use [Link] [Link]() in JavaScript helps to write a
JavaScript program or HTML expression into the document.
Example 2: We can also write HTML content and display them on a web page.
<html><head>
<script>
[Link]("<b>Beware of Cyber
Scams<b>");</script>
</head></html>
2. Dialog boxes
(i) alert() dialog box: An alert dialog box displays a short message or notification
to the user. Alert box gives only one button "OK" to select and proceed. It just
gives some information, necessary to the user and it can be invoked at various
events possible in JavaScript.
Example:
<html>
<head>
<title> JavaScript Alert Dialog Box
</title></head>
<body>
<script>
alert("You have chosen an Alert
box");
</script></body></html>
(ii) prompt() dialog box: The prompt dialog box is used to get some input from
the user. It has two buttons, one for “OK” and the other for “Cancel”. This method
returns the text entered in the input field when the user clicks the OK button. It
will return null if the user clicks the Cancel button. If the user clicks the OK button
without entering any text, an empty string is returned. For this reason, its result
is usually assigned to a variable when it is used. If you enter a number in the
prompt box, it will be stored as a string, as it always returns a string.
Example:
<html>
<head>
<script>
var yourname = prompt("Enter your name : ");
var age = prompt("Enter your age :");
[Link]("Your name is : " + yourname+"<br>");
[Link]("Your age is : " + age);
</script>
</head></html>
(iii) confirm() dialog box: A confirmation dialog box is mostly used to take the
user's confirmation on any option. It displays a dialog box with two buttons: OK
and Cancel. If the user clicks on the OK button, it will return true. If the user clicks
on the Cancel button, it will return false. It returns a Boolean value depending on
whether the user clicks OK(true) or CANCEL(false) button.
Example:
<html>
<head>
<title> JavaScript Confirm Dialog Box </title></head>
<body>
<script>
var result = confirm("Are you sure you want to cancel the order?");
if(result==true)
{
[Link]("Order IS Canceled!");
}
else
{
[Link]("Order NOT Canceled");
}
</script></body></html>
Output a value from JavaScript into an HTML element, in this case in the paragraph.
Example 2:
<html>
<head>
<script>
function myFunction()
{
[Link]("demo").innerHTML="Hello World";
}
</script>
</head>
<body>
<p>Click the button</p>
<button me</button>
<p id="demo"></p>
</body>
</html>
Output a value from an HTML form, in this case in a text box into an alert box in
JavaScript.
<!DOCTYPE html>
<html>
<body>
Name: <input type="text" id="myText" value="Enter your full name here">
<button Here</button>
There are special numeric values e.g. NaN and Infinity. If a number is divided by 0, the
resulting value is infinity.
A ‘NaN’ results when we try to perform an operation on a number with a non-numeric value
String:
The string data type in JavaScript can be any group of characters enclosed by a single or
double-quotes or by backticks.
1. var str1 = “This is a string1”; // This is a string primitive type or string literal
2. var str2= ‘This is a string2’;
3. var str3 = `This is a string3`;
Boolean
The Boolean data type has only two values, true and false. It is mostly used to check a
logical condition. Thus Booleans are logical data types which can be used for comparison
of two variables or to check a condition. The true and false imply a ‘yes’ for ‘true’ and a
‘no’ for ‘false'. When we check the data type of ‘true’ or ‘false’ using typeof operator, it
returns a Boolean.
Undefined
Undefined data type means a variable that is not defined. The variable is declared but
doesn’t contain any value. In the following example, the variable ‘a’ has been declared
but hasn’t been assigned a value yet.
var a;
[Link](a) // This will return undefined.
Null
The Null in JavaScript is a data type that is represented by only one value, the ‘null’ itself.
A null value means no value.
var a = null;
[Link](a) // This returns null
typeof(a)
4.6 Variables
JavaScript variables are used to store data that can be changed later on. The variables can
be thought of as named containers. You can place data into these containers and then
refer to the data simply by naming the container. JavaScript variables must have unique
names. These names are called Identifiers.
Examples of variables
var X; //defines a variable X, and by default no value is assigned to this variable
// the variable X has data type undefined
var y = 100; //defines a variable Y and assigns the integer value of 100 to it
● 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.
JavaScript Literals
JavaScript Literals are the values that are assigned to a variable and depending on what
literal we assign to a variable its data type will be fixed.
For example:
var a= “Roman Numbers”
var b=45
var x=90.78
var c=[34,56,78]
var d=true
4.7 Operators
In JavaScript, an operator is a symbol that performs an operation on one or more
operands, such as variables or values, and returns a result. Let us take a simple
expression: 5 + 3 is equal to 8. Here 5 and 3 are called operands, and ‘+’ is called the
operator.
● Arithmetic Operators
● Comparison (or Relational) Operators
● Logical Operators
● Assignment Operators
Arithmetic Operators
There are following arithmetic operators supported by JavaScript language: assume
variable a hold 10 and variable b holds 20 then:
Operator Description Example
- (Subtraction) Subtracts second operand from the first a - b will give -10
** (Exponent) Can be used to give one value raised to a**2 will give 102 or
power another value. 100
Comparison Operators
These are some of the comparison operators supported by JavaScript language. Assume
variable has value 10 and variable b has value 20
Operator Description Example
> (Greater than) Checks if the value of the left operand is (a > b) is false
greater than the value of right operand, if
yes then the condition becomes true.
< (Less than) Checks if the value of the left operand is (a < b) is true
less than the value of the right operand, if
yes then the condition becomes true.
>= (Greater than Checks if the value of left operand is (a >= b) is false
or equal to) greater than or equal to the value of right
operand, if yes then the condition becomes
true.
<= (Less than or Checks if the value of left operand is less (a <= b) is true
equal to) than or equal to the value of right operand,
if yes then the condition becomes true.
&& (logical AND) If both the operands are non-zero (10&&20) will output 20
|| (logical OR) If both the operands are non-zero (10||20) will output 10
numbers then and returns/outputs (20||10) will output 20
the first number. If one of them is (45<=49||7<9) will
zero it returns the non-zero output true
number. (1>=5||2==2.7)will
In other cases it gives false only if output false
both conditions are false otherwise
it gives true.
+= (Add and It adds the right operand to the left operand z += x is equivalent
Assignment) and assigns the result to the left operand. to z = z + x
*=(Multiply and It multiplies the right operand with the left z *= x is equivalent
Assignment) operand and assigns the result to the left to z = z * x
operand.
/= (Divide and It divides the left operand with the right z /= x is equivalent
Assignment) operand and assigns the result to the left to z = z / x
operand.
Conditional operator (? :)
The conditional operator is also called the ternary operator, containing the 3 parts. The
first part contains the condition and executes the second part if the condition evaluates
the true; Otherwise, it executes the third part.
Syntax
Condition ? First statement : Second statement
Parameters
● Condition − It is a conditional statement.
● First Statement − If the conditional statement evaluates true, First Statement will
be executed.
● Second Statement − If the conditional statement evaluates false, the Second
statement will be executed.
For example
The statement assigns value "Pass" to the variable status if marks are 30 or more.
Otherwise, it assigns the value of "Fail" to status.
typeof operator
typeof in JavaScript is an operator used for type checking and returns the data type of
the operand passed to it. The operand can be any variable, function, or object whose type
you want to find out using the typeof operator.
Syntax
typeof (operand)
<!DOCTYPE html>
<html><body>
<h3>JavaScript Arithmetic Operators</h3>
<script>
var a=10;
var b=5
c=a+b;
[Link]("The value of a+b is: ", c)
[Link]("<br>")
c=a-b;
[Link]("The value of a-b is: ", c)
[Link]("<br>")
c=a*b;
[Link]("The value of a*b is: ", c)
[Link]("<br>")
c=a/b;
[Link]("The value of a/b is: ", c)
[Link]("<br>")
c=a%b; Observe how the increment
[Link]("The value of a%b is: ", c) operator written after the
[Link]("<br>") variable a will not increase the
value in place, it will be
[Link]("The value of a++ is: ", a++) reflected the next time variable
[Link]("<br>")
[Link]("The value of a++ is: ", a)
a is output.
[Link]("<br>")
[Link]("The value of ++a is: ", ++a)
However the increment or
[Link]("<br>")
decrement operator written
[Link]("The value of --b is: ", --b)
[Link]("<br>") before the variable will
</script> </body> increase or decrease the value
</html> in place.
<!DOCTYPE html>
<html>
<body>
<h3>JavaScript Assignment Operators</h3>
<script>
var a;
a=10;
a+=5;
[Link]("The value of a after a+=5 is: ", a)
[Link]("<br>")
a-=3
[Link]("The value of a after a-=2 is: ", a)
[Link]("<br>")
a*=5
[Link]("The value of a after a*=5 is: ", a)
[Link]("<br>")
a/=4
[Link]("The value of a after a/=4 is: ", a)
[Link]("<br>")
a**=2
[Link]("The value of a after a**=2 is: ", a)
[Link]("<br>")
</script>
</body>
</html>
parseInt(): This function converts a string into an integer (a whole number) based on the
specified radix (base). The radix is optional, default is 10. If the first character of the string
cannot be converted to a number, it will return a NaN (Not a Number)
For example:
parseInt (“20”) returns 20
parseInt (“34.12”) returns 34
parseInt (“20 Pens”) returns 20
parseInt (“Pens 20”) returns NaN
parseFloat(): It accepts the string and converts it into a floating-point number. If the
string does not contain a numeral value or If the first character of the string is not a
Number, then it returns NaN.
For example:
parseFloat(“65”) returns 65
parseFloat(“65.33”) returns 65.33
parseFloat( “14 inch”) returns 14
parseFloat( “inch 14”) returns NaN
var num=NaN
[Link]() // will return NaN
isNaN(): This method checks whether the passing argument is a number or not. It
returns true or false value as a result.
For example:
document. write(isNaN("Bottles")) //will return true
Conditional Statements:
[Link] if..else statements: The if-else statement will perform some action for a specific
condition. If the condition is satisfied, then a particular code of action will be executed.
If the condition is not satisfied, it will execute another code of action that satisfies that
particular condition.
Example: If the hour is less than 18, create a "Good day" greeting, otherwise "Good
evening":
if (hour < 18)
{
greeting = "Good day";
}
else
{
greeting = "Good evening";
}
The else if statement can be used to specify a new condition if the first condition is false.
Example: If time is less than 10:00, create a "Good morning" greeting, if not, but time is
less than 20:00, create a "Good day" greeting, otherwise a "Good evening":
if (time < 10)
{
greeting = "Good morning";
}
else if (time < 20)
{
greeting = "Good day";
}
else
{
greeting = "Good evening";
}
Example: Calculate discount price base on total amount. If the amount is less than 10000
then no discount. If the amount is less than 20000 then the discount is 5%. If the amount
is less than 30000 then the discount is 10%. If the amount is more than 30000 then the
discount is 15%.
else if(condition)
….statements…..
else if(condition)
….statements…..
else
….statements…..
1. Using switch…case statement: The switch statement is used to select one of many
blocks of the code to be executed in a program. The switch expression is evaluated
once and the value of the expression is compared with the values of each case. If
a match is found, then the associated block of code is executed, otherwise the
default code block is executed.
Syntax:
● Expression is the value that you want to compare.
● Case value1, case value2, etc., represent the
possible values of the expression.
● break statement terminates the switch statement.
Without it, execution will continue into the next
case.
● Default specifies the code to run if none of the
cases match the expression.
Example: The following program asks the user to input the day of the week starting with
Sunday as 1. It displays the day as a string and displays a message for an invalid number.
<!DOCTYPE html>
<html><body>
<h2>Displaying the Day of the Week</h2>
<p id="demo"></p>
<script>
var day;
var daynum=prompt("Enter the Day of the Week (Sunday-1)")
switch(daynum) {
case 1:
day = "Sunday";
break;
case 2:
day = "Monday";
break;
case 3:
day = "Tuesday";
break;
case 4:
day = "Wednesday";
break;
case 5:
day = "Thursday";
break;
case 6:
day = "Friday";
break;
case 7:
day = "Saturday";
break;
default:
[Link]("Invalid Number")
}
[Link]("demo").innerHTML = "Today is " + day;
</script></body></html>
Example: Based on the grade entered show the remark as per the student grade
<!DOCTYPE html>
<html> <body>
<script>
var grade=prompt("Enter the grade A/B/C");
switch(grade)
{ case 'A':
result="Excellent"
break;
case 'B':
result="Very Good"
break;
case 'C':
result="Good"
break;
default:
result="No Grade"
}
[Link](result);
</script>
</body> </html>
● Initialization: Initializes a counter variable to start the loop. This is done only
once in a loop.
● Condition: Specifies a condition that must evaluate to true for the next iteration.
If the condition evaluates to true, the statements inside the loop body will execute,
If the condition evaluates to false, the loop will terminate.
● Iteration: Increase or decrease the counter variable after every pass of the loop.
1. for loop: The for loop is used to repeat the set of instructions for a fixed number
of times. The syntax to use the for loop is as follows:
Example: To display the text “Hello Life! You are so Good” for 5 times
<html>
<body>
<p> For loop Example</p>
<script>
for (i = 0; i < 5; i++) {
[Link]("Hello Life! You are so Good" +"<br>"); }
</script>
</body>
</html>
Output
<html>
<body>
<p> For loop Example 2</p>
<script>
for (i = 0; i <=10; i++) {
[Link](i +"<br>"); }
</script>
</body>
</html>
Output:
2. while loop: The while loop is also used to repeat a set of instructions until a
conditional statement returns true. Once the condition returns false, the loop is
terminated. The syntax to use the while loop is as follows:
Initialization;
while (condition)
{ Why while loops?
//set of JavaScript statements In advanced programming while
iteration; loops are used when we may not
} have a fixed number of iterations.
For example in a video game we
want the user click a certain key to
end the game, we can use a while
loop to make the game go on and it
will break only if that key is pressed.
In for loops the number of iterations
is mostly fixed.
Example: The same example of for Loop can be executed with the use of while loop
<html>
<body>
<p> While loop Example 2</p>
<script>
var i=1
while (i<=5)
{
[Link]("Hello Life! You are so Good" +"<br>");
i++;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Loops</h2> Output:
<p>A loop with a <b>break</b> statement.</p>
<p id="demo"></p>
<script>
var text = "";
for (var i = 0; i < 10; i++)
{
if (i === 3)
{
break;
}
text += "The number is " + i + "<br>"; The loop stops as soon
}
as i becomes equal to 3
[Link]("demo").innerHTML = text;
</script>
</body>
</html>
The continue statement is used with a loop to ignore execution when a condition is true.
This statement will not stop the execution of the rest of the loop.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Loops</h2>
Exercise
2. _______________ can provide the information to the user or ask him to input the
value required by a program.
a. Browser
b. Dialog box
c. Value box
d. Window box
a. end
b. break
c. stop
d. continue
16. In the switch..case statement,____________ specifies the code to run if none of the
cases match the expression.
a. omit
b. skip
c. fail
d. default
17. Which of the following is not a valid variable name?
a. grade_pay
b. 2gradepay
c. gradepay
d. GradePay
18. Which of the following was also the name of JavaScript?
a. LiveScript
b. VBscript
c. BasicScript
d. None of the above
19. There can be only one if statement in if-else if-else construct.
a. True
b. False
20. _____________ operator and gives the remainder of after an integer division.
a. /
b. %
c. &&
d. <=
var x=17,y=12;
x--;
iv) x+=10;
y+=x
y++
[Link](y)
v) <!DOCTYPE html>
<html>
<body>
<p> While loop</p>
<script>
var i=1;
while(i<= 5)
{
if( i==3)
continue
i++
[Link]("The number is " + i+ "<br>");
}
</script>
</body>
</html>
vi) <script>
for (i-0; i<5; i++)
{
[Link](“@” + “<br>”);
}
</script>
vii)
var i=10;
var j=2;
while(i > j)
{
i = i / j;
[Link](i+” “);
}
10. What are variables? Declare a variable subject and give it a value as “Web
Application”.
11. Differentiate between local and global variables.
12. What are different types of operators in JavaScript?
13. What is the use of typeof operator?
14. What is the difference between operator precedence and associativity?
15. Differentiate between conditional statements and iterative statements.
IV. Short Answer Questions
1. Differentiate between a static and dynamic website.
2. Explain any 4 features of JavaScript.
3. Explain the tag used to write a JavaScript program? Write about its attributes also.
4. Explain the [Link] method
5. Differentiate between the alert(), prompt() and confirm() dialog boxes.
6. Explain the primitive data types of JavaScript.
7. What are the rules for naming the variables?
8. Explain the conditional operator with an example.
Grade Bonus
A 30% of salary
B 35% of salary
C 20% of salary
D 15% of salary
16. Calculate discount price base on total amount. If the amount is less than 10000
then no discount. If the amount is less than 20000 then the discount is 5%. If the
amount is less than 30000 then the discount is 10%. If the amount is more than
30000 then the discount is 15%.
<script>
var prod, counter;
prod=2;
ctr =2;
while (ctr<=9)
prod= prod * ctr;
ctr = ctr+2;
[Link](prod + “, “+ ctr +”<br>”);
}
2. Give the JavaScript statement for each of the following:
a. A variable ‘sum’ that stores the sum of variables ‘A’ & ‘B’
b. To print the data type of variable ‘k’
c. To take ‘age’ as input from the user
3. Rohit, a student of class 12, is learning JavaScript. During examination, he has been
assigned an incomplete JavaScript code (shown below). Help him in completing the
code :
Incomplete Code
{
da=bs*12/100;
hra=bs*8/100;
}
else if(bs>=30000)
{
da=bs*10/100;
hra=bs*6/100;
}
gs=bs+da+hra;
______________(gs); ------------ line 4
4. The following program is given using if...else if. Use the same program to convert
using switch..case without changing the meaning of the program:
<script>
var grade=parseInt(prompt(“Enter grade of employee”))
if (grade==”A”)
[Link](“You are Vice President”)
else if(grade==”B”)
[Link](“You are LEVEL 1 Officer”)
else if(grade==”C”)
[Link](“You are a Trainee”)
else
[Link](“You are not employed”)
</script>