Java Sript
Java Sript
JavaScript is the most popular and widely used client-side scripting language.
Client-side scripting refers to scripts that run within web browser. JavaScript is
designed to add interactivity and dynamic effects to the web pages by manipulating
the content returned from a web server.
MEAN stack.
based on JavaScript programming language, many frameworks and databases have been
developed. The most popular and trending now a days is MEAN stack.
M – MongoDB
E – Express (web application framework)
A – AngularJS
N – Node.js
<!DOCTYPE html>
<head>
<title>JavaScript Example</title>
<script>
document.write("welcome to javascript");
</script>
</head>
<body>
</body>
</html>
JavaScript Example
Variables are fundamental to all programming languages. Variables are used to store
data, like string of text, numbers, etc. The data or value stored in the variables
can be set, updated, and retrieved whenever needed.
You can create a variable with the var keyword, whereas the assignment operator (=)
is used to assign value to a variable
JavaScript Variable
A variable name must start with a letter, underscore (_), or dollar sign ($).
A variable name cannot start with a number.
A variable name can only contain alpha-numeric characters (A-z, 0-9) and
underscores.
A variable name cannot contain spaces.
A variable name cannot be a JavaScript keyword or a JavaScript reserved word.
Naming conventions for JavaScript Variables
Writing Output to Browser Console
You can easily outputs a message or writes data to the browser console using the
console.log()
Displaying Output in Alert Dialog Boxes
You can also use alert dialog boxes to display the message or output data to the
user.
Writing Output to the Browser Window
You can use the document.write() method to write the content to the current
document
Generating Output in JavaScript
Data types basically specify what kind of data can be stored and manipulated within
a program.
There are six basic data types in JavaScript which can be divided into three main
categories:
primitive
String
Number
Boolean
composite
Object
Array
special data types
Undefined
Null
Data Types in JavaScript
The undefined data type can only have one value-the special value undefined. If a
variable has been declared, but has not been assigned a value, has the value
undefined.
var a;
document.write(a);
The Undefined Data Type
This is another special data type that can have only one value-the null value. A
null value means that there is no value. It is not equivalent to an empty string
("") or 0, it is simply nothing.
var x = null;
document.write(x + "<br>");
The Null Data Type
The arithmetic operators are used to perform common arithmetical operations, such
as addition, subtraction, multiplication etc.
Operator
Description
Example
Result
+
Addition
x + y
Sum of x and y
-
Subtraction
x - y
Difference of x and y.
*
Multiplication
x * y
Product of x and y.
/
Division
x / y
Quotient of x and y
%
Modulus
x % y
Remainder of x divided by y
JavaScript Arithmetic Operators
Operator
Description
Example
Is The Same As
=
Assign
x = y
x = y
+=
Add and assign
x += $
x = x + y
-=
Subtract and assign
x -= y
x = x - y
*=
Multiply and assign
x *= y
x = x * y
/=
Divide and assign quotient
x /= y
x = x / y
%=
Divide and assign modulus
x %= y
x = x % y
JavaScript Assignment Operators
The comparison operators are used to compare two values in a Boolean fashion.
Operator
Name
Example
Result
==
Equal
x == y
True if x is equal to y
!=
Not equal
x != y
True if x is not equal to y
<
Less than
x < y
True if x is less than y
>
Greater than
x > y
True if x is greater than y
>=
Greater than or equal to
x >= y
True if x is greater than or equal to y
<=
Less than or equal to
x <= y
True if x is less than or equal to y
JavaScript Comparison Operators
Operator
Name
Example
Result
&&
And
x && y
True if both x and y are true
||
Or
x || y
True if either x or y is true
!
Not
!x
True if x is not true
JavaScript Logical Operators
There are several conditional statements in JavaScript that you can use to make
decisions:
The if statement
The if...else statement
The if...else if....else statement
The switch...case statement
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
If example
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
if else example
<script>
var subject = "OS";
<script>
var grade = 'A';
switch (grade) {
case 'A':
document.write("Good job<br />");
break;
case 'B':
document.write("Pretty good<br />");
break;
case 'D':
document.write("Not so good<br />");
break;
case 'F':
document.write("Failed<br />");
break;
default:
document.write("Unknown grade<br />")
}
</script>
switch … case statement example
Loop statements are used to execute a block of code repeatedly for a number of
times, or execute a block of code for each item in an iterable, etc.
Loops are used to execute the same block of code again and again, as long as a
certain condition is met.
while — loops through a block of code as long as the condition specified evaluates
to true.
do…while — loops through a block of code once; then the condition is evaluated. If
the condition is true, the statement is repeated as long as the specified condition
is true.
for — loops through a block of code until the counter reaches a specified number
Different types of Loops in JavaScript
While loop is used to execute a block of code a number of times in a loop, based on
a condition.
As soon as the condition fails, the loop is stopped.
where condition is the expression which is checked before executing the statements
inside while loop.
#
while (condition)
{
Statements to be executed if expression is true
}
<script>
var i = 1;
while(i <= 5) {
document.write("<p>The number is " + i + "</p>");
i++;
}
</script>
while loop example
The do-while loop is a variant of the while loop, which evaluates the condition at
the end of each loop iteration. With a do-while loop the block of code executed
once.
do
{
Statements to be executed;
} while (expression);
The for loop is the most compact form of looping and 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 the given condition is true or not. If
condition is true then code given inside the loop will be executed otherwise loop
will come out.
The iteration statement where you can increase or decrease your counter.
You can put all the three parts in a single line separated by a semicolon.
for loop
<script type="text/javascript">
var count;
for(count = 0; count < 10; count++)
{
document.write("Current Count : " + count );
document.write("<br />");
}
</script>
<script type="text/javascript">
for (i=0;i<10;i++)
{
if (i==3)
{
break;
}
document.write( "The number is " + i + "<br>");
}
</script>
break statment
The continue statement breaks one iteration (in the loop), if a specified condition
occurs, and continues with the next iteration in the loop.
e.g.
<script type="text/javascript">
for (i=0;i<10;i++)
{
if (i==3)
{
continue;
}
continue statement
A function is a group of statements that perform specific tasks and can be kept and
maintained separately form main program. Functions provide a way to create reusable
code which are more portable and easier to debug.
The declaration of a function start with the function keyword, followed by the name
of the function you want to create, followed by parentheses i.e. () and finally
place your function's code between curly brackets {}.
// Defining function
function sayHello() {
alert("Hello, welcome to this website!");
}
// Calling function
sayHello(); // 0utputs: Hello, welcome to this website!
Defining and Calling a Function example
You can specify parameters when you define your function to accept input values at
run time. The parameters work like placeholder variables within a function; they're
replaced at run time by the values (known as argument) provided to the function at
the time of invocation.
Adding Parameters to Functions
<!DOCTYPE html>
<head>
<title>JavaScript Add Parameters to a Function</title>
</head>
<body>
<script>
// Defining function
function displaySum(num1, num2) {
var total = num1 + num2;
document.write(total);
}
// Calling function
displaySum(6, 20); // Prints: 26
document.write("<br>");
displaySum(-5, 17); // Prints: 12
</script>
</body>
</html>
Adding Parameters to Functions example
A function can return a value back to the script that called the function as a
result using the return statement. The value may be of any type, including arrays
and objects.
Returning Values from a Function
// Defining function
function getSum(num1, num2) {
var total = num1 + num2;
return total;
}
JavaScript String
The JavaScript string is an object that represents a sequence of characters.
<script>
var str="javascript";
document.write(str.charAt(2));
</script>
charAt()
<script>
var s1="javascript ";
var s2="concat example";
var s3=s1.concat(s2);
document.write(s3);
</script>
Concat()
<script>
var s1="javascript from w3c";
var n=s1.indexOf("from");
document.write(n);
</script>
indexOf()
<script>
var s1="JavaScript toLowerCase Example";
var s2=s1.toLowerCase();
document.write(s2);
</script>
toLowerCase()
<script>
var s1="JavaScript toUpperCase Example";
var s2=s1.toUpperCase();
document.write(s2);
</script>
toUpperCase()
<script>
var s1=" javascript trim ";
var s2=s1.trim();
document.write(s2);
</script>
Trim()
The JavaScript date object can be used to get year, month and day.
You can use different Date constructors to create date object. It provides methods
to get and set day, month, year, hour, minute and seconds.
JavaScript Date Object
<script>
var date=new Date();
var day=date.getDate();
var month=date.getMonth()+1;
var year=date.getFullYear();
document.write("<br>Date is: "+day+"/"+month+"/"+year);
</script>
The JavaScript math object provides several constants and methods to perform
mathematical operation.
document.write( Math.sqrt(17)) ;
document.write(Math.random()) ;
JavaScript Math example