Javascript
Javascript
what is JavaScript?
JavaScript is a programming language that adds interactivity to your
website (for example games, responses when buttons are pressed or
data is entered in forms, dynamic styling, and
animation). JavaScript (JS) is a programming language mostly used to
dynamically script webpages on the client side, but it is also often utilized
on the server-side, using packages such as Node.js.
JavaScript should not be confused with the Java programming language.
Using document.write()
For testing purposes, it is convenient to use document.write()
Using document.write() after an HTML document is loaded, will delete
all existing HTML. The d ocument.write() method should only be used
for testing.
Using window.alert()
You can use an alert box to display data
Using console.log()
For debugging purposes, you can use the console.log() method to display
data.
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.
JavaScript | Syntax
JavaScript is the lightweight and dynamic computer programming language. It is used to create
client side dynamic pages. It is open source and cross-platform language.
Basic Syntax:
<script> Document.write(“hello”); </script>
JavaScript Variables: A JavaScript variable is the simple name of storage location where data to
be stored. There are two types of variables in JavaScript which are listed below:
• Local variables: Declare a variable inside of block or function.
• Global variables: Declare a variable outside function or with window object.
• JavaScript Operator: JavaScript operators are symbols that are used to compute the value or in
other word we can perform operations on operands. Arithmetic operators ( +, -, *, / ) are used
to compute the value and Assignment operator ( =, +=, %= ) are used to assign the values to
variables.
JavaScript Expression: Expression is the combination of values, operators and variables. It is used to
compute the values.
JavaScript Comments: The comments are ignored by JavaScript compiler. It increase the readability of
code. It adds suggestions, Information and warning of code. Anything written after double slashes //
(single line comment) or between /* and */ (multi line comment) is treated as comment and ignored by
JavaScript compiler.
JavaScript Data Types: JavaScript provides different datatype to hold different values on variable.
JavaScript is a dynamic programming language, it means do not need to specify the type of variable.
There are two types of data types in JavaScript.
•Primitive data type
•Non-primitive (reference) data type
•JavaScript Functions: JavaScript functions are the blocks of code used to perform some particular
operations. JavaScript function is executed when something call it. It calls many times so the function is
reusable.
JavaScript Variables:
JavaScript Variables: JavaScript variables are containers for storing data values.
In this example, x, y, and z, are variables
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).
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 are case sensitive (y and Y are different variables)
➢ Reserved words (like JavaScript keywords) cannot be used as names
➢ JavaScript identifiers are case-sensitive.
EXAMPLE:
var x = 5;
var y = 6;
var sum= x + y;
<html>
<head>
<title> Varibales in JavaScript</title>
<meta charset="utf-8">
<script type="text/javascript">
var a= 100; var b= 10.124; var c="JAVASCRIPT";
var d = 'java Script' var e = true; var f = false;
console.log(a);
console.log(b);
console.log(c);
console.log(d);
console.log(e);
console.log(f);
</script>
<</head>
<body>
<h1> Hello JavaScript </h1>
<h2> This is my second Program in JavaScript</h2>
</body>
</html>
•Local Variable: When you use JavaScript, local variables are variables that are defined within functions. They
have local scope, which means that they can only be used within the functions that define them.
•Global Variable: In contrast, global variables are variables that are defined outside of functions. These variables
have global scope, so they can be used by any function without passing them to the function as parameters.
Syntax :
function functionName(parameter1, parameter2,……….) (parameters also a optional)
{
statements return (value); (return value is a optional
}
functionName(); //function call
)//type-1 function with return value
function test1(a)
{
return a;
}
console.log("a1:",test1(10));
var test2=function(a)
{
return a;
}
console.log("a2:",test2(20));
var test3=a=>a;
console.log("a3:",test3(30));
“ARGUMENTS” – PREDEFINED VARIABLE :- It is used to represent all the argument
values that are received by the current function.
It is a pre-defined variable that can be used only in the functions.
function sample(a,b)
{
console.log(arguments);
console.log(a); // output : 10
console.log(arguments[0]); // output : 10
console.log(b); // output : 20
console.log(arguments[1]); // output : 20
console.log(arguments[6]); // output : Undefined means not decleared
}
Sample(10,20,30,40,50,60);
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>javascript</title>
<link rel="stylesheet" href="javascript.css">
<script src="javascript.js"></script>
</head>
<body>
<h2 id="h">welcome to javascript</h2>
<input type="button" value="changetoblue" onclick="changeBlue()">
<input type="button" value="changetored" onclick="changeRed()">
<input type="button" value="changecolor" onclick="changeColor()">
<br><br>
<img src="pics/img.jpg" id="i" alt="no img" height="70px" width="70px">
<br>
<input type="button" value="happy" onclick="changeHappy()">
<input type="button" value="sad" onclick="changeSad()">
<script>
function changeBlue()
{
document.getElementById("h").style.color="blue";
}
function changeRed()
{
document.getElementById("h").style.color="red";
}
function changeColor()
{
var c=prompt("Enter color","");
document.getElementById("h").style.color=c;
}
function changeHappy()
{
document.getElementById("i").src="pics/html5.png";
}
function changeSad()
{
document.getElementById("i").src="pics/css3.png";
}
</script>
</body>
CONTROL STATEMENTS :
CONTROL STATEMENTS:
By default, all the statements executes in sequential order (top – to – bottom) In order
to change (control) the execution flow of the statements. We have to use control
statements.
Types of Control Statements:-
a. Conditional Control Statements (Conditional Operator (? :))
b. Looping Control Statements
a. Conditional Control Statements :- Conditional control statements divided into 2
types (things)
1. If
2. Switch case
b. Looping Control Statements: Looping control Statements are 3 types (things)
1. While
2. Do-while
3. for
a. Conditional Control Statements:
I) “If” Conditional control statement:- If you want to check the condition first, and execute
the statements only when the condition is TRUE, then use “if”.
0. If (simple if)
1. If-else
2. Else-if
3. Nested if
if (simple if):- simple check the condition, if the condition is true only you want the execute
the statements. The condition is false , Don’t execute the statements.
Syntax:
if (expression)
{
Statement(s) to be executed if expression is true ;
}
If-else :-
Syntax :
if (expression)
{ Statement(s) to be executed if expression is true }
else
{ Statement(s) to be executed if expression is false }
else-if :- The if...else if... statement is an advanced form of if…else that allows JavaScript to make
a correct decision out of several conditions
Syntax:
if (expression 1)
{ Statement(s) to be executed if expression 1 is true }
else if (expression 2)
{ Statement(s) to be executed if expression 2 is true }
Nested if example:
if (a>=b)
{
if (a==b)
{
console.log("a is equal to b");
}
else
{
console.log("a is greater than b");
}
}
else
{
console.log("a is less than b");
}
2)Switch..Case :The objective of a switch statement is to give an expression to evaluate and several different
statements to execute based on the value of the expression. The interpreter checks each case against the value
of the expression until a match is found. If nothing matches, a default condition will be used.
Syntax:
switch (expression)
{
case value1: statement(s) to be executed; break;
case value2: statement(s) to be executed; break;
...
default: statement(s);
break; //it is optional to write break, if default is the last statement in the switch block
}
b.Looping Control Statement :-
The while Loop :The most basic loop in JavaScript is the 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.
Note: the expression has to be true in the beginning to enter the loop. The syntax of while loop in JavaScript is
as follows −
Syntax:
while (expression)
{
Statement(s) to be executed if expression is true
}
The do...while Loop: The do...while loop is similar to the while loop except that the condition check
happens at the end of the loop. This means that the loop will always be executed at least once, even if
the condition is false.
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.
Syntax:
for (initialization; test condition; iteration statement)
{
Statement(s) to be executed if test condition is true
}
JAVASCRIPT ARRAYS
The Array object lets you store multiple values in a single variable. It stores a fixed-size sequential
collection of elements of the same type. An array is used to store a collection of data, but it is often
more useful to think of an array as a collection of variables of the same type.
Syntax:- Use the following syntax to create an Array object −
var fruits = new Array["apple", "orange", "mango" ];
Some important properties and methods of an Array:
1. length: returns the length(size) of an Array
2. pop() : Removes the last element from an array and returns that element.
3. push() : Adds one or more elements to the end of an array and returns the new length of the array.
4. toString() : converts an array to a string of (comma separated) array values.
5. join() : joins all array elements into a string. it behaves just like toString(), but in addition you can
specify the separator. E.g. fruits.join(" * ");
6. sort() : sorts an array alphabetically in ascending order
7. reverse(): reverses the elements in an array. You can use it to sort an array in descending order
Objects in Javascript
Objects, in JavaScript, is it’s most important data-type and forms the building blocks for modern JavaScript. These
objects are quite different from JavaScript’s primitive data-types(Number, String, Boolean, null, undefined and symbol)
in the sense that while these primitive data-types all store a single value each (depending on their types).
Creating Objects:
There are several ways or syntax’s to create objects. One of which, known as the Object literal syntax, we have already
used. Besides the object literal syntax, objects in JavaScript may also be created using the constructors, Object
Constructor or the prototype pattern.
1.Using the Object literal syntax : Object literal syntax uses the {…} notation to initialize an object an its
methods/properties directly.
Let us look at an example of creating objects using this method :
var obj =
{
Key1 : value1,
key2 : value2,
};
These members can be anything – strings, numbers, functions, arrays or even other objects. An object like this is referred
to as an object literal. This is different from other methods of object creation which involve using constructors and classes
or prototypes, which have been discussed below.
2.Object Constructor : Another way to create objects in JavaScript involves using the
“Object” constructor. The Object constructor creates an object wrapper for the given value.
This, used in conjunction with the “new” keyword allows us to initialize new objects.