JAVA SCRIPT SUDHAKAR SHARMA(1)
JAVA SCRIPT SUDHAKAR SHARMA(1)
- JavaScript is a language.
- It is an open source, cross platform, interpreted and just-in-time
compiled programming language.
- Interpreter is a translated that translates line by line.
- Just-in-time is a compiler that compiles in browser when requested by
client.
- V8 is JavaScript compiler.
- JavaScript is used
o Client Side with HTML
o Server Side with Node.js
o Database with MongoDB
o Animations with Flash
- JavaScript supports various types of programming like, imperative,
functional programming, structural programming and object-oriented
programming.
- In early 1994 Brendan Eich introduces a script called “Mocha” for
Netscape browser.
- After that “Moca” was renamed into “Live Script”
- 1995 Sun Microsystems took responsibility of maintaining Live Script and
re-named as “JavaScript”.
- JavaScript Designed by “Brendan Eich”
- JavaScript initially belong to “Netscape communications”.
- JavaScript follows the standards of “ECMA” [European Computer
Manufacturers Association].
- JavaScript versions are ECMAScript 2015, ES6, ES8 ES2020
- ES5, ES6 are most commonly used versions in various web technologies.
- ES6
Issues with JavaScript
- Browser incompatibility: Every browser has its own extensions to
JavaScript and every browser have its own parser [translator].
- JavaScript is not secured: It is client side. Everyone can view.
- JavaScript can be disabled by browser. [Browser can block JavaScript].
- JavaScript is not strongly typed language.
var x = 10; // number
x = “John”; // string – valid
JavaScript with HTML
- JavaScript is used to manipulate the HTML DOM.
- It converts the static DOM elements into dynamic DOM elements.
- JavaScript can add elements, remove elements, modify the data, handle
validations, handle plugins, browser location, history etc.
- JavaScript can reduce burden on server by managing several interactions
client-side.
JavaScript Inline:
- JavaScript functions are defined within the element.
- They are faster as they are local to element.
- They can’t be re-used.
Ex:
<!DOCTYPE html>
<html>
<head>
<title>Inline</title>
</head>
<body>
<h2>Click Print Button to Print Page</h2>
<button onclick="window.print()">Print Page</button>
</body>
</html>
JavaScript Embedded:
- You can write the JavaScript functions and embed into page by using
<script> element.
- You can embed in head section or body section.
- You can re-use the functions across the page from any element.
Ex:
<!DOCTYPE html>
<html>
<head>
<title>Inline</title>
<script>
function PrintPage(){
window.print();
}
</script>
</head>
<body>
<h2>Click Print Button to Print Page</h2>
<button onclick="PrintPage()">Print Page</button>
<button onclick="PrintPage()">Print</button>
</body>
</html>
- Embedded scripts require MIME type to define.
- The JavaScript MIME type is “text/javascript” or “language=JavaScript”
Syntax:
<script type="text/javascript" language="javascript">
function PrintPage(){
window.print();
}
</script>
JavaScript Strict Mode:
- JavaScript is recommended to write in “Strict” mode.
- It reduces the code inconsistency.
- You can turn ON strict mode by using “use strict” in the code.
Ex:
<script>
"use strict";
function f1()
{
x = 10; // x is not declared as variable
document.write("x=" + x);
}
f1();
</script>
Note: remove “use strict” from <script> element, the above code will
work normally. In strict mode you have to declare a variable “var x”.
Ex:
<!DOCTYPE html>
<html>
<head>
<style>
.effects {
background-color: yellow;
}
</style>
<title>Reference</title>
<script type="text/javascript">
function bodyload(){
x = document.getElementsByName("pay");
alert("Total Payment Methods: " + x.length);
}
</script>
</head>
<body onload="bodyload()">
<fieldset>
<legend>Payment</legend>
<input type="radio" name="pay" value="Cash"> Cash
<input type="radio" name="pay" value="UPI"> UPI
<input type="radio" name="pay" value="Credit Card"> Credit Card
</fieldset>
</body>
</html>
alert():
It is used to display output in a message box.
User have to confirm the message in order to continue.
Syntax:
alert(“message/ expression”);
You can’t cancel alert. “esc” key is similar to OK.
EX:
<!DOCTYPE html>
<html>
<head>
<style>
.effects {
background-color: yellow;
}
</style>
<title>Reference</title>
<script type="text/javascript">
function DeleteClick(){
alert("Record Deleted");
}
</script>
</head>
<body>
<button onclick="DeleteClick()">Delete</button>
</body>
</html>
confirm():
It is similar to alert, but provides option to cancel the message.
It returns true on OK and false on Cancel.
Ex:
<!DOCTYPE html>
<html>
<head>
<style>
.effects {
background-color: yellow;
}
</style>
<title>Reference</title>
<script type="text/javascript">
function DeleteClick(){
x = confirm("Are you sure want to Delete?");
if(x==true){
alert("Record Deleted");
} else {
alert("Canceled..");
}
}
</script>
</head>
<body>
<button onclick="DeleteClick()">Delete</button>
</body>
</html>
document.write()
It is used to print output in a new screen of same page.
The output is erased when you refresh the page.
EX:
<!DOCTYPE html>
<html>
<head>
<style>
.effects {
background-color: yellow;
}
</style>
<title>Reference</title>
<script type="text/javascript">
function DeleteClick(){
x = confirm("Are you sure want to Delete?");
if(x==true){
document.write("Record Deleted");
} else {
alert("Canceled..");
}
}
</script>
</head>
<body>
<button onclick="DeleteClick()">Delete</button>
</body>
</html>
Ex:
<!DOCTYPE html>
<html>
<head>
<style>
.effects {
background-color: yellow;
}
</style>
<title>Reference</title>
<script type="text/javascript">
function DeleteClick(){
x = confirm("Are you sure want to Delete?");
if(x==true){
document.getElementById("msg").innerText="<font
color='red'>Record Deleted</font>";
} else {
alert("Canceled..");
}
}
</script>
</head>
<body>
<button onclick="DeleteClick()">Delete</button>
<p align="center" id="msg"></p>
</body>
</html>
Ex:
<!DOCTYPE html>
<html>
<head>
<style>
.effects {
background-color: yellow;
}
</style>
<title>Reference</title>
<script type="text/javascript">
function DeleteClick(){
x = confirm("Are you sure want to Delete?");
if(x==true){
document.getElementById("msg").innerHTML="<font
color='red'>Record Deleted</font>";
} else {
alert("Canceled..");
}
}
</script>
</head>
<body>
<button onclick="DeleteClick()">Delete</button>
<p align="center" id="msg"></p>
</body>
</html>
innerHTML will add inside existing element.
outerHTML will add by replacing existing element.
Ex:
<!DOCTYPE html>
<html>
<head>
<style>
.effects {
background-color: yellow;
}
</style>
<title>Reference</title>
<script type="text/javascript">
function DeleteClick(){
x = confirm("Are you sure want to Delete?");
if(x==true){
document.getElementById("msg").outerHTML="<h2><font
color='red'>Record Deleted</font></h2>";
} else {
alert("Canceled..");
}
}
</script>
</head>
<body>
<button onclick="DeleteClick()">Delete</button>
<p align="center" id="msg"></p>
</body>
</html>
Console options
<!DOCTYPE html>
<html>
<head>
<style>
.effects {
background-color: yellow;
}
</style>
<title>Reference</title>
<script type="text/javascript">
function DeleteClick(){
x = confirm("Are you sure want to Delete?");
console.info("Delete Initiated");
if(x==true){
console.error("Delete Completed");
document.getElementById("msg").outerHTML="<h2><font
color='red'>Record Deleted</font></h2>";
} else {
alert("Canceled..");
console.warn("Canceld action");
}
}
</script>
</head>
<body>
<button onclick="DeleteClick()">Delete</button>
<p align="center" id="msg"></p>
</body>
</html>
Ex:
<!DOCTYPE html>
<html>
<head>
<title>Input</title>
<style>
label {
font-weight: bold;
}
.box{
width: 300px;
justify-content: center;
align-items: center;
margin: auto;
}
</style>
<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/bootstrap.css">
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script
src="../node_modules/bootstrap/dist/js/bootstrap.bundle.js"></script>
<script>
function RegisterClick(){
document.getElementById("lblName").innerText =
document.getElementById("txtName").value;
document.getElementById("lblPrice").innerText =
document.getElementById("txtPrice").value;
document.getElementById("lblCity").innerText =
document.getElementById("lstCities").value;
stock = document.getElementById("optStock");
status = "";
if(stock.checked){
status = "Available";
} else {
status = "Out of Stock";
}
document.getElementById("lblStock").innerText = status;
document.getElementById("lblMfd").innerText =
document.getElementById("txtMfd").value;
}
</script>
</head>
<body class="container-fluid">
<div class="box">
<form>
<h2 class="text-primary text-center">Register Product</h2>
<div class="form-group">
<label>Name</label>
<div>
<input type="text" id="txtName" class="form-control">
</div>
</div>
<div class="form-group">
<label>Price</label>
<div>
<input type="text" id="txtPrice" class="form-control">
</div>
</div>
<div class="form-group">
<label>Shipped To</label>
<div>
<select id="lstCities" class="form-control">
<option value="Delhi">Delhi</option>
<option value="Hyderabad">Hyderabad</option>
</select>
</div>
</div>
<div class="form-group">
<label>Manufactured</label>
<div>
<input type="date" id="txtMfd" class="form-control">
</div>
</div>
<div class="form-group">
<label>In Stock</label>
<div>
<input type="checkbox" id="optStock"> Yes
</div>
</div>
<div class="form-group">
<button onclick="RegisterClick()" type="button" data-
target="#summary" data-toggle="modal" class="btn btn-primary btn-
block">Register</button>
</div>
</form>
</div>
<div class="modal fade" id="summary">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h2>Product Details</h2>
<button class="close" data-dismiss="modal" >x</button>
</div>
<div class="modal-body">
<table class="table table-hover">
<tr>
<td>Name</td>
<td id="lblName"></td>
</tr>
<tr>
<td>Price</td>
<td id="lblPrice"></td>
</tr>
<tr>
<td>Shipped To</td>
<td id="lblCity"></td>
</tr>
<tr>
<td>Stock</td>
<td id="lblStock"></td>
</tr>
<tr>
<td>Manufactured</td>
<td id="lblMfd"></td>
</tr>
</table>
</div>
<div class="modal-footer">
<button data-dismiss="modal" class="btn btn-
primary">OK</button>
</div>
</div>
</div>
</div>
</body>
</html>
JavaScript Language Basics
- Variables
- Data Types
- Operators
- Statements
- Functions
Variables in JavaScript
- Variables are storage locations in memory where you can store a value
and use it as a part of any expression.
- Variables configuration contains 3 stages
o Declaration
o Assigning or Rendering
o Initialization
}
f1();
</script>
- Let allows declaration, rendering, initialization.
Ex:
<script>
"use strict";
function f1(){
let x = 10; // intialization
if(x==10) {
let y; // declaration
y = 20; // rendering
document.write("X=" + x + "<br>" + "Y=" + y);
}
}
f1();
</script>
- Let will not allow shadowing.
- There can’t be same name identifier with in the scope.
<script>
"use strict";
function f1(){
let x = 10; // intialization
if(x==10) {
let x = 20;
let x = 30; // invalid – shadowing not
allowed
let y; // declaration
y = 20; // rendering
document.write("X=" + x + "<br>" + "Y=" + y);
}
}
f1();
</script>
- Let will not allow hoisting.
Ex:
<script>
"use strict";
function f1(){
x = 10;
document.write("X=" + x);
let x; // Not Allowed
}
f1();
</script>
const:
- It is also a block scope variable.
- It will allow only initialization, no declaration, no rendering.
- It will not allow shadowing.
- It will not allow hoisting.
Ex:
<script>
"use strict";
function f1(){
const x; // not allowed
x= 10;
document.write("x=" + x);
}
f1();
</script>
Ex:
<script>
"use strict";
var x = 10;
let y = 20;
const z = 30;
function f1(){
window.a = 40; //window refers to browser
document.write(`f1 values: <br>
x=${x}<br>y=${y}<br>z=${z}<br>a=${a}<br>`);
}
function f2(){
document.write(`f2 values: <br> x=${x}<br>y=${y}<br>z=${z}<br>a=${a}`);
}
f1();
f2();
</script>
Variables Naming
- Variable name must start with an alphabet or underscore _
- It can be alpha numeric, but can’t start with number.
Syntax:
var jan2020 = 12000;
var 2020jan = 23000; invalid
var _2020jan = 34000; valid
var jan_2020 = 34000; valid
FAQ: Why underscore is supported? What underscore means?
A. Underscore is special symbol that doesn’t have any compile time issues.
underscore is used by developers to indicate that the variable
requires
further implementation.
“Marked for Implementation”
- ECMA standards prefer variable name length maximum 255 chars.
- Variable name must speak what it is.
- Always use camel case for naming references.
class EmployeeSalary
{
}
var employeeSalary = new Employee();
var txtName;
var txtPassword;
var btnSubmit;
Data Types
- Data type determines the data structure.
- Data structure specifies the size and behaviour of value in memory.
- Data Type uses a data structure to define the type of value that can be
stored in memory.
- JavaScript is implicitly typed; the data type is determined according to
the value assigned. There is no specific built-in type.
- JavaScript is not strongly typed, you can store any contradictory values.
Syntax:
var x = “John”; //string
x = 10; // valid and x changes to number
What type of values JavaScript can handle?
The JavaScript data types are classified into 2 groups
- Primitive Types
- Non-Primitive Types
Primitive Types
- Primitive types are stored in memory stack. [LIFO]
- They have a fixed range for values.
- They are Immutable types.
- Their values can’t change according to state and situation.
- JavaScript primitive types are
o Number
o String
o Boolean
o Null
o Undefined
Number Type:
- Number type is used to handle a numeric value.
- JavaScript number type can allow
o Signed Integer
var x = -10;
var x = +10;
o Unsigned Integer
var x = 10;
o Floating point
var x = 4.5;
var x = 33.55;
o Double
var x = 553.558
o Decimal
var x = 45600.6669594; [29 decimal places]
o Hexa
0xf00d
o Binary
0b1010
o Octa
0o744
o Exponent
Var x = 2e3; [2 x 103] = 2000
BigInt = 100n; [Binary Data – images - complex]
Ex:
<script>
"use strict";
function f1(){
document.write(`Min Integer: ${Number.MIN_SAFE_INTEGER} <br> Max
Integer: ${Number.MAX_SAFE_INTEGER}`);
}
f1();
</script>
Validating Numbers
- The operator “typeof” is used to verify and return the data type of variable.
- IsNaN() is a JavaScript that verifies whether the give value is a number or any other type.
- Every value you entered in form element will be “string” type.
- You have to convert the string into number by using the functions
o parseInt()
o parseFloat()
Ex:
<script>
var x = 10;
var y = "4";
if(isNaN(y)){
document.write("Invalid Number");
} else {
var z = x * y;
document.write("z=" + z);
</script>
Ex:
<script>
if(isNaN(y)){
document.write("Invalid Number");
} else {
var z = x * y;
document.write("z=" + z);
</script>
String Type
- String is a literal with group of characters enclosed in Quotes.
- JavaScript string can be enclosed in
o Single Quote ‘ ‘
o Double Quote “ “
o Back Tick ` `
- Single and double quotes are used to swap between inner and outer
string.
Ex:
<script>
"use strict";
function f1(){
var link = "<a href='home.html'>Home</a>";
document.write(link);
}
f1();
</script>
Ex:
<script>
"use strict";
function f1(){
var link = '<a href="home.html">Home</a>';
document.write(link);
}
f1();
</script>
Back Tick:
- Back Tick [` `] is available from ES5
- It is used to define a string with embedded expression.
- Expression can be embedded with “${}”
- Expression can’t be embedded into string with single or double quote.
Ex:
<script>
"use strict";
function f1(){
var age = 20;
var year = 2020;
document.write("You will be" + " " + (age+1) + " " + "Next Year" + " " +
(year+1) + "<br>");
document.write(`You will be ${age+1} Next Year ${year+1}`);
}
f1();
</script>
Ex:
<script>
"use strict";
function f1(){
var title = "Admin Login";
var login = `
<h2>${title}</h2>
<dl>
<dt>Name</dt>
<dd><input type="text"></dd>
<dt>Price</dt>
<dd><input type="text"></dd>
</dl>
<button>Login</button>
`;
document.write(login);
}
f1();
</script>
- Several special characters defined in a string will escape printing.
- To print the non-printable characters, we have to use “\”.
Ex:
<script>
"use strict";
function f1(){
var path = "\"D:\\Images\\Pics\\mobile.jpg\"";
document.write(path);
}
f1();
</script>
Ex:
<script>
"use strict";
function f1(){
alert("Hello \n Welcome \n to \n JavaScript");
document.write("Hello ! <br> Welcome");
}
f1();
</script>
Note: The numbers or the values that you access from any element are string
type. You have to convert the string into number to handle expressions.
JavaScript functions to convert string into number.
- parseInt()
- parseFloat()
Ex:
<!DOCTYPE html>
<html>
<head>
<title>String</title>
<script>
function Calculate(){
var txt1 = document.getElementById("txt1").value;
var txt2 = document.getElementById("txt2").value;
document.getElementById("result").innerHTML = parseFloat(txt1) +
parseFloat(txt2);
}
</script>
</head>
<body>
<dl>
<dt>Number-1</dt>
<dd><input id="txt1" type="text"></dd>
<dt>Number-2</dt>
<dd><input id="txt2" type="text"></dd>
</dl>
<button onclick="Calculate()">Calculate</button>
<h2 id="result"></h2>
</body>
</html>
String Manipulation Functions
- JavaScript string object provides a set of properties and methods that
are used to manipulate and format string.
- Manipulation methods
Method Description
charAt() It returns the character as specified index.
Syntax:
string.charAt();
Ex:
<script>
function f1(){
var str = "Welcome to JavaScript";
var char1 = str.charAt(0);
var char2 = str[1]; //New in ES5
document.write(`Char1=${char1}<br>Char2=${char2}`)
}
f1();
</script>
charCodeAt() It returns the character code of character at specified
index. ASCII code of characters are accessed.
A=65, Z=90
indexOf() Returns the first occurrence index number of specified
characters.
lastIndexOf() Returns the last occurrence index number of specified
char.
If the character not found then both methods return “-1”.
trim() It is used to remove the leading spaces in a string.
substring() It can extract a portion of string based on specified index. It
is similar to slice but will not allow negative values.
You can access right to left by using positive value.
Ex:
<script>
function f1(){
var str = "Welcome to JavaScript";
document.write(str.substring(7,0));
}
f1();
</script>
substr() It is a legacy method, will not allow the values right to left.
slice() It is used to extract a part of string and return a new string.
Syntax:
slice(startIndex, endIndex)
slice(startIndex); slice upto end.
Slice(-1); It returns the last character.
Slice(-4); It returns the last 4 chars.
split() It splits string at specific delimiter and returns an array of
substrings.
You can also restrict the number of items to split.
Syntax:
String.split(‘delimiter’, count)
Ex:
<script>
function f1(){
var mobiles = "9876543210,9988776655,9008833113";
var numbers = mobiles.split(',', 2);
for(var number of numbers) {
document.write(number + "<br>");
}
}
f1();
</script>
startsWith() It returns true if string starts with specified chars.
endsWith() It returns true if string ends with specified chars.
Ex:
<!DOCTYPE html>
<html>
<head>
<title>String</title>
<script>
function Verify(){
var txtEmail =
document.getElementById("txtEmail").value;
if(txtEmail.endsWith("gmail.com")) {
document.write("Your Gmail Verified..");
} else {
document.write("Only Gmail allowed");
}
}
</script>
</head>
<body>
<fieldset>
<legend>Your Email</legend>
<input type="text" id="txtEmail" placeholder="Only
Gmail Allowed">
<button onclick="Verify()">Submit</button>
</fieldset>
</body>
</html>
search() You can search for any char using a regular expression.
It returns the index number of searched string.
If character not found then it returns -1
Ex:
<script>
function f1(){
var str = "Welcome to JavaScript";
document.write(str.search(/javascript/i));
}
f1();
</script>
Ex:
<!DOCTYPE html>
<html>
<head>
<title>String Demo</title>
<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/bootstrap.css">
<script>
function VerifyName(){
var txtName = document.getElementById("txtName").value;
var msg = document.getElementById("msg");
var firstCharCode = txtName.charCodeAt(0);
if(firstCharCode>=65 && firstCharCode<=90) {
msg.innerHTML = "";
} else {
msg.innerHTML = "Name must start with Uppercase Letter";
}
}
function VerifyCard(){
var txtCard = document.getElementById("txtCard").value;
var firstChar = txtCard.charAt(0);
var cardLogo = document.getElementById("cardLogo");
if(firstChar=="4") {
cardLogo.src="../Images/visa.png";
} else if(firstChar=="5"){
cardLogo.src="../Images/master.png";
} else {
cardLogo.src="../Images/invalid.png";
}
}
</script>
</head>
<body class="container-fluid">
<div class="form-group">
<label>User Name</label>
<div>
<input onblur="VerifyName()" class="form-control"
placeholder="Name must start with Uppercase Letter" type="text"
id="txtName">
<div id="msg" class="text-danger"></div>
</div>
</div>
<div class="form-group">
<label>Card Number</label>
<div class="input-group">
<input onkeyup="VerifyCard()" type="text" id="txtCard" class="form-
control">
<div class="input-group-append">
<span class="input-group-text">
<img id="cardLogo" width="50" height="20">
</span>
</div>
</div>
</div>
</body>
</html>
Ex:
<!DOCTYPE html>
<html>
<head>
<title>String Demo</title>
<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/bootstrap.css">
<script>
function VerifyName(){
var txtName = document.getElementById("txtName").value;
var msg = document.getElementById("msg");
var firstCharCode = txtName.charCodeAt(0);
if(firstCharCode>=65 && firstCharCode<=90) {
msg.innerHTML = "";
} else {
msg.innerHTML = "Name must start with Uppercase Letter";
}
}
function VerifyCard(){
var txtCard = document.getElementById("txtCard").value;
var firstChar = txtCard.charAt(0);
var cardLogo = document.getElementById("cardLogo");
if(firstChar=="4") {
cardLogo.src="../Images/visa.png";
} else if(firstChar=="5"){
cardLogo.src="../Images/master.png";
} else {
cardLogo.src="../Images/invalid.png";
}
}
function VerifyEmail(){
var txtEmail = document.getElementById("txtEmail").value;
var emailError = document.getElementById("emailError");
var atPos = txtEmail.indexOf("@");
var dotPos = txtEmail.lastIndexOf(".");
if(atPos<=2 && (dotPos-atPos)<=2) {
emailError.innerHTML = "Error: @ missing or not at valid position in
email";
} else {
emailError.innerHTML = "Email Verified";
}
}
</script>
</head>
<body class="container-fluid">
<div class="form-group">
<label>User Name</label>
<div>
<input onblur="VerifyName()" class="form-control"
placeholder="Name must start with Uppercase Letter" type="text"
id="txtName">
<div id="msg" class="text-danger"></div>
</div>
</div>
<div class="form-group">
<label>Card Number</label>
<div class="input-group">
<input onkeyup="VerifyCard()" type="text" id="txtCard" class="form-
control">
<div class="input-group-append">
<span class="input-group-text">
<img id="cardLogo" width="50" height="20">
</span>
</div>
</div>
</div>
<div class="form-group">
<label>Email</label>
<div>
<input onblur="VerifyEmail()" id="txtEmail" type="text" class="form-
control">
<div id="emailError">
</div>
</div>
</div>
</body>
</html>
Ex:
<!DOCTYPE html>
<html>
<head>
<title>String Demo</title>
<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/bootstrap.css">
<script>
function VerifyName(){
var txtName = document.getElementById("txtName").value;
var msg = document.getElementById("msg");
var firstCharCode = txtName.charCodeAt(0);
if(firstCharCode>=65 && firstCharCode<=90) {
msg.innerHTML = "";
} else {
msg.innerHTML = "Name must start with Uppercase Letter";
}
}
function VerifyCard(){
var txtCard = document.getElementById("txtCard").value;
var firstChar = txtCard.charAt(0);
var cardLogo = document.getElementById("cardLogo");
if(firstChar=="4") {
cardLogo.src="../Images/visa.png";
} else if(firstChar=="5"){
cardLogo.src="../Images/master.png";
} else {
cardLogo.src="../Images/invalid.png";
}
}
function VerifyEmail(){
var txtEmail = document.getElementById("txtEmail").value;
var emailError = document.getElementById("emailError");
var atPos = txtEmail.indexOf("@");
var dotPos = txtEmail.lastIndexOf(".");
if(atPos<=2 && (dotPos-atPos)<=2) {
emailError.innerHTML = "Error: @ missing or not at valid position in
email";
} else {
emailError.innerHTML = "Email Verified";
}
}
function VerifyPassword(){
var txtPwd = document.getElementById("txtPwd").value;
var pwdError = document.getElementById("pwdError");
if(txtPwd.trim()=="john") {
pwdError.innerHTML = "Verified";
} else {
pwdError.innerHTML = "Invalid Password";
}
}
</script>
</head>
<body class="container-fluid">
<div class="form-group">
<label>User Name</label>
<div>
<input onblur="VerifyName()" class="form-control"
placeholder="Name must start with Uppercase Letter" type="text"
id="txtName">
<div id="msg" class="text-danger"></div>
</div>
</div>
<div class="form-group">
<label>Password</label>
<div>
<input onblur="VerifyPassword()" type="password" id="txtPwd"
class="form-control">
<div id="pwdError">
</div>
</div>
</div>
<div class="form-group">
<label>Card Number</label>
<div class="input-group">
<input onkeyup="VerifyCard()" type="text" id="txtCard" class="form-
control">
<div class="input-group-append">
<span class="input-group-text">
<img id="cardLogo" width="50" height="20">
</span>
</div>
</div>
</div>
<div class="form-group">
<label>Email</label>
<div>
<input onblur="VerifyEmail()" id="txtEmail" type="text" class="form-
control">
<div id="emailError">
</div>
</div>
</div>
</body>
</html>
</div>
</div>
</div>
</body>
</html>
Compare with Regular Expression:
- The function “match()” is used to verify the value with regular
expression.
- It returns true if value is matching with regular expression.
Syntax:
String.match(regularExpression); // true-false
Ex:
<!DOCTYPE html>
<html>
<head>
<title>Verify Password</title>
<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/bootstrap.css">
<style>
progress {
height: 50px;
width: 100%;
}
</style>
<script>
function VerifyPassword(){
var regExp = /(?=.*[A-Z])\w{4,10}/;
var txtPwd = document.getElementById("txtPwd").value;
var lblMsg = document.getElementById("lblMsg");
var grade = document.getElementById("grade");
grade.style.display = "inline";
if(txtPwd.match(regExp)){
lblMsg.innerHTML="Strong Password";
GradeDisplay(1,100,100);
} else {
if(txtPwd.length<4) {
lblMsg.innerHTML="Poor Password";
GradeDisplay(1,100,20)
} else {
lblMsg.innerHTML="Weak Password";
GradeDisplay(1,100,60);
}
}
}
</script>
</head>
<body class="container-fluid">
<h2>Regular Expression</h2>
<div class="form-group">
<label>Password</label>
<div>
<input onkeyup="VerifyPassword()" id="txtPwd" type="password"
class="form-control">
<div>
<progress min="1" max="100" style="display: none;"
id="grade"></progress>
<span id="lblMsg"></span>
</div>
</div>
</div>
</body>
</html>
if(txtPwd.match(regExp)){
lblMsg.innerHTML="Strong Password".fontcolor('green').bold();
GradeDisplay(1,100,100);
} else {
if(txtPwd.length<4) {
lblMsg.innerHTML="Poor Password".fontcolor('red').italics();
GradeDisplay(1,100,20)
} else {
lblMsg.innerHTML="Weak
Password".fontcolor('yellow').bold().italics();
GradeDisplay(1,100,60);
}
}
}
</script>
</head>
<body class="container-fluid">
<h2>Regular Expression</h2>
<div class="form-group">
<label>Password</label>
<div>
<input onkeyup="VerifyPassword()" id="txtPwd" type="password"
class="form-control">
<div>
<progress min="1" max="100" style="display: none;"
id="grade"></progress>
<span id="lblMsg"></span>
</div>
</div>
</div>
</body>
</html>
Boolean Types
- Boolean types are defined by using “true or false”.
- Boolean type is used to handle decision making in programming.
- JavaScript boolean types refer to numeric value
o 0 : false
o 1 : true
- The boolean conditions in JavaScript can be configure with 0 or 1.
- JavaScript can control several HTML properties by using boolean type,
which includes checked, selected, disabled etc.
Syntax:
var x = true;
if(x==1) {
statement on true;
} else {
statement on false;
}
Ex:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/bootstrap.css">
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script
src="../node_modules/bootstrap/dist/js/bootstrap.bundle.js"></script>
<style>
body {
background-color: darkred;
width: 90%;
}
.card {
padding: 20px;
}
</style>
<script>
function OrderClick(){
document.getElementById("lblName").innerHTML =
document.getElementById("txtName").value;
document.getElementById("lblMobile").innerHTML =
document.getElementById("txtMobile").value;
var total = 0;
if(optBurger.checked) {
mealCost = 130;
mealName = optBurger.value;
}
if(optRoller.checked) {
mealCost = 100;
mealName = optRoller.value;
}
if(optFries.checked) {
adonCost = 80;
mealCost = mealCost + adonCost;
adonName += optFries.value + "<br>";
}
if(optKrusher.checked) {
adonCost = 40;
mealCost = mealCost + adonCost;
adonName += optKrusher.value + "<br>";
}
total = mealCost;
document.getElementById("lblMeal").innerHTML = mealName;
document.getElementById("lblAdon").innerHTML = adonName;
document.getElementById("lblTotal").innerHTML= "₹" + total;
}
</script>
</head>
<body class="container-fluid">
<header>
<img src="../Images/kfctop.PNG" width="100%" height="150">
</header>
<section>
<div class="accordion" id="orderForm">
<div class="card">
<div class="card-header">
<button data-target="#customerInfo" data-toggle="collapse"
class="btn btn-danger btn-block">Customer Info</button>
</div>
<div class="collapse show" id="customerInfo" data-
parent="#orderForm">
<div class="form-group">
<label>Customer Name</label>
<div>
<input type="text" id="txtName" class="form-control">
</div>
</div>
<div class="form-group">
<label>Mobile Number</label>
<div>
<input type="text" id="txtMobile" class="form-control">
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<button data-target="#mealInfo" data-toggle="collapse" class="btn
btn-danger btn-block">Select Meal</button>
</div>
<div class="collapse" id="mealInfo" data-parent="#orderForm">
<div class="row">
<div class="col">
<div class="card">
<div class="card-header">
<h3>OMG Burger</h3>
</div>
<div class="card-body">
<img src="../Images/omg1.PNG">
</div>
<div class="card-footer">
<h4>
<input name="meal" id="optBurger" value="OMG
Burger" type="radio"> ₹ 130/-
</h4>
</div>
</div>
</div>
<div class="col">
<div class="card">
<div class="card-header">
<h3>OMG Roller</h3>
</div>
<div class="card-body">
<img src="../Images/omg2.PNG">
</div>
<div class="card-footer">
<h4>
<input name="meal" id="optRoller" value="OMG Roller"
type="radio"> ₹ 100/-
</h4>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<button data-target="#adonInfo" data-toggle="collapse" class="btn
btn-danger btn-block">Select Ad-ON</button>
</div>
<div class="collapse" id="adonInfo" data-parent="#orderForm">
<div class="row">
<div class="col">
<div class="card">
<div class="card-header">
<h3>Large Fries</h3>
</div>
<div class="card-body">
<img src="../Images/fries1.PNG">
</div>
<div class="card-footer">
<h4>
<input id="optFries" value="Large Fries"
type="checkbox"> ₹ 80/-
</h4>
</div>
</div>
</div>
<div class="col">
<div class="card">
<div class="card-header">
<h3>Krusher Brownie</h3>
</div>
<div class="card-body">
<img src="../Images/krusher1.PNG">
</div>
<div class="card-footer">
<h4>
<input type="checkbox" id="optKrusher" value="Krusher
Browser"> ₹ 40/-
</h4>
</div>
</div>
</div>
<button onclick="OrderClick()" data-target="#billSummary" data-
toggle="modal" class="btn btn-danger btn-block">Place Order</button>
</div>
</div>
</div>
</div>
</section>
<div class="modal fade" id="billSummary">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h3>Bill Summary</h3>
<button data-dismiss="modal" class="close">x</button>
</div>
<div class="modal-body">
<table class="table table-hover">
<tbody>
<tr>
<td>Customer Name</td>
<td id="lblName"></td>
</tr>
<tr>
<td>Mobile</td>
<td id="lblMobile"></td>
</tr>
<tr>
<td>Meal Name</td>
<td id="lblMeal"></td>
</tr>
<tr>
<td>Ad-ONs</td>
<td id="lblAdon"></td>
</tr>
<tr>
<td>Total Amount</td>
<td id="lblTotal"></td>
</tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<button data-dismiss="modal" class="btn btn-
primary">OK</button>
</div>
</div>
</div>
</div>
</body>
</html>
Undefined Type
- Undefined type is configured for variables that are not defined with
value.
- Variable is defined but value is not assigned or initialized then the
compile will configure as “undefined”.
- You can verify whether value defined or not by using undefined.
Ex:
<script>
function f1(){
var x;
if(x==undefined) {
document.write("there is No value in x");
} else {
document.write(`x=${x}`);
}
}
f1();
</script>
Null Type
- Value is not defined into a reference dynamically during run time.
- Null is reference type, which indicates that value is not supplied to
variable during run time.
Ex:
<script>
function f1(){
var uname = prompt("Enter Name");
if(uname==null) {
document.write("You canceled");
} else {
document.write(`Hello ! ${uname}`);
}
}
f1();
</script>
Summary
- Number
- String
- Boolean
- Null
- Undefined
Non-Primitive Types
- The non-primitive types are “Mutable” types.
- Their reference can be changed according to state and situation.
- They don’t have fixed range of values.
- The value range varies according to the memory available.
- JavaScript non-primitive types are
o Array
o Object
o Regular Expression
Array Type
- Arrays in computer programming are used to reduce overhead and
complexity.
- JavaScript Array can store different types of values in sequential order.
- It can reduce overhead by storing values in sequential order.
- It can reduce complexity by storing multiple values under one name.
- Array size can be changed dynamically.
- Array in JavaScript have the behaviour of collections like stack, queue,
hash table.
Declaring Array:
- Array can be declared by using
o Array Meta Character “[]”
o Array Constructor “Array()”
Ex:
<script>
function f1(){
var categories = [];
var products = new Array();
}
f1();
</script>
Initialize values into Array:
<script>
function f1(){
var categories = ["Electronics","Footwear"];
var products = new Array("Speaker","Nike Causals");
}
f1();
</script>
Assign Values by using Array Property
- Property is used to map with index number in memory.
- So you can use property to access and or send value into memory.
Ex:
<script>
function f1(){
var categories = [];
categories["0"] = "Electronics";
categories["1"] = "Footwear";
for(var property in categories) {
document.write(`${property} : [${typeof property}]<br>`);
}
}
f1();
</script>
Ex:
<!DOCTYPE html>
<html>
<head>
<title>Slide Show</title>
<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" href="../Fonts/css/all.css">
<script>
var products = ["../Images/jblspeaker.jpg", "../Images/earpods.jpg",
"../Images/shoe.jpg", "../Images/shirt.jpg"];
var productNames = ["JBL Speaker","Earpods", "Nike Casuals", "Shirt"];
function loadImage(index){
var pic = document.getElementById("pic");
pic.src= products[index];
var lblName = document.getElementById("lblName");
lblName.innerHTML = productNames[index];
}
var index = 0;
function NextClick(){
index++;
loadImage(index);
}
function PreviousClick(){
index--;
loadImage(index);
}
function SlideShow(){
var txtRange = document.getElementById("txtRange").value;
loadImage(txtRange);
}
</script>
</head>
<body class="container-fluid" onload="loadImage(0)">
<div class="card">
<div class="card-header text-center">
<h3 id="lblName"></h3>
</div>
<div class="card-body text-center">
<button onclick="PreviousClick()" class="btn btn-outline-danger">
<span><</span>
</button>
<img id="pic" width="500" height="400">
<button onclick="NextClick()" class="btn btn-outline-danger">
<span>></span>
</button>
</div>
<div class="card-footer text-center">
<input onchange="SlideShow()" class="form-control-range"
id="txtRange" type="range" min="0" value="0" max="3">
</div>
</div>
</body>
</html>
Array Manipulation
Read Array Elements:
Method Description
toString() Returns array elements separated with comma.
Ex:
<script>
function f1(){
var products = ["TV", "Mobile", "Shoe"];
document.write(products.toString());
}
f1();
</script>
join() Returns array elements separated with custom delimiter.
Ex:
<script>
function f1(){
var products = ["TV", "Mobile", "Shoe"];
document.write(products.join("-->"));
}
f1();
</script>
slice() Return array element between specified index.
Ex:
<script>
function f1(){
var products = ["TV", "Mobile", "Shoe"];
document.write(products.slice(1,2));
}
f1();
</script>
for..of It reads and return all array elements in sequential order.
Ex:
<script>
function f1(){
var products = ["TV", "Mobile", "Shoe"];
for(var item of products) {
document.write(item + "<br>");
}
}
f1();
</script>
for..in It reads and return all array properties.
Ex:
<script>
function f1(){
var products = ["TV", "Mobile", "Shoe"];
for(var item in products) {
document.write(item + "<br>");
}
}
f1();
</script>
for It uses a loop to read all elements by using initialization, condition
and counter.
Syntax:
for(initializer, condition, iterator) {
}
Ex:
<script>
function f1(){
var products = ["TV", "Mobile", "Shoe"];
for(var i=0; i<products.length; i++) {
document.write(products[i] + "<br>");
}
}
f1();
</script>
Ex:
<!DOCTYPE html>
<html>
<head>
<title>Array</title>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
<script>
var categories = ["All", "Electronics", "Footwear", "Fashion", "Accessories"];
function bodyload(){
var lstCategories = document.getElementById("lstCategories");
var optCategories = document.getElementById("optCategories");
for(var item of categories) {
var li = document.createElement("li");
li.innerHTML = item;
lstCategories.appendChild(li);
var option = document.createElement("option");
option.text = item;
option.value = item;
optCategories.appendChild(option);
}
}
</script>
</head>
<body onload="bodyload()" class="container-fluid">
<div class="form-group">
<h3>Select a Category</h3>
<ol id="lstCategories">
</ol>
</div>
<div class="form-group">
<h3>Select Category</h3>
<select class="form-control" id="optCategories">
</select>
</div>
</body>
</html>
Method Description
push() Add new elements as last item.
unshift() Add new elements as first item.
pop() Remove and return last item.
shift() Remove and return first item.
splice() It is used to add or remove item at any specific index.
Syntax:
splice(startIndex, removeCount, NewItems…)
Ex:
<!DOCTYPE html>
<html>
<head>
<title>Array</title>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
<script>
var categories = ["All", "Electronics", "Footwear"];
function bodyload(){
var lstCategories = document.getElementById("lstCategories");
var optCategories = document.getElementById("optCategories");
lstCategories.innerHTML="";
optCategories.innerHTML="";
for(var item of categories) {
var li = document.createElement("li");
li.innerHTML = item;
lstCategories.appendChild(li);
</ol>
<div>
<button onclick="RemoveClick()">Remove</button>
</div>
</div>
<div class="form-group">
<h3>Select Category</h3>
<select size="3" class="form-control" id="optCategories">
</select>
<div>
<button onclick="RemoveSelected()">Remove Selected</button>
</div>
</div>
</body>
</html>
Searching for Elements in Array
indexOf() It can search for element in array based on given string and returns
the “index” number.
lastIndexOf() It returns the last occurrence index number.
find() It finds and returns the first occurrence element that matches the
given condition.
Ex:
<script>
function f1(){
var sales = [34500, 20000, 45000, 12000, 30000];
var result = sales.find(function(val){
return val>30000;
});
document.write(result);
}
f1();
</script>
filter() It finds and returns all elements that matches the given condition.
Ex:
<script>
function f1(){
var sales = [34500, 20000, 45000, 12000, 30000];
var result = sales.filter(function(val){
return val<=30000;
});
document.write(result.toString());
}
f1();
</script>
Ex:
<script>
function f1(){
var sales = [34500, 20000, 45000, 12000, 30000];
function search(val){
return val>=30000;
}
var result = sales.find(search);
document.write(result);
}
f1();
</script>
Sort Array Elements
FAQ:
1. What type of values we can store in array?
You can store any type of value.
2. We store function in Array?
Yes.
Ex:
<script>
function f1(){
var methods = [function(){return "Hello !"}, function(a, b){return a +
b}];
document.write(methods[0]() + "<br>");
document.write(methods[1](10,20));
}
f1();
</script>
3. What is Array Destruction?
It is a technique used to access array elements and store in individual
memory references.
Ex:
<script>
function f1(){
var methods = [function(){return "Hello !"}, function(a, b){return a +
b}];
//Without Destruction
var m1 = methods[0];
var m2 = methods[1];
document.write(m1() + "<br>");
document.write(m2(10,30) + "<br>");
// With Destruction
var [x1, x2] = methods;
document.write(x1() + "<br>");
document.write(x2(10,20));
}
f1();
</script>
4. Can we define Array inside Array [Multi Dimension]?
Yes.
Ex:
<script>
function f1(){
var values = [[10,20],["A","B"]];
document.write(values[0][1]);
}
f1();
</script>
Object Type
- Object in computer programming was introduced in early 1960’s by
“Alan Kay”.
- Object can keep all related data and functionality at one memory
reference.
- Object comprises of data and functionality.
- Object is a set of properties and methods.
}
f1();
</script>
JSON Type Data
[JavaScript Object Notation]
- It is a format for data.
- It is a collection objects.
Ex:
<script>
function f1(){
var products = [
{Name: "TV", Price: 45000.44, Cities:['Delhi', 'Hyd']},
{Name: "Mobile", Price: 12000.33, Cities: ['Hyd','Chennai']}
];
for(var product of products) {
document.write(product.Name + "-" + product.Price + "-" +
product.Cities.toString() + "<br>");
}
}
f1();
</script>
Ex: Filtering of data
<script>
function f1(){
var products = [
{Name: "TV", Price: 45000.44, Cities:['Delhi', 'Hyd'], Category:
"Electronics"},
{Name: "Mobile", Price: 12000.33, Cities: ['Hyd','Chennai'],
Category:"Electronics"},
{Name: "Nike Casuals", Price: 4000.44, Cities: ['Chennai', 'Hyd'],
Category: "Footwear"}
];
var result = products.filter(function(product){
return product.Category=="Electronics";
})
for(var item of result) {
document.write(item.Name + "-" + item.Price + "<br>");
}
}
f1();
</script>
tdName.innerHTML = item.Name;
tdPrice.innerHTML = item.Price;
tdPhoto.appendChild(pic);
tr.appendChild(tdName);
tr.appendChild(tdPrice);
tr.appendChild(tdPhoto);
tbody.appendChild(tr);
}
}
</script>
</head>
<body onload="bodyload()" class="container-fluid">
<h2>Product Details</h2>
<table class="table table-hover">
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>Preview</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</body>
</html>
</ol>
</body>
</html>
tdName.innerHTML = item.Name;
tdPrice.innerHTML = item.Price;
tr.appendChild(tdName);
tr.appendChild(tdPrice);
tbody.appendChild(tr);
}
}
function bodyload(){
LoadTable();
}
var newObject = {
Name: "",
Price: 0
};
function AddClick(){
var txtName = document.getElementById("txtName");
var txtPrice = document.getElementById("txtPrice");
newObject = {
Name: txtName.value,
Price: txtPrice.value
}
data.push(newObject);
alert("Record Added");
txtName.value="";
txtPrice.value="";
LoadTable();
}
</script>
</head>
<body onload="bodyload()" class="container-fluid">
<div class="row">
<div class="col-3">
<h3>Register Product</h3>
<div class="form-group">
<label>Name</label>
<div>
<input type="text" id="txtName" class="form-control">
</div>
</div>
<div class="form-group">
<label>Price</label>
<div>
<input type="text" id="txtPrice" class="form-control">
</div>
</div>
<div class="form-group">
<button onclick="AddClick()" class="btn btn-primary btn-
block">Add Product</button>
</div>
</div>
<div class="col-9">
<table class="table table-hover">
<thead>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
</div>
</body>
</html>
Regular Expression
- Regular expression is used to verify the format of input value.
- Expression is defined by using meta character and quantifiers enclosed
in “/ /”
- Regular expression is verified by using “match()”.
- match() is a boolean method that return true if expression is matching
with value.
Ex:
<!DOCTYPE html>
<html>
<head>
<title>Regular Expression</title>
<script>
function VerifyPassword(){
var txtPwd = document.getElementById(“txtPwd”).value;
var regExp = /(?=.*[A-Z])\w{4,10}/;
var msg = document.getElementById(“msg”);
var grade= document.getElementById(“grade”);
function ShowGrade(mn, mx, val){
grade.min = mn;
grade.max= mx;
grade.value = val;
}
if(txtPwd.match(regExp)){
msg.innerHTML=”Strong Password”.fontcolor(‘green’);
ShowGrade(1,100,100);
} else {
if(txtPwd.length<4){
msg.innerHTML=”Poor Password”.fontcolor(‘red’);
ShowGrade(1,100,20);
} else {
msg.innerHTML=”Weak Password”.fontcolor(‘orange’);
ShowGrade(1,100,70);
}
}
}
</script>
<style>
progress{
height: 20px;
width: 150px;
}
</style>
</head>
<body>
<fieldset>
<legend>Password</legend>
<div>
<input onkeyup=”VerifyPassword()” id=”txtPwd”
type=”password”>
<div>
<progress id=”grade” min=”1” value=”0”
max=”100”></progress>
</div>
<div id=”msg”></div>
</div>
</fieldset>
</body>
</html>
Ex:
<script>
function f1(){
var product = {
Name: "Samsung TV",
Price: 45000.55,
InStock: true,
Mfd: new Date("2020-03-18")
};
var months = ["January", "Feb", "March", "Apr"];
var weekdays = ["Sunday", "Monday", "Tue", "Wednesday", "Thu"];
document.write(`Name=${product.Name}<br>Price=${product.Price}<br>InSto
ck=${product.InStock}<br>
Manufactured Month: ${months[product.Mfd.getMonth()]} <br>
Manufactured Weekday: ${weekdays[product.Mfd.getDay()]} <br>
Manufactured Date: ${product.Mfd.getDate()} <br>
Manufactured Year: ${product.Mfd.getFullYear()}<br>
Date: ${product.Mfd.toLocaleDateString()}
`);
}
f1();
</script>
- You can set date dynamically by using “set” methods.
o setMonth()
o setDate()
o setFullYear()
o setHours()
o setMinutes()
o setSeconds()
o setMilliseconds()
Ex:
<script>
function f1(){
var product = {
Name: "Samsung TV",
Price: 45000.55,
InStock: true,
Mfd: new Date("2020-03-18")
};
var months = ["January", "Feb", "March", "Apr"];
var weekdays = ["Sunday", "Monday", "Tue", "Wednesday", "Thu"];
product.Mfd.setFullYear(2021);
product.Mfd.setMonth(1);
document.write(`Name=${product.Name}<br>Price=${product.Price}<br>InSto
ck=${product.InStock}<br>
Manufactured Month: ${months[product.Mfd.getMonth()]} <br>
Manufactured Weekday: ${weekdays[product.Mfd.getDay()]} <br>
Manufactured Date: ${product.Mfd.getDate()} <br>
Manufactured Year: ${product.Mfd.getFullYear()}<br>
Date: ${product.Mfd.toLocaleDateString()}
`);
}
f1();
</script>
Ex:
<!DOCTYPE html>
<html>
<head>
<title>Date</title>
<style>
.container{
width: 600px;
height: 400px;
justify-content: center;
align-items: center;
margin:auto;
}
</style>
<script>
function bodyload(){
var now = new Date();
var hrs = now.getHours();
var pic = document.getElementById("pic");
if(hrs>=00 && hrs<=12) {
pic.src="../Images/morning.gif";
} else if(hrs>12 && hrs<=17) {
pic.src="../Images/afternoon.gif";
} else {
pic.src="../Images/evening.gif";
}
}
</script>
</head>
<body onload="bodyload()">
<div class="container">
<img id="pic" width="300" height="300">
</div>
</body>
</html>
Summary
- Primitive Types
o Number
o String
o Boolean
o Null
o Undefined
- Non-Primitive Types
o Array
o Object
o Regular Expression
o Date
JavaScript Operators and Expressions
- Operator is an object that evaluates a value.
- Based on what type of value an operator evaluates the operators are
classified into following types:
o Arithmetic Operators
o Logical Operators
o Comparison Operators
o Assignment Operators
o Special Operators
- Operators are also classed into 3 type based on the number of operands
they can handle.
o Unary : One Operand [x++]
o Binary : Two operands [x + y]
o Ternary : Three operands [ (condition)?true:false]
Arithmetic Operators:
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus division
** Exponent [new in ES5] [old version – Math.pow()]
++ Increment
-- Decrement
Ex:
<script>
function f1(){
var x = 2;
var y = 3;
document.write(`x**y=${x**y} <br>`);
document.write(`Power=${Math.pow(x,y)}`);
}
f1();
</script>