JavaScript is a lightweight, cross-platform, and interpreted scripting language.
It is well-
known for the development of web pages, many non-browser environments also use it.
JavaScript can be used for Client-side developments as well as Server-side developments.
JavaScript contains a standard library of objects, like Array, Date, and Math, and a core set
of language elements like operators, control structures, and statements.
Client-side: It supplies objects to control a browser and its Document Object Model
(DOM). Like if client-side extensions allow an application to place elements on an HTML
form and respond to user events such as mouse clicks, form input, and page navigation.
Useful libraries for the client-side are AngularJS, ReactJS, VueJS and so many others.
Server-side: It supplies objects relevant to running JavaScript on a server. Like if the
server-side extensions allow an application to communicate with a database, and provide
continuity of information from one invocation to another of the application, or perform file
manipulations on a server. The useful framework which is the most famous these days is
[Link].
JavaScript can be added to your HTML file in two ways:
Internal JS: We can add JavaScript directly to our HTML file by writing the code inside
the <script> tag. The <script> tag can either be placed inside the <head> or the <body> tag
according to the requirement.
External JS: We can write JavaScript code in other file having an extension .js and then
link this file inside the <head> tag of the HTML file in which we want to add this code.
Syntax:
<script>
// JavaScript Code
</script>
To connect <script src="./[Link]">
Applications of JavaScript:
Web Development Adding interactivity and behavior to static sites JavaScript was
invented to do this in 1995. By using AngularJS that can be achieved so easily.
Web Applications With technology, browsers have improved to the extent that a language
was required to create robust web applications. When we explore a map in Google Maps
then we only need to click and drag the mouse. All detailed view is just a click away, and
this is possible only because of JavaScript. It uses Application Programming
Interfaces(APIs) that provide extra power to the code. The Electron and React is helpful in
this department.
Server Applications With the help of [Link], JavaScript made its way from client to
server and [Link] is the most powerful on the server-side.
Games: Not only in websites, but JavaScript also helps in creating games for leisure. The
combination of JavaScript and HTML 5 makes JavaScript popular in game development
as well. It provides the EaseJS library which provides solutions for working with rich
graphics.
Smartwatches: JavaScript is being used in all possible devices and applications. It provides
a library PebbleJS which is used in smartwatch applications. This framework works for
applications that require the internet for its functioning.
Machine Learning: This JavaScript [Link] library can be used in web development by
using machine learning.
Limitations of JavaScript:
Performance: JavaScript does not provide the same level of performance as offered by
many traditional languages as a complex program written in JavaScript would be
comparatively slow. But as JavaScript is used to perform simple tasks in a browser, so
performance is not considered a big restriction in its use.
Complexity: To master a scripting language, programmers must have a thorough
knowledge of all the programming concepts, core language objects, client and server-side
objects otherwise it would be difficult for them to write advanced scripts using JavaScript.
Modern JavaScript is very powerful as when compared to the versions launched 10 years
ago. I can be termed as a ‘Safe’ Programming language as it was initially created for
browsers which do not require it. In browser, JavaScript can do many things like
interaction with the user, webpage manipulation and the web server. Some of these are:
❖ Add new HTML content to the page
❖ Change Existing HTML content and styles
❖ React to user actions like mouse clicks, pointer movements etc.
❖ Can get and set cookies
❖ Remember the data on the client-side.
Safe’ Programming
Open console in – browser and type
➢ alert('hello')
undefined
➢ let js='amazing'
undefined
➢ if (js==='amazing') alert('java sc is fun');
undefined
➢ js = 'boring'
'boring'
➢ if (js==='amazing') alert('java sc is fun');
undefined
➢ 10+20+30
60
Where to Put the JavaScript
JavaScripts in a page will be executed immediately while the page loads into the browser.
This is not always what we want. Sometimes we want to execute a script when a page
loads, or at a later event, such as when a user clicks a button.
Scripts in <head>
Scripts to be executed when they are called, or when an event is triggered, are placed in
functions. Put your functions in the head section, this way they are all in one place, and
they do not interfere
with page content.
<html>
<head>
<script type="text/javascript">
function message()
{
alert("This alert box was called with the onload event");
}
</script>
</head>
<body onload="message()">
</body>
</html>
Scripts in <body>
If you don't want your script to be placed inside a function, or if your script should
write page content, it should be placed in the body section.
Example
<html>
<body>
<script type="text/javascript">
[Link]("This java script code in side body ");
</script>
</body>
</html>
[Link] –
The [Link] command is a standard JavaScript command for writing output to a
page. By entering the [Link] command between the <script> and </script> tags,
the browser will recognize it as a JavaScript command and execute the code line.
Using Buttons:
<!DOCTYPE html>
<html> <head> <meta charset="utf-8">
<title> buttons </title>
</head>
<body>
<p> Use of Button </p>
<button onclick="alert('How can I help you?')"> Click me. </button>
<button id="button2"> Click me. </button>
<script>
[Link]("button2").onclick=function(){
alert("You have just clicked me!");
}
</script>
</body> </html>
Using Extrnal JS file.
Creating [Link] File and attach with HTML file
<!DOCTYPE html>
<html lang="en">
<head>
<title>Using External JS</title>
<link rel="stylesheet" href="[Link]">
<script src="[Link]"></script>
</head>
<body>
<h1>Hello java script </h1>
</body>
</html>
JavaScript Code
JavaScript code (or just JavaScript) is a sequence of JavaScript statements.
Each statement is executed by the browser in the sequence they are written.
<script type="text/javascript">
[Link]("<h1>This is a heading</h1>");
[Link]("<p>This is a paragraph.</p>");
[Link]("<p>This is another paragraph.</p>");
</script>
JavaScript Blocks
JavaScript statements can be grouped together in blocks.
Blocks start with a left curly bracket {, and ends with a right curly bracket }.
The purpose of a block is to make the sequence of statements execute together.
<script type="text/javascript">
{
[Link]("<h1>This is a heading</h1>");
[Link]("<p>This is a paragraph.</p>");
[Link]("<p>This is another paragraph.</p>");
}
</script>
JavaScript Comments
Comments can be added to explain the JavaScript, or to make the code more readable.
Single line comments start with //.
The following example uses single line comments to explain the code:
Example
<script type="text/javascript">
// Write a heading
[Link]("<h1>This is a heading</h1>");
// Write two paragraphs:
[Link]("<p>This is a paragraph.</p>");
[Link]("<p>This is another paragraph.</p>");
</script>
JavaScript Multi-Line Comments
Multi line comments start with /* and end with */.
The following example uses a multi line comment to explain the code:
Example
<script type="text/javascript">
/*
The code below will write
one heading and two paragraphs
*/
[Link]("<h1>This is a heading</h1>");
[Link]("<p>This is a paragraph.</p>");
[Link]("<p>This is another paragraph.</p>");
</script>
JavaScript Variables
JavaScript variables are used to hold values or expressions. It’s value can change as we
want.
Rules for define a variable:
(1) A variable can have a short name, like x, or a more descriptive name, like car name.
(2) Variable names a re case sensitive (y and Y are two different variables)
(3) Variable names must begin with a letter or the underscore character
Note: Because JavaScript is case-sensitive, variable names are case-sensitive.
Type these code at console in the browser:
// Values and Variables
[Link]("Jonas");
[Link](23);
let firstName = "Kailash";
[Link](firstName);
// Variable name conventions
let My_value = "JM";
let $function = 27;
let person = "Muna";
let PI = 3.1415;
let myFirstJob = "Coder";
let myCurrentJob = "Teacher";
let job1 = "programmer";
let job2 = "teacher";
[Link](myFirstJob);
Console Log, Error and Warning
[Link](“hello”);
[Link](“warning Message”);
[Link](“Error message”);
JavaScript Operators
JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic between variables and/or values.
Given that y=5, the table below explains the arithmetic operators:
Operator Description Example Result
+ Addition x=y+2 x=7
- Subtraction x=y-2 x=3
* Multiplication x=y*2 x=10
/ Division x=y/2 x=2.5
% Modulus (division remainder) x=y%2 x=1
++ Increment x=++y x=6
-- Decrement x=--y x=4
JavaScript Assignment Operators
Assignment operators are used to assign values to JavaScript variables.
Given that x=10 and y=5, the table below explains the assignment operators:
Operator Example Same As Result
= x=y x=5
+= x+=y x=x+y x=15
-= x-=y x=x-y x=5
*= x*=y x=x*y x=50
/= x/=y x=x/y x=2
%= x%=y x=x%y x=0
The + Operator Used on Strings
The + operator can also be used to add string variables or text values together.
To add two or more string variables together, use the + operator.
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
Logical Operators
Logical operators are used to determine the logic between variables or values.
Given that x=6 and y=3, the table below explains the logical operators:
Operator Description Example
&& and (x < 10 && y > 1)
|| or (x==5 || y==5)
! not !(x==y)
Operators:
It is used in expression to get result.
It can be different types according to the use.
Arithematic Op. a + b (a and b is operand and + is a operator)
Here ‘+’ will work as addition.
Arithematic Operators. +, -, *, /, %
comparison operator.
Strict Equality - when two values consider strictly equal if they refer to the same object or
they are the same type and have the same value.
We use === equal sign for not (!==)
Abstract Equality :
When two values consider abstractly equal if they refer to the same object or having the
same value.
We can use == sign for not equal (!=)
For Example
function check()
{
let y=10, str='10';
[Link](y===str); // it will check type and value and return false
[Link](y==str); // it will return true only check with value.
[Link](y===Number(str)); // result = true.
}
Typeof() Operators – used to identify the data
type of a variable and objects.
Undefined
Null
Boolean
Number
String
Symbol
Object.
Example
[Link]( typeof 1);
Assignment operators using object:
const obj={a:100, b:200};
const {a,b}=obj; //must be use {} to assign
[Link](a);
[Link](b);
Conditional Operator
JavaScript also contains a conditional operator that assigns a value to a variable based on
some condition.
Syntax:
variablename=(condition)?value1:value2;
JavaScript If...Else Statements
Conditional statements are used to perform different actions based on different
conditions.
conditional statements:
• if statement - use this statement to execute some code only if a specified condition
is true.
• if...else statement - use this statement to execute some code if the condition is true
and another code if the condition is false.
• if...else if....else statement - use this statement to select one of many blocks of code
to be executed.
• switch statement - use this statement to select one of many blocks of code to be
executed.
If Statement
Use the if statement to execute some code only if a specified condition is true.
Syntax:
if (condition)
{
code to be executed if condition is true
}
//Write a "Good morning" greeting if the time is less than 10
<script type="text/javascript">
var d=new Date();
var time=[Link]();
if (time<10)
{ [Link]("<b>Good morning</b>"); }
</script>
If...else Statement
Use the if....else statement to execute some code if a condition is true and another code if
the condition is not true.
Syntax:
if (condition)
{ //code to be executed if condition is true }
else
{ //code to be executed if condition is not true }
EXAMPLE -
<script type="text/javascript">
var d = new Date()
var time = [Link]()
if (time<10)
{ [Link]("<b>Good morning</b>"); }
else if (time>10 && time<16)
{ [Link]("<b>Good day</b>"); }
else
{ [Link]("<b>Hello World!</b>");}
</script>
The JavaScript Switch Statement
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch(n)
{
case 1:
execute code block 1;
break;
case 2:
execute code block 2;
break;
default:
code to be executed if n is different from case 1 and 2
}
JavaScript Popup Boxes
Alert Box
An alert box is often used if you want to make sure information comes through to the user.
When an alert box pops up, the user will have to click "OK" to proceed.
<html>
<head>
<script type="text/javascript">
function show_alert()
{ alert("I am an alert box!"); }
</script> </head>
<body> <input type="button" onclick="show_alert()" value="Show alert box" />
</body> </html>
Confirm Box
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to
proceed. If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box
returns false.
<html><head>
<script type="text/javascript">
function show_confirm()
{
var r=confirm("Press a button");
if (r==true)
{
alert("You pressed OK!");
}
else
{
alert("You pressed Cancel!");
}
}
</script>
</head>
<body>
<input type="button" onclick="show_confirm()"
value="Show confirm box" />
</body>
</html>
Prompt Box
A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to
proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box
returns null.
prompt("sometext","defaultvalue");
<html>
<head>
<script type="text/javascript">
function show_prompt()
{
var name=prompt("Please enter your name","Harry Potter");
if (name!=null && name!="")
{
[Link]("Hello " + name + "! How are you today?");
}
}
</script>
</head>
<body>
<input type="button" onclick="show_prompt()" value="Show prompt box" />
</body>
</html>
Expression:
It is used to produce a value. It will evaluate the expression and return
Primary expression – is a very simple to write
Undefined – is global variable.
Let y,j;
Y= 4*5; // this is an expression. We multiply two number and assign to y.
[Link](y);
J=y=4*5;
Note: we can assign multiple variable at a time.
Use of getElementById()
<!DOCTYPE html>
<html>
<body>
<h1>The Element Object</h1>
<h2>The Differences Between innerText, innerHTML and textContent</h2>
<p id="myP"> This element has extra spacing and contains <span>a span element</span>.</p>
<button onclick="getinnerHTML()">Get innerHTML</button>
<button onclick="getinnerText()">Get innerText</button>
<button onclick="gettextContent()">Get textContent</button>
<pre id="demo"></pre>
<p>The innerText property is not supported in IE 9 and earlier.</p>
<p>The textContent property is not supported in IE 8 and earlier.</p>
<script>
function getinnerText() {
let text = [Link]("myP").innerText;
[Link]("demo").innerText = text;
}
function getinnerHTML() {
let text = [Link]("myP").innerHTML;
[Link]("demo").innerText = text;
}
function gettextContent() {
let text = [Link]("myP").textContent;
[Link]("demo").innerText = text;
}
</script>
</body>
</html>
Note
[Link]("demo").innerHTML = "I have changed!";
Example – 2
<!DOCTYPE html>
<html>
<body>
<h1>The Element Object</h1>
<h2>The innerHTML Property</h2>
<ul id="myList">
<li>Coffee</li>
<li>Tea</li>
</ul>
<p>The HTML content of the ul element "myList" is:</p>
<p id="demo"></p>
<script>
let html = [Link]("myList").innerHTML;
[Link]("demo").innerHTML = html;
</script>
TextContent
<!DOCTYPE html>
<html><body>
<h1>The Element Object</h1>
<h2>The textContent Property</h2>
<ul id="myList">
<li>Coffee</li>
<li>Tea</li>
</ul>
<p>The text content of the ul element is:</p>
<p id="myinfo"></p>
<script>
let text = [Link]("myList").textContent;
[Link]("myinfo").innerHTML = text;
</script>
</body></html>
Operators and its use
// Data Types
let javascriptIsFun = true;
[Link](javascriptIsFun);
// [Link](typeof true);
[Link](typeof javascriptIsFun);
// [Link](typeof 23);
// [Link](typeof 'Jonas');
javascriptIsFun = 'YES!';
[Link](typeof javascriptIsFun);
let year;
[Link](year);
[Link](typeof year);
year = 1991;
[Link](typeof year);
[Link](typeof null);
////////////////////////////////////
// let, const and var
let age = 30;
age = 31;
const birthYear = 1991;
// birthYear = 1990;
// const job;
var job = 'programmer';
job = 'teacher'
lastName = 'Schmedtmann';
[Link](lastName);
const now = 2037;
const ageJonas = now - 1991;
const ageSarah = now - 2018;
[Link](ageJonas, ageSarah);
[Link](ageJonas * 2, ageJonas / 10, 2 ** 3);
// 2 ** 3 means 2 to the power of 3 = 2 * 2 * 2
const firstName = 'Jonas';
const lastName = 'Schmedtmann';
[Link](firstName + ' ' + lastName);
// Assignment operators
let x = 10 + 5; // 15
x += 10; // x = x + 10 = 25
x *= 4; // x = x * 4 = 100
x++; // x = x + 1
x--;
x--;
[Link](x);
// Comparison operators
[Link](ageJonas > ageSarah); // >, <, >=, <=
[Link](ageSarah >= 18);
const isFullAge = ageSarah >= 18;
[Link](now - 1991 > now - 2018);
////////////////////////////////////
// Operator Precedence
const now = 2037;
const ageJonas = now - 1991;
const ageSarah = now - 2018;
[Link](now - 1991 > now - 2018);
let x, y;
x = y = 25 - 10 - 5; // x = y = 10, x = 10
[Link](x, y);
const averageAge = (ageJonas + ageSarah) / 2;
[Link](ageJonas, ageSarah, averageAge);
*/
Type Conversion and Coercion
const inputYear = '1991';
[Link](Number(inputYear), inputYear);
[Link](Number(inputYear) + 18);
[Link](Number('Jonas'));
[Link](typeof (NaN));
[Link](String(23), 23);
[Link]('I am ' + 23 + ' years old');
[Link]('23' - '10' - 3);
[Link]('23' / '2');
let n = '1' + 1; // '11'
n = n - 1;
[Link](n);
////////////////////////////////////
// Truthy and Falsy Values
// 5 falsy values: 0, '', undefined, null, NaN
[Link](Boolean(0));
[Link](Boolean(undefined));
[Link](Boolean('Jonas'));
[Link](Boolean({}));
[Link](Boolean(''));
////////////////////////////////////
// Equality Operators: == vs. ===
const age = '18';
if (age === 18) [Link]('You just became an adult :D (strict)');
if (age == 18) [Link]('You just became an adult :D (loose)');
const favourite = Number(prompt("What's your favourite number?"));
[Link](favourite);
[Link](typeof favourite);
if (favourite === 23) {
[Link]('Cool! 23 is an amazing number!')
} else if (favourite === 7) {
[Link]('7 is also a cool number')
} else if (favourite === 9) {
[Link]('9 is also a cool number')
} else {
[Link]('Number is not 23 or 7 or 9')
}
if (favourite !== 23) [Link]('Why not 23?');
////////////////////////////////////
// Logical Operators
const hasDriversLicense = true; // A
const hasGoodVision = true; // B
[Link](hasDriversLicense && hasGoodVision);
[Link](hasDriversLicense || hasGoodVision);
[Link](!hasDriversLicense);
// if (hasDriversLicense && hasGoodVision) {
// [Link]('Sarah is able to drive!');
// } else {
// [Link]('Someone else should drive...');
// }
const isTired = false; // C
[Link](hasDriversLicense && hasGoodVision && isTired);
if (hasDriversLicense && hasGoodVision && !isTired) {
[Link]('Sarah is able to drive!');
} else {
[Link]('Someone else should drive...');
}
////////////////////////////////////
// The switch Statement
const day = 'friday';
switch (day) {
case 'monday': // day === 'monday'
[Link]('Plan course structure');
[Link]('Go to coding meetup');
break;
case 'tuesday':
[Link]('Prepare theory videos');
break;
case 'wednesday':
case 'thursday':
[Link]('Write code examples');
break;
case 'friday':
[Link]('Record videos');
break;
case 'saturday':
case 'sunday':
[Link]('Enjoy the weekend :D');
break;
default:
[Link]('Not a valid day!');
}
if (day === 'monday') {
[Link]('Plan course structure');
[Link]('Go to coding meetup');
} else if (day === 'tuesday') {
[Link]('Prepare theory videos');
} else if (day === 'wednesday' || day === 'thursday') {
[Link]('Write code examples');
} else if (day === 'friday') {
[Link]('Record videos');
} else if (day === 'saturday' || day === 'sunday') {
[Link]('Enjoy the weekend :D');
} else {
[Link]('Not a valid day!');
}
////////////////////////////////////
// Statements and Expressions
3+4
1991
true && false && !false
if (23 > 10) {
const str = '23 is bigger';
}
const me = 'Jonas';
[Link](`I'm ${2037 - 1991} years old ${me}`);
////////////////////////////////////
// The Conditional (Ternary) Operator
const age = 23;
// age >= 18 ? [Link]('I like to drink wine 🍷') : [Link]('I like to drink
water 💧');
const drink = age >= 18 ? 'wine 🍷' : 'water 💧';
[Link](drink);
let drink2;
if (age >= 18) {
drink2 = 'wine 🍷';
} else {
drink2 = 'water 💧';
}
[Link](drink2);
[Link](`I like to drink ${age >= 18 ? 'wine 🍷' : 'water 💧'}`);
*/
////////////////////////////////////
// Coding Challenge #4
Steven wants to build a very simple tip calculator for whenever he goes eating in a
resturant. In his country, it's usual to tip 15% if the bill value is between 50 and 300. If the
value is different, the tip is 20%.
1. Your task is to caluclate the tip, depending on the bill value. Create a variable
called 'tip' for this. It's not allowed to use an if/else statement 😅 (If it's easier for you,
you can start with an if/else statement, and then try to convert it to a ternary operator!)
2. Print a string to the console containing the bill value, the tip, and the final value
(bill + tip). Example: 'The bill was 275, the tip was 41.25, and the total value 316.25'
TEST DATA: Test for bill values 275, 40 and 430
HINT: To calculate 20% of a value, simply multiply it by 20/100 = 0.2
HINT: Value X is between 50 and 300, if it's >= 50 && <= 300 😉
GOOD LUCK 😀
*/
/*
const bill = 430;
const tip = bill <= 300 && bill >= 50 ? bill * 0.15 : bill * 0.2;
[Link](`The bill was ${bill}, the tip was ${tip}, and the total value ${bill +
tip}`);
*/
DOM manipulation: Document Object Model
It is a connection between java script and browser.
DOM Tree Structure :
The special object that is the entry point to the DOM. For example:
[Link]()
The Difference Between an HTMLCollection and a NodeList
A NodeList and an HTMLcollection is very much the same thing.
Both are array-like collections (lists) of nodes (elements) extracted from a document. The
nodes can be accessed by index numbers. The index starts at 0.
Both have a length property that returns the number of elements in the list (collection).
An HTMLCollection is a collection of document elements.
A NodeList is a collection of document nodes (element nodes, attribute nodes, and text
nodes).
HTMLCollection items can be accessed by their name, id, or index number.
NodeList items can only be accessed by their index number.
An HTMLCollection is always a live collection. Example: If you add a <li> element to a
list in the DOM, the list in the HTMLCollection will also change.
A NodeList is most often a static collection. Example: If you add a <li> element to a list in
the DOM, the list in NodeList will not change.
The getElementsByClassName() and getElementsByTagName() methods return a live
HTMLCollection.
The querySelectorAll() method returns a static NodeList.
Get the first <p> element in with class="example":
[Link]("[Link]");
Change the text of the element with id="demo":
[Link]("#demo").innerHTML = "Hello World!";
<button onclick="myFunction()">Try it</button>
Select the first <p> element with the parent is a <div> element.
<script>
function myFunction() {
var x = [Link]("div > p");
[Link] = "red";
}
Select the first <h3> or the first <h4>:
<h3>A h3 element</h3>
<h4>A h4 element</h4>
[Link]("h3, h4").[Link] = "red";
</script>
Redirect to any page
function check()
{
[Link] = "[Link]
}
Or within the project
[Link] = "[Link]";
HTML DOM Document querySelectorAll()Example
Select all elements with class="example":
[Link](".example");
For example:
<p>Add a background color all elements with class="example":</p>
<h2 class="example">A heading</h2>
<p class="example">A paragraph.</p>
<script>
const nodeList = [Link](".example");
for (let i = 0; i < [Link]; i++) {
nodeList[i].[Link] = "red";
}
</script>
HTML DOM Document getElementsByName()
JavaScript Object
1) JavaScript Object by object literal
The syntax of creating object using object literal is given below:
1. object={property1:value1,property2:value2.....propertyN:valueN}
As you can see, property and value is separated by : (colon).
Let’s see the simple example of creating object in JavaScript.
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
[Link]([Link]+" "+[Link]+" "+[Link]);
</script>
2) By creating instance of Object
The syntax of creating object directly is given below:
1. var objectname=new Object();
Here, new keyword is used to create object.
Let’s see the example of creating object directly.
<script>
var emp=new Object();
[Link]=101;
[Link]="Ravi Malik";
[Link]=50000;
[Link]([Link]+" "+[Link]+" "+[Link]);
</script>
3) By using an Object constructor
Here, you need to create function with arguments. Each argument value can be assigned in
the current object by using this keyword.
The this keyword refers to the current object.
The example of creating object by object constructor is given below.
<script>
function emp(id,name,salary){
[Link]=id;
[Link]=name;
[Link]=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
[Link]([Link]+" "+[Link]+" "+[Link]);
</script>
Java Script Array:
JavaScript array is an object that represents a collection of similar type of elements.
There are 3 ways to construct array in JavaScript
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
1) JavaScript array literal
The syntax of creating array using array literal is given below:var
arrayname=[value1,value2.....valueN];
As you can see, values are contained inside [ ] and separated by , (comma).
Let's see the simple example of creating and using array in JavaScript.
<script>
1. var emp=["Sonoo","Vimal","Ratan"];
2. for (i=0;i<[Link];i++){
3. [Link](emp[i] + "<br/>");
4. }
5. </script>
2) JavaScript Array directly (new keyword)
The syntax of creating array directly is given below:
1. var arrayname=new Array();
Here, new keyword is used to create instance of array.
Let's see the example of creating array directly.
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<[Link];i++){
[Link](emp[i] + "<br>");
}
</script>
3) JavaScript array constructor (new keyword)
Here, you need to create instance of array by passing arguments in constructor so that we
don't have to provide value explicitly.
The example of creating object by array constructor is given below.
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<[Link];i++){
[Link](emp[i] + "<br>");
}
</script>
JavaScript Array concat() Method
The JavaScript array concat() method combines two or more arrays and returns a new
string. This method doesn't make any change in the original array.
Syntax
The concat() method is represented by the following syntax:
[Link](arr1,arr2,....,arrn)
Parameter
arr1,arr2,....,arrn - It represent the arrays to be combined.
Return
A new array object that represents a joined array.
Example 1
Here, we will print the combination of two arrays.
<script>
var arr1=["C","C++","Python"];
var arr2=["Java","JavaScript","Android"];
var result=[Link](arr2);
[Link](result);
</script>
Example 2:
In this example, we will concat the elements directly.
<script>
var arr=["C","C++","Python"];
var result= [Link]("Java","JavaScript","Android");
[Link](result);
</script>
JavaScript String
The JavaScript string is an object that represents a sequence of characters.
There are 2 ways to create string in JavaScript
By string literal
By string object (using new keyword)
1) By string literal
The string literal is created using double quotes. The syntax of creating string using string
literal is given below:
var stringname="string value";
Let's see the simple example of creating string literal.
<script>
var str="This is string literal";
[Link](str);
</script>
2) By string object (using new keyword)
The syntax of creating string object using new keyword is given below:
var stringname=new String("string literal");
Here, new keyword is used to create instance of string.
<script>
var stringname=new String("hello javascript string");
[Link](stringname);
</script>
Methods Description
charAt() It provides the char value present at the specified index.
charCodeAt() It provides the Unicode value of a character present at the specified
index.
concat() It provides a combination of two or more strings.
indexOf() It provides the position of a char value present in the given string.
lastIndexOf() It provides the position of a char value present in the given string by
searching a character from the last position.
search() It searches a specified regular expression in a given string and returns
its position if a match occurs.
match() It searches a specified regular expression in a given string and returns
that regular expression if a match occurs.
replace() It replaces a given string with the specified replacement.
substr() It is used to fetch the part of the given string on the basis of the
specified starting position and length.
substring() It is used to fetch the part of the given string on the basis of the
specified index.
JavaScript Date Object
The JavaScript date object can be used to get year, month and day. You can display a
timer on the webpage by the help of JavaScript date object.
You can use different Date constructors to create date object. It provides methods to get
and set day, month, year, hour, minute and seconds.
Constructor
You can use 4 variant of Date constructor to create date object.
Date()
Date(milliseconds)
Date(dateString)
Date(year, month, day, hours, minutes, seconds, milliseconds)
JavaScript Date Methods:
JavaScript Date getDate() method
The JavaScript date getDate() method returns the day for the specified date on the basis of
local time.
Syntax
The getDate() method is represented by the following syntax:
[Link]()
Return An integer value between 1 and 31 that represents the day of the specified date.
<script>
var date=new Date();
[Link]("Today's day: "+[Link]());
</script>
JavaScript Date getDay() method
The JavaScript date getDay() method returns the value of day of the week for the specified
date on the basis of local time. The value of the day starts with 0 that represents Sunday.
Syntax
The getDay() method is represented by the following syntax:
[Link]()
Return An integer value between 0 and 6 that represents the days of the week for the
specified date.
<script>
var day=new Date();
[Link]([Link]());
</script>
Let's see an example to print the value of weekday from the given date.
<script>
var day=new Date("August 15, 1947 [Link]");
[Link]([Link]())
</script>
getFullYears() : It returns the integer value that represents the year on the basis of local
time.
getHours() :It returns the integer value between 0 and 23 that represents the hours on the
basis of local time.
getMilliseconds() :It returns the integer value between 0 and 999 that represents the
milliseconds on the basis of local time.
getMinutes(): It returns the integer value between 0 and 59 that represents the minutes on
the basis of local time.
getMonth() : It returns the integer value between 0 and 11 that represents the month on the
basis of local time.
getSeconds(): It returns the integer value between 0 and 60 that represents the seconds on
the basis of local time.
JavaScript Form Validation
It is important to validate the form submitted by the user because it can have inappropriate
values. So, validation is must to authenticate user.
JavaScript provides facility to validate the form on the client-side so data processing will
be faster than server-side validation. Most of the web developers prefer JavaScript form
validation.
Through JavaScript, we can validate name, password, email, date, mobile numbers and
more fields.
JavaScript Form Validation Example
In this example, we are going to validate the name and password. The name can’t be
empty and password can’t be less than 6 characters long.
<script>
function validateform(){
var name=[Link];
var password=[Link];
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if([Link]<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="[Link]" onsubmit="return validateform()"
>
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
Let's validate the textfield for numeric value only. Here, we are using isNaN() function.
<script>
function validate(){
var num=[Link];
if (isNaN(num)){
[Link]("numloc").innerHTML="Enter Numeric value only";
return false;
}else{
return true;
}
}
</script>
<form name="myform" onsubmit="return validate()" >
Number: <input type="text" name="num"><span id="numloc"></span><br/>
<input type="submit" value="submit">
</form>
JavaScript email validation
We can validate the email by the help of [Link] are many criteria that need to be
follow to validate the email id such as:
1. email id must contain the @ and . character
2. There must be at least one character before and after the @.
3. There must be at least two characters after . (dot).
4. Let's see the simple example to validate the email field.
<script>
function validateemail()
{
var x=[Link];
var atposition=[Link]("@");
var dotposition=[Link](".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=[Link]){
alert("Please enter a valid e-mail address \n atpostion:"
+atposition+"\n dotposition:"+dotposition);
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="#" onsubmit="return validateemail();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register">
</form>