4 Scripting Part II
4 Scripting Part II
All websites run on three components: the server, the database, and the client. The client is simply the browser a person
is using to view a site, and it’s where client-side technology is unpacked and processed. The server is at a remote location
anywhere in the world—housing data, running a site’s back-end architecture, processing requests, and sending pages to
the browser. The client is anywhere your users are viewing your site: mobile devices, laptops, or desktop
computers. Server-side scripting is executed by a web server; client-side scripting is executed by a browser.
Client-end scripts are embedded in a website’s HTML markup code, which is housed on the server in a language that’s
compatible with, or compiled to communicate with, the browser. The browser temporarily downloads that code, and then,
apart from the server, processes it. If it needs to request additional information in response to user clicks, mouse-overs,
etc. (called “events”), a request is sent back to the server.
Client-side scripting is always evolving—it’s growing simpler, more nimble, and easier to use. As a result, sites are faster,
more efficient, and less work is left up to the server.
Scripts are embedded within and interact with the HTML of your site, selecting elements of it, and then
manipulating those elements to provide an interactive experience.
Scripts interact with a cascading style sheet (CSS) file that styles the way the page looks.
It dictates what work the server-side code is going to have to accomplish (where utility should be built around
these front-end functions), and returns data that’s pulled from the site in a way that’s readable by the browser. For
example: If there’s a form for updating a profile, the back end is built to pull specific data from the database to
populate that form, while front-end scripts populate the form with that information.
Scripts put less stress on the server because they don’t require processing on the server once they’re
downloaded, just when post-backs are made. “Post-backs” perform specific call-and-answers with the server-side
code, and respond to the user immediately.
Client-end scripts are embedded in a website’s HTML markup code, which is housed on the server in a language that’s
compatible with, or compiled to communicate with, the browser. The browser temporarily downloads that code, and then,
apart from the server, processes it. If it needs to request additional information in response to user clicks, mouse-overs,
etc. (called “events”), a request is sent back to the server.
Client-side scripting is always evolving—it’s growing simpler, more nimble, and easier to use. As a result, sites are faster,
more efficient, and less work is left up to the server.
Introduction to java Script: JavaScript was first known as LiveScript, but Netscape changed its name to
JavaScript, possibly because of the excitement being generated by Java. JavaScript made its first appearance in
Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core of the language has been embedded
in Netscape, Internet Explorer, and other web browsers.
JavaScript ("JS" for short) is a full-fledged dynamic programming language that, when applied to an HTML document, can
provide dynamic interactivity on websites. It was invented by Brendan Eich, co-founder of the Mozilla project, the Mozilla
Foundation, and the Mozilla Corporation.
JavaScript contains a standard library of objects, such as Array, Date, and Math, and a core set of language elements such
as operators, control structures, and statements. Core JavaScript can be extended for a variety of purposes by supplementing
it with additional objects
JavaScript Vs Java
JavaScript Java
Object-oriented. No distinction between types of Class-based. Objects are divided into classes and
objects. Inheritance is through the prototype instances with all inheritance through the class
mechanism, and properties and methods can be hierarchy. Classes and instances cannot have
added to any object dynamically. properties or methods added dynamically.
Variable data types are not declared (dynamic Variable data types must be declared (static typing,
typing, loosely typed). strongly typed).
Cannot automatically write to hard disk. Can automatically write to hard disk.
JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in 1997.
ECMAScript Editions
Ver Official Name Description
1 ECMAScript 1 (1997) First Edition.
2 ECMAScript 2 (1998) Editorial changes only.
3 ECMAScript 3 (1999)Added Regular Expressions.Added try/catch.
4 ECMAScript 4 Never released.
5 ECMAScript 5 (2009)Added "strict mode".
Added JSON support.
Added String.trim().
Added Array.isArray().
Added Array Iteration Methods.
5.1 ECMAScript 5.1 (2011) Editorial changes.
6 ECMAScript 2015 Added let and const.
Added default parameter values.
Added Array.find().
Added Array.findIndex().
7 ECMAScript 2016 Added exponential operator (**).
Added Array.prototype.includes.
8 ECMAScript 2017 Added string padding.
Added new Object properties.
Added Async functions.
Added Shared Memory.
9 ECMAScript 2018 Added rest / spread properties.
Added Asynchronous iteration.
Added Promise.finally().
Additions to RegExp.
ECMAScript is often abbreviated to ES.
Browser Support
ECMAScript 3 is fully supported in all browsers.
ECMAScript 5 is fully supported in all modern browsers.
Advantages of JavaScript
Less server interaction: You can validate user input before sending the page off to the server. This saves
server traffic, which means less load on your server.
Immediate feedback to the visitors: They don't have to wait for a page reload to see if they have
forgotten to enter something.
Increased interactivity: You can create interfaces that react when the user hovers over them with a
mouse or activates them via the keyboard.
Richer interfaces: You can use JavaScript to include such items as drag-anddrop components and sliders
to give a Rich Interface to your site visitors.
Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the following important features:
Client-side JavaScript does not allow the reading or writing of files. This has been kept for security
reason.
JavaScript cannot be used for networking applications because there is no such support available.
JavaScript doesn't have any multithreading or multiprocessor capabilities. Once again, JavaScript is a
lightweight, interpreted programming language that allows you to build interactivity into otherwise
static HTML pages.
In JavaScript there are 5 different data types that can contain values:
string
number
boolean
object
function
Object
Date
Array
String
Number
Boolean
null
undefined
JavaScript variables can hold many data types: numbers, strings, objects and more:
In programming, data types is an important concept. To be able to operate on variables, it is important to know
something about the type. Without data types, a computer cannot safely solve this:
var x = 16 + "Volvo";
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript</h2>
<p>When adding a number and a string, JavaScript will treat the number as a string.</p>
<p id="demo"></p>
<script>
var x = 16 + "Volvo";
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
Output
JavaScript
When adding a number and a string, JavaScript will treat the number as a string.
16Volvo
Note: When adding a number and a string, JavaScript will treat the number as a string.
JavaScript evaluates expressions from left to right. Different sequences can produce different results:
JavaScript:
var x = 16 + 4 + "Volvo";
Result:
20Volvo
JavaScript:
var x = "Volvo" + 16 + 4;
Result:
Volvo164
In the first example, JavaScript treats 16 and 4 as numbers, until it reaches "Volvo".
In the second example, since the first operand is a string, all operands are treated as strings.
JavaScript has dynamic types. This means that the same variable can be used to hold different data types:
Example
var x; // Now x is undefined
x = 5; // Now x is a Number
x = "John"; // Now x is a String
JavaScript Strings
A string (or a text string) is a series of characters like "John Doe". Strings are written with quotes. You can use
single or double quotes:
Example
var carName1 = "Volvo XC60"; // Using double quotes
var carName2 = 'Volvo XC60'; // Using single quotes
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Strings</h2>
<p>You can use quotes inside a string, as long as they don't match the quotes surrounding the string:</p>
<p id="demo"></p>
<script>
var answer1 = "It's alright";
var answer2 = "He is called 'Johnny'";
var answer3 = 'He is called "Johnny"';
document.getElementById("demo").innerHTML =
answer1 + "<br>" +
answer2 + "<br>" +
answer3;
</script>
</body>
</html>
Output
JavaScript Strings
You can use quotes inside a string, as long as they don't match the quotes surrounding the
string:
It's alright
He is called 'Johnny'
He is called "Johnny"
JavaScript Numbers
JavaScript has only one type of numbers. Numbers can be written with, or without decimals:
Example
var x1 = 34.00; // Written with decimals
var x2 = 34; // Written without decimals
Try it yourself »
Extra large or extra small numbers can be written with scientific (exponential) notation:
Example
var y = 123e5; // 12300000
var z = 123e-5; // 0.00123
JavaScript Booleans : Booleans can only have two values: true or false.
Example
var x = 5;
var y = 5;
var z = 6;
(x == y) // Returns true
(x == z) // Returns false
JavaScript Arrays
JavaScript arrays are written with square brackets. Array items are separated by commas.
The following code declares (creates) an array called cars, containing three items (car names):
Example
var cars = ["Saab", "Volvo", "BMW"];
JavaScript Objects
JavaScript objects are written with curly braces {}. Object properties are written as name:value pairs, separated
by commas.
Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
The object (person) in the example above has 4 properties: firstName, lastName, age, and eyeColor.
Example
typeof "" // Returns "string"
typeof "John" // Returns "string"
typeof "John Doe" // Returns "string"
Undefined
In JavaScript, a variable without a value, has the value undefined. The type is also undefined.
Example
var car; // Value is undefined, type is undefined
Any variable can be emptied, by setting the value to undefined. The type will also be undefined.
Example
car = undefined; // Value is undefined, type is undefined
Empty Values An empty value has nothing to do with undefined. An empty string has
both a legal value and a type.
Example
var car = ""; // The value is "", the typeof is "string"
Null
In JavaScript null is "nothing". It is supposed to be something that doesn't exist.
You can consider it a bug in JavaScript that typeof null is an object. It should be null.
Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
person = null; // Now value is null, but type is still an object
Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
person = undefined; // Now both value and type is undefined
Primitive Data
A primitive data value is a single simple data value with no additional properties and methods.
string
number
boolean
undefined
Example
typeof "John" // Returns "string"
typeof 3.14 // Returns "number"
typeof true // Returns "boolean"
typeof false // Returns "boolean"
typeof x // Returns "undefined" (if x has no value)
Complex Data
The typeof operator can return one of two complex types:
function
object
The typeof operator returns "object" for objects, arrays, and null.
Example
typeof {name:'John', age:34} // Returns "object"
typeof [1,2,3,4] // Returns "object" (not "array", see note below)
typeof null // Returns "object"
typeof function myFunc(){} // Returns "function"
The typeof operator returns "object" for arrays because in JavaScript arrays are objects.
JavaScript Variables :JavaScript variables are containers for storing data values.
In this example, x, y, and z, are variables:
Example
var x = 5;
var y = 6;
var z = x + y;
JavaScript Identifiers
All JavaScript variables must be identified with unique names. These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
JavaScript Operators
The assignment operator (=) assigns a value to a variable.
Assignment
var x = 10;
Assignment
var x = 10;
x += 5;
Example
var txt1 = "John";
var txt2 = "Doe";
var txt3 = txt1 + " " + txt2;
John Doe
Adding Strings and Numbers Adding two numbers, will return the sum, but adding
a number and a string will return a string:
Example
var x = 5 + 5;
var y = "5" + 5;
var z = "Hello" + 5;
10
55
Hello5
Operator Description
== equal to
=== equal value and equal type
!= not equal
!= = not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
?: ternary operator
Operator Description
&& logical and
|| logical or
! logical not
Operator Description
typeof Returns the type of a variable
instanceof Returns true if an object is an instance of an object type
Any numeric operand in the operation is converted into a 32 bit number. The result is converted
back to a JavaScript number.
Operator Description Example Same as Result Decimal
& AND 5&1 0101 & 0001 0001 1
| OR 5|1 0101 | 0001 0101 5
~ NOT ~5 ~0101 1010 10
^ XOR 5^1 0101 ^ 0001 0100 4
<< Zero fill left shift 5 << 1 0101 << 1 1010 10
>> Signed right shift 5 >> 1 0101 >> 1 0010 2
>>> Zero fill right shift 5 >>> 1 0101 >>> 1 0010 2
Conditional Statements
Very often when you write code, you want to perform different actions for different
decisions.
JavaScript variables can be converted to a new variable and another data type:
Example
String(x) // returns a string from a number variable x
String(123) // returns a string from a number literal 123
String(100 + 23) // returns a string from a number from an expression
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.
Syntax
window.alert("sometext");
Example
alert("I am an alert box!");
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.
Syntax
window.confirm("sometext");
Example
if (confirm("Press a button!")) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
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.
Syntax
window.prompt("sometext","defaultText");
The window.prompt() method can be written without the window prefix.
Example
var person = prompt("Please enter your name", "Harry Potter");
Line Breaks
To display line breaks inside a popup box, use a back-slash followed by the character n.
Example
alert("Hello\nHow are you?");
JavaScript Events : HTML events are "things" that happen to HTML elements. When
JavaScript is used in HTML pages, JavaScript can "react" on these events.
HTML Events : An HTML event can be something the browser does, or something a user does.
Here are some examples of HTML events:
Often, when events happen, you may want to do something. JavaScript lets you execute code when events are
detected.
HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.
In the following example, an onclick attribute (with code), is added to a <button> element:
Example
<button onclick="document.getElementById('demo').innerHTML = Date()">The time is?</button>
In the example above, the JavaScript code changes the content of the element with id="demo". In the next example,
the code changes the content of its own element (using this.innerHTML):
Example
<button onclick="this.innerHTML = Date()">The time is?</button>
JAVA SCRIPT ARRAY: An array is a special variable, which can hold more than one value
at a time.
If you have a list of items (a list of car names, for example), storing the cars in single
variables could look like this:
Syntax:
2.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
var cars = new Array("Saab", "Volvo", "BMW"); /// using Array constructor.
document.getElementById("demo").innerHTML = cars; //cars[0]—gives info about the element of array
</script> in this case it will return saab.
</body>
</html>
Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays. But,
JavaScript arrays are best described as arrays.
Arrays use numbers to access its "elements". In this example, person[0] returns John:
Array:
var person = ["John", "Doe", 46];
Objects use names to access its "members". In this example, person.firstName returns John:
Object:
var person = {firstName:"John", lastName:"Doe", age:46};
program
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p>JavaScript uses names to access object properties.</p>
<p id="demo"></p>
<script>
var person = {firstName:"John", lastName:"Doe", age:46};
document.getElementById("demo").innerHTML = person["firstName"];
</script>
</body>
</html>
Array Elements Can Be Objects
Because of this, you can have variables of different types in the same Array.
You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array:
myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;
looping Elements
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p>The best way to loop through an array is using a standard for loop:</p>
<p id="demo"></p>
<script>
var fruits, text, fLen, i;
fruits = ["Banana", "Orange", "Apple", "Mango"];
fLen = fruits.length;
text = "<ul>";
for (i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = typeof fruits;
</script>
</body>
</html>
Output : object
The length Property
The length property of an array returns the length of an array (the number of array elements).
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length; // the length of fruits is 4
The easiest way to add a new element to an array is using the push() method:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon"); // adds a new element (Lemon) to fruits
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
Result:
Banana,Orange,Apple,Mango
The join() method also joins all array elements into a string.
It behaves just like toString(), but in addition you can specify the separator:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");
Result:
Popping
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop(); // Removes the last element ("Mango") from fruits
The pop() method returns the value that was "popped out":
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.pop(); // the value of x is "Mango"
Pushing
The push() method adds a new element to an array (at the end):
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi"); // Adds a new element ("Kiwi") to fruits
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.push("Kiwi"); // the value of x is 5
Shifting Elements
Shifting is equivalent to popping, working on the first element instead of the last.
The shift() method removes the first array element and "shifts" all other elements to a
lower index.
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift(); // Removes the first element "Banana" from fruits
The shift() method returns the string that was "shifted out":
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.shift(); // the value of x is "Banana"
the unshift() method adds a new element to an array (at the beginning), and "unshifts"
older elements:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon"); // Adds a new element "Lemon" to fruits
Splicing an Array
The splice() method can be used to add new items to an array:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
The first parameter (2) defines the position where new elements should be added (spliced
in).
The second parameter (0) defines how many elements should be removed.
The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added.
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 2, "Lemon", "Kiwi");
<html>
<body>
<h2>splice()</h2>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = "Original Array:<br>" + fruits;
function myFunction() {
fruits.splice(2, 0, "Lemon", "Kiwi");
document.getElementById("demo2").innerHTML = "New Array:<br>" + fruits;
}
</script>
</body>
</html>
Example-2
<!DOCTYPE html>
<html>
<body>
<h2>splice()</h2>
<p>The splice() method adds new elements to an array, and returns an array with the deleted elements (if
any).</p>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = "Original Array:<br> " + fruits;
function myFunction() {
var removed = fruits.splice(2, 2, "Lemon", "Kiwi");
document.getElementById("demo2").innerHTML = "New Array:<br>" + fruits;
document.getElementById("demo3").innerHTML = "Removed Items:<br> " + removed;
}
</script>
</body>
</html>
Using splice() to Remove Elements
With clever parameter setting, you can use splice() to remove elements without leaving
"holes" in the array:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 1); // Removes the first element of fruits
The first parameter (0) defines the position where new elements should be added (spliced
in).
The second parameter (1) defines how many elements should be removed.
The rest of the parameters are omitted. No new elements will be added.
<!DOCTYPE html>
<html>
<body>
<h2>splice()</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = fruits;
function myFunction() {
fruits.splice(0, 1);
document.getElementById("demo").innerHTML = fruits;
</script>
</body>
</html>
The concat() method creates a new array by merging (concatenating) existing arrays:
The concat() method does not change the existing arrays. It always returns a new array.
Slicing an Array
The slice() method slices out a piece of an array into a new array.
This example slices out a part of an array starting from array element 1 ("Orange"):
Example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1,3);
The slice() method creates a new array. It does not remove any elements from the source array.
This example slices out a part of an array starting from array element 3 ("Apple"):
Example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1,3);
The slice() method can take two arguments like slice(1, 3).
The method then selects elements from the start argument, and up to (but not including) the end argument.
Example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(-3, -1);
start Optional. An integer that specifies where to start the selection (The
first element has an index of 0). Use negative numbers to select from
the end of an array. If omitted, it acts like "0"
JavaScript Strings
A JavaScript string stores a series of characters like "John Doe". A string can be any text inside double or single
quotes:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Strings</h2>
<p>Strings are written inside quotes. You can use single or double quotes:</p>
<p id="demo"></p>
<script>
var carName1 = "Volvo XC60"; // Double quotes
var carName2 = 'Volvo XC60'; // Single quotes
document.getElementById("demo").innerHTML =
carName1 + " " + carName2;
</script>
</body>
</html>
String indexes are zero-based: The first character is in position 0, the second in 1, and so
on.
String Properties
Property Description
constructor Returns the string's constructor function
length Returns the length of a string
prototype Allows you to add properties and methods to an object
String Methods
Method Description
charAt() Returns the character at the specified index (position)
charCodeAt() Returns the Unicode of the character at the specified index
concat() Joins two or more strings, and returns a new joined strings
endsWith() Checks whether a string ends with specified string/characters
fromCharCode() Converts Unicode values to characters
includes() Checks whether a string contains the specified string/characters
indexOf() Returns the position of the first found occurrence of a specified value in a string
lastIndexOf() Returns the position of the last found occurrence of a specified value in a string
localeCompare() Compares two strings in the current locale
new Date()
new Date(year, month, day, hours, minutes, seconds, milliseconds)
new Date(milliseconds)
new Date(date string)
new Date()
new Date() creates a new date object with the current date and time:
Example
var d = new Date();
ex:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p>6 numbers specify year, month, day, hour, minute and second:</p>
<p id="demo"></p>
<script>
var d = new Date(2018, 11, 24, 10, 33, 30);
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>
Gettime function
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript getTime()</h2>
<p id="demo"></p>
<script>
var d = new Date();
var months=[“january”,”feb”,march,april,may,june…]
document.getElementById("demo").innerHTML = d.getTime();
document.getElementById("demo").innerHTML = d.getFullYear();
document.getElementById("demo").innerHTML = d.getMonth()+1;
document.getElementById("demo").innerHTML = months[d.getMonth()];
</script>
</body>
</html>
1587713793112
Get full year
2020
<h2>JavaScript setFullYear()</h2>
<p>The setFullYear() method sets the year of a date object:</p>
<p id="demo"></p>
<script>
var d = new Date();
d.setFullYear(2020);
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>
d.setFullYear(2011,10,3);
comparing dates:
JavaScript Function: JavaScript functions are defined with the function keyword.
Ex:
function functionName(parameters) {
// code to be executed
}
Function parameters are the names listed in the function definition. Function arguments are the
real values passed to (and received by) the function.
Parameter Rules
Parameter Defaults
If a function is called with missing arguments (less than declared), the missing values are set
to: undefined
Sometimes this is acceptable, but sometimes it is better to assign a default value to the parameter:
This.lastname=arg2;
x.firstname;
x.lastname;
The Arguments Object
The argument object contains an array of the arguments used when the function was called (invoked).
This way you can simply use a function to find (for instance) the highest value in a list of numbers:
Example
x = findMax(1, 123, 500, 115, 44, 88);
function findMax() {
var i;
var max = -Infinity;
for (i = 0; i < arguments.length; i++) {
if (arguments[i] > max) {
max = arguments[i];
}
}
return max;
}
EX:
function sumAll() {
var i;
var sum = 0;
for (i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
In JavaScript, the thing called this, is the object that "owns" the current code. The value of this, when used in a
function, is the object that "owns" the function.
Note that this is not a variable. It is a keyword. You cannot change the value of this.
If a form field (fname) is empty, this function alerts a message, and returns false, to prevent the form from being
submitted:
JavaScript Example
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
If a form field (fname) is empty, the required attribute prevents this form from being submitted:
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Output
Data Validation
Data validation is the process of ensuring that user input is clean, correct, and useful.
Most often, the purpose of data validation is to ensure correct user input.
Validation can be defined by many different methods, and deployed in many different ways.
Server side validation is performed by a web server, after input has been sent to the server.
Client side validation is performed by a web browser, before input is sent to a web server.
With the HTML DOM, JavaScript can access and change all the elements of an HTML
document.
When a web page is loaded, the browser creates a Document Object Model of the page.
"The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs
and scripts to dynamically access and update the content, structure, and style of a document."
The HTML DOM is a standard object model and programming interface for HTML. It defines:
The HTML DOM is a standard for how to get, change, add, or delete HTML elements.
<!DOCTYPE html>
<html>
<body>
<script>
document.getElementById("p1").innerHTML = "New text!";
</script>
</body>
</html>
Output
JavaScript can Change HTML
New text!
In the example above the getElementById method used id="p1" to find the element.
The innerHTML property can be used to get or change any HTML element,
including <html> and <body>.
The HTML DOM document object is the owner of all other objects in your web page.
If you want to access any element in an HTML page, you always start with accessing the document object.
Below are some examples of how you can use the document object to access and manipulate HTML.
Method Description
Method Description