Table of Contents
What is JavaScript?
- JavaScript (js) is a light-weight object-oriented programming language which is used by several websites for scripting the web pages.
- It is an interpreter, full-fledged programming language that enables dynamic interactivity on websites when applied to an HTML document.
- With JavaScript, users can build modern web applications to interact directly without reloading the page every time.
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.
- JavaScript is an object-oriented programming language.
- 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.
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 example is easy to code. JavaScript provides 3 places to put the JavaScript code: within body tag, within head tag and external JavaScript file.
<html>
<body>
<script type="text/javascript">
document.write("We are learning JavaScript ");
</script>
</body>
</html>
Output
- The script tag specifies that we are using JavaScript.
- The text/javascript is the content type that provides information to the browser about the data.
- The document.write() function is used to display content through JavaScript.
- There are 3 places where we can put <script> or JavaScript code:
- Body: When page loads, JavaScript runs
- Head : When some specific action triggers, JavaScript runs JS (external javascript file): Uses for code re usability
Types of JavaScript Comments
- It is a meaningful way to deliver message. There are two types of comments in JavaScript.
- Single-line Comment //
- Multi-line Comment /* */
JavaScript Variable
- A JavaScript variable is simply a name of storage location
- There are two types of variables in JavaScript: local variable and global variable
Rules to declare a JavaScript variable
- Name must start with a letter (a to z or A to Z) or underscore.
- After first letter we can use digits (0 to 9), for example value1.
- JavaScript variables are case sensitive, for example a and A are different variables.
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 Variable − A global variable has global scope which means it can be defined anywhere in your JavaScript code.
- Local Variable − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function. Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable.
<body>
<script type = "text/javascript">
var a = "global"; // Declare a global variable
function fun_scope( )
{
var a = "local"; // Declare a local variable
document.write("The value of a = ",a,"<br>");
}
fun_scope();
document.write("The value of a = ",a); //global
</script>
</body>
Output
JavaScript Data Types
- JavaScript provides different data types to hold different types of values.
- JavaScript has integer, string, Boolean, object, array etc types of values.
- JavaScript is a dynamic type language, it means you don’t need to specify type of the variable because it is dynamically used by JavaScript engine.
- Use “var” to specify the data type. It can hold any type of values such as numbers, strings, boolean etc.
var a=10;//holding number
var b="Hello BCA Students";//holding string
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands.
- Arithmetic Operators
- Comparison (Relational) Operators
- Logical Operators
- Assignment Operators
- Special Operators
Arithmetic Operators
- Arithmetic operators are used to perform arithmetic operations on the operands: +, -, *, /, %, ++, —
- These are addition, subtraction, multiplication, division, modulus, increment & decrement operators.
Operator | Description |
+ | Addition |
– | Subtraction |
* | Multiplication |
/ | Division |
% | Modulus |
++ | Increment |
— | Decrement |
<html>
<body>
<script type="text/javascript">
var a=20;
var b=10;
document.write("Addition of a+b = ",(a+b),"<br>");
document.write("Subtraction of a-b = ",(a-b),"<br>");
document.write("Multiplication of a*b = ",(a*b),"<br>");
document.write("Multiplication of a/b = ",(a/b),"<br>");
document.write("Multiplication of a%b = ",(a%b),"<br>");
</script>
</body>
</html>
Output
Comparison Operators
- Arithmetic operators are used to perform arithmetic operations on the operands: <, >, <=, >=, ==, ===, !=, !==
Operator | Description |
== | Is equal to |
=== | Identical (equal & of same type) |
!= | Not equal |
!== | Not identical |
> | Greater than |
>= | Greater than or equal to |
< | Less than |
<= | Less than or equal to |
Logical Operators
Operator | Description |
&& | Logical AND |
|| | Logical OR |
! | Logical NOT |
Assignment Operators
Operator | Description |
= | Assign |
+= | Add & assign |
-= | Subtract & assign |
*= | Multiply & assign |
/= | Divide & assign |
%= | Modulus & assign |
Special Operators
Operator | Descritption |
? : | Conditional operator returns value based on the condition, like If..else |
, | Comma operator allows multiple expressions to be evaluated as single statement |
Example
<script type='text/javascript'>
var a=200;
var b=100;
c=(a>b)?"a is bigger":"b is bigger";
document.write(c);
</script>
Output
Conditional Structure
- The JavaScript if-else statement is used to execute the code whether condition is true or false.
- In JavaScript, there are three form of if statement.
- If Statement
- If else statement
- if else if statement
If statement
- It evaluates the content only if expression is true.
Syntax:
if(expression)
{
//content to be evaluated
}
Example:
<script language="javascript">
var a=11;
if(a>10)
{
document.write("a is greater than 10");
}
</script>
Example
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
}
Example:
<script>
var a=20;
if(a%2==0)
{
document.write(a," is even number");
}
else
{
document.write(a," is odd number");
}
</script>
Output
If…else if .. else 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
}
Example:
<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>
Output
Switch Case
- 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;
}
Example:
<script>
var grade='B';
var result;
switch(grade)
{
case 'A':
result="You have got A Grade";
break;
case 'B':
result="You have got B Grade";
break;
case 'C':
result="You have got C Grade";
break;
default:
result="You haven't got any Grade";
}
document.write(result);
</script>
Output
- Use break statement in a switch case block, otherwise once a case block is executed, the rest of the subsequent case blocks will execute.
- In above example, if we skip to write break in every case, the output will be: You have got B Grade You have got C Grade You haven’t got any Grade
JavaScript Looping Structure
- It may happen that during the programming one may need to perform some kind of action over and over again.
- In such situations, you would need to write loop statements to reduce the number of lines.
While Loop
- The purpose of a while loop is to execute a statement or code block repeatedly as long as an expression is true. Once the expression becomes false, the loop terminates.
Syntax:
while (expression) {
Statement(s) to be executed if expression is true
}
Example:
<script type = "text/javascript">
var start = 1;
document.write("<b>Loop has started from 1 & ended upto 10");
while (start <= 10)
{
document.write("<b>Loop Number : " + start + "<br>");
start++;
}
</script>
Output
The do…while Loop
- The do…while loop is similar to the while loop except that the condition is checked the end of the loop.
- This means that the loop will always be executed at least once, even if the condition is false.
Syntax:
do {
Statement(s) to be executed;
} while (expression);
Example:
<script type = "text/javascript">
var start = 0;
do
{
document.write("Loop Number : " + start + "<br>");
start++;
}while (start < 5);
</script>
- In above example, the condition is true.
- We will have one more example with false condition. In this example, it will execute the loop once. As it checks the condition at the time of exit, it will not execute the loop second time.
Example
<script type = "text/javascript">
var start = 1;
do
{
document.write("<b>Loop Number : " + start + "<br>");
start++;
}while (start > 5);
</script>
Output
For Loop
- The ‘for’ loop is the most compact form of looping. It includes the following three important parts:
- The loop initialization: where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.
- The test statement: which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop.
- The iteration statement: where you can increase or decrease your counter.
- You can put all the three parts in a single line separated by semicolons.
Syntax:
for (initialization; test condition; iteration statement) {
Statement(s) to be executed if test condition is true
}
Example:
<script type="text/javascript">
a=parseInt(prompt("Enter start value"));
b=parseInt(prompt("Enter end value"));
for(n=a;n<=b;n++)
{
document.write("<b>",n,"<br>");
}
</script>