Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 12

JAVASCRIPT

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.

It is supported by all web browsers available today, such as Google Chrome,


Mozilla Firefox, Apple Safari, etc.
JavaScript is an object-oriented language, and it also has some similarities in
syntax to Java programming language
Introduction to JavaScript

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

JavaScript consists of JavaScript statements that are placed within the


<script></script>
Case Sensitivity in JavaScript
JavaScript Comments
Single-line comments begin with a double forward slash (//)
a multi-line comment begins with a slash and an asterisk (/*) and ends with an
asterisk and slash (*/).
JavaScript Syntax

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

The assignment operators are used to assign values to variables.

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

JavaScript Conditional Statements

If expression is true, then set of statements are executed. Else execution


continues with the statements after if-statement.
if statement

<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
If example

It is an extension to Javascript If statement. When the condition is false, another


set of statements are executed.
#
The if … else statement

<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

The if...else if...else a special statement that is used to combine multiple


if...else statements.
It is an extension to Javascript If-Else statement. Instead of a single condition,
there are multiple conditions.
The if …else if … else statement

<script>
var subject = "OS";

if( subject == "CJ" ) {


document.write("<b>CORE JAVA</b>");
} else if( subject == "WP" ) {
document.write("<b>WEB PROGRAMMING</b>");
} else if( subject == "OS" ) {
document.write("<b>OPERATING SYSTEM</b>");
} else {
document.write("<b>Unknown Subject</b>");
}
</script>
The if …else if … else statement

JavaScript Switch statement is used to execute different set of statements based on


different conditions. It is similar to If-Else statement, but excels in code
simplicity and works greatly with numbers, characters and Strings.
#
switch … case statement

<script>
var grade = 'A';

switch (grade) {
case 'A':
document.write("Good job<br />");
break;

case 'B':
document.write("Pretty good<br />");
break;

case 'C': document.write("Passed<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
}

The while loop

<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 do…while loop


<script>
var i = 1;
do {
document.write("<p>The number is " + i + "</p>");
i++;
}
while(i <= 5);
</script>
The do…while loop example

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

for (initialization; test condition; iteration statement)


{
Statement(s) to be executed if test condition is true
}
for loop syntax

<script type="text/javascript">
var count;
for(count = 0; count < 10; count++)
{
document.write("Current Count : " + count );
document.write("<br />");
}
</script>

for loop example

The break statement can also be used to jump out of a loop.

<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;
}

document.write( "The number is " + i + "<br>");


}
</script>

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.

Advantages of using functions:


Functions reduces the repetition of code within a program
Functions makes the code much easier to maintain
Functions makes it easier to eliminate the errors
JavaScript Functions

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 {}.

function functionName() {# // Code to be executed#}


Defining and Calling a Function

// 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

function functionName(parameter1, parameter2, parameter3) {


// Code to be executed
}
Adding Parameters to Functions syntax

<!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;
}

// Displaying returned value


alert(getSum(6, 20)); // 0utputs: 26
alert(getSum(-5, 17)); // 0utputs: 12
Returning Values from a Function example

JavaScript String
The JavaScript string is an object that represents a sequence of characters.

var stringname="string value";


Or
var stringname=new String("hello javascript string");
JavaScript String

It provides the char value present at the specified index.


charAt()
It provides a combination of two or more strings.
concat()
It provides the position of a char value present in the given string.
indexOf()
It is used to fetch the part of the given string on the basis of the specified
index.
substring()
It converts the given string into lowercase letter.
toLowerCase()
It converts the given string into uppercase letter.
toUpperCase()
It provides a string representing the particular object..
toString()
JavaScript String methods

<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

JavaScript Date Methods


It returns the integer value between 1 and 31 that represents the day for the
specified date.
getDate()
It returns the integer value between 0 and 6 that represents the day of the week.
getDay()
It returns the integer value that represents the year.
getFullYears()
It returns the integer value that represents the hours.
getHours()
It returns the integer value that represents the milliseconds.
getMilliseconds()
It returns the integer value that represents the minutes.
getMinutes()
It returns the integer value between 0 and 11 that represents the month.
getMonth()
It returns the integer value between 0 and 60 that represents the seconds
getSeconds()
JavaScript Date methods

<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>

JavaScript Date methods example

Current Time: <span id="txt"></span>


<script>
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
</script>

JavaScript Date methods example

The JavaScript math object provides several constants and methods to perform
mathematical operation.

It returns the absolute value of the given number.


abs()
It returns maximum value of the given numbers.
max()
It returns minimum value of the given numbers.
min()
It returns random number between 0 (inclusive) and 1
random()
It returns closest integer value of the given number.
round()
It returns the square root of the given number
sqrt()
JavaScript Math object

document.write( Math.sqrt(17)) ;
document.write(Math.random()) ;
JavaScript Math example

You might also like