JS Tutorial
JS Version
JS Objects
JS Function
JS Classes
JS Async
JS HTML DOM
JS Browser BOM
JS Web API
JS AJAX
JS JSON
JS vs JQUERY
JS Graphics
JavaScript ES5
The “use strict” Directive
“use strict” specifies that the JavaScript code must be executed in “strict mode”.
While using the strict mode you can, for example, not use undeclared variables.
Strict mode can be used in all your programs. It helps you to write cleaner code, like avoiding using undeclared variables.
“use strict” is just a string expression. Old browsers are not allowed to throw an error if they don’t understand it.
Property Access on Strings
The charAt() method is used returns the character at a specified index (position) in a string:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>The charAt() method returns the character at a given position in a string:</p>
<p id=”demo”></p>
<script>
var str = “HELLO WORLD”;
document.getElementById(“demo”).innerHTML = str.charAt(0);
</script>
</body>
</html>
Output
JavaScript String Methods
The charAt() method returns the character at a given position in a string:
ES5 enables property access on strings:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>ECMAScript 5 allows property acces on strings:</p>
<p id=”demo”></p>
<script>
var str = “HELLO WORLD”;
document.getElementById(“demo”).innerHTML = str[0];
</script>
</body>
</html>
Output
JavaScript String Methods
ECMAScript 5 allows property acces on strings:
H
Strings Over Multiple Lines
ES5 enables string literals over multiple lines if escaped with a backslash:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Strings</h2>
<p>
You can break a code line within a text string with a backslash.
</p>
<p id=”demo”></p>
<script>
document.getElementById(“demo”).innerHTML = “Hello \
Dolly!”;
</script>
</body>
</html>
Output
JavaScript Strings
You can break a code line within a text string with a backslash.
Hello Dolly!
The best way to break up a string literal, is to use string addition:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Strings</h2>
<p>The safest way to break a code line in a string is using string addition.</p>
<p id=”demo”></p>
<script>
document.getElementById(“demo”).innerHTML = “Hello ” +
“Dolly!”;
</script>
</body>
</html>
Output
JavaScript Strings
The safest way to break a code line in a string is using string addition.
Hello Dolly!
Reserved Words as Property Names
ES5 allows reserved words as property names:
Object Example
<!DOCTYPE html>
<html>
<body>
<h2>ECMAScript 5</h2>
<p>ECMAScript 5 allows reserwed words as propery names.</p>
<p id=”demo”></p>
<script>
var obj = {name: “John”, new: “yes”};
document.getElementById(“demo”).innerHTML = obj.new;
</script>
</body>
</html>
Output
ECMAScript 5
ECMAScript 5 allows reserwed words as propery names.
yes
String trim()
The trim() method is used to remove the whitespace from both sides of a string.
Example
<!DOCTYPE html>
<html>
<body>
<h2>The trim() Method</h2>
<p id=”demo”></p>
<script>
let text1 = ” Hello World! “;
let text2 = text1.trim();
document.getElementById(“demo”).innerHTML =
“Length text1=” + text1.length + “<br>Length2 text2=” + text2.length;
</script>
</body>
</html>
Output
The trim() Method
Length text1=22
Length2 text2=12
Array.isArray()
The isArray() method is used to checks whether an object is an array.
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array.isArray()</h2>
<p>Click the button to check if “fruits” is an array.</p>
<button onclick=”myFunction()”>Try it</button>
<p id=”demo”></p>
<script>
function myFunction() {
var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
var x = document.getElementById(“demo”);
x.innerHTML = Array.isArray(fruits);
}
</script>
</body>
</html>
Output
JavaScript Array.isArray()
Click the button to check if "fruits" is an array.
Array forEach()
The forEach() method is used to calls a function once for each array element.
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array.forEach()</h2>
<p>Calls a function once for each array element.</p>
<p id=”demo”></p>
<script>
var txt = “”;
var numbers = [45, 4, 9, 16, 25];
numbers.forEach(myFunction);
document.getElementById(“demo”).innerHTML = txt;
function myFunction(value) {
txt = txt + value + “<br>”;
}
</script>
</body>
</html>
Output
JavaScript Array.forEach()
Calls a function once for each array element.
454
9
16
25
Array map()
This example multiplies each array value by 2:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array.map()</h2>
<p>Creates a new array by performing a function on each array element.</p>
<p id=”demo”></p>
<script>
var numbers1 = [45, 4, 9, 16, 25];
var numbers2 = numbers1.map(myFunction);
document.getElementById(“demo”).innerHTML = numbers2;
function myFunction(value, index, array) {
return value * 2;
}
</script>
</body>
</html>
Output
JavaScript Array.map()
Creates a new array by performing a function on each array element.
90,8,18,32,50
Array filter()
This example helps in creating a new array from elements with a value larger than 18:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array.filter()</h2>
<p>Creates a new array with all array elements that passes a test.</p>
<p id=”demo”></p>
<script>
var numbers = [45, 4, 9, 16, 25];
var over18 = numbers.filter(myFunction);
document.getElementById(“demo”).innerHTML = over18;
function myFunction(value, index, array) {
return value > 18;
}
</script>
</body>
</html>
Output
JavaScript Array.filter()
Creates a new array with all array elements that passes a test.
45, 25
Array reduce()
This example finds the sum of all numbers in an array:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array.reduce()</h2>
<p>This example finds the sum of all numbers in an array:</p>
<p id=”demo”></p>
<script>
var numbers = [45, 4, 9, 16, 25];
var sum = numbers.reduce(myFunction);
document.getElementById(“demo”).innerHTML = “The sum is ” + sum;
function myFunction(total, value, index, array) {
return total + value;
}
</script>
</body>
</html>
Output
JavaScript Array.reduce()
This example finds the sum of all numbers in an array:
The sum is 99
Array reduceRight()
This example also finds the sum of all numbers in an array:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array.reduceRight()</h2>
<p>This example finds the sum of all numbers in an array:</p>
<p id=”demo”></p>
<script>
var numbers = [45, 4, 9, 16, 25];
var sum = numbers.reduceRight(myFunction);
document.getElementById(“demo”).innerHTML = “The sum is ” + sum;
function myFunction(total, value) {
return total + value;
}
</script>
</body>
</html>
Output
JavaScript Array.reduceRight()
This example finds the sum of all numbers in an array:
The sum is 99
Array every()
This example checks if all values are over 18:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array.every()</h2>
<p>The every() method checks if all array values pass a test.</p>
<p id=”demo”></p>
<script>
var numbers = [45, 4, 9, 16, 25];
var allOver18 = numbers.every(myFunction);
document.getElementById(“demo”).innerHTML = “All over 18 is ” + allOver18;
function myFunction(value, index, array) {
return value > 18;
}
</script>
</body>
</html>
Output
JavaScript Array.every()
The every() method checks if all array values pass a test.
All over 18 is false
Array some()
This example checks if some values are over 18:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array.some()</h2>
<p>The some() method checks if some array values pass a test.</p>
<p id=”demo”></p>
<script>
var numbers = [45, 4, 9, 16, 25];
var allOver18 = numbers.some(myFunction);
document.getElementById(“demo”).innerHTML = “Some over 18 is ” + allOver18;
function myFunction(value) {
return value > 18;
}
</script>
</body>
</html>
Output
JavaScript Array.some()
The some() method checks if some array values pass a test.
Some over 18 is true
Array indexOf()
Searching an array for an element value and returns its position.
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array.indexOf()</h2>
<p id=”demo”></p>
<script>
const fruits = [“Apple”, “Orange”, “Apple”, “Mango”];
let position = fruits.indexOf(“Apple”) + 1;
document.getElementById(“demo”).innerHTML = “Apple is found in position ” + position;
</script>
</body>
</html>
Output
JavaScript Array.indexOf()
Apple is found in position 1
Array lastIndexOf()
lastIndexOf() is the same as indexOf(), but searches from the end of the array.
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array.lastIndexOf()</h2>
<p id=”demo”></p>
<script>
const fruits = [“Apple”, “Orange”, “Apple”, “Mango”];
let position = fruits.lastIndexOf(“Apple”) + 1;
document.getElementById(“demo”).innerHTML = “Apple is found in position ” + position;
</script>
</body>
</html>
Output
JavaScript Array.lastIndexOf()
Apple is found in position 3
JSON.parse()
A common use of JSON is to retrieve data from a web server.
Let’s suppose you received this text string from a web server:
‘{“name”:”John”, “age”:30, “city”:”New York”}’
The JavaScript function JSON.parse()converts the text into a JavaScript object
<!DOCTYPE html>
<html>
<body>
<h2>Creating an Object from a JSON String</h2>
<p id=”demo”></p>
<script>
const txt = ‘{“name”:”John”, “age”:30, “city”:”New York”}’
const obj = JSON.parse(txt);
document.getElementById(“demo”).innerHTML = obj.name + “, ” + obj.age;
</script>
</body>
</html>
Output
Creating an Object from a JSON String
John, 30
JSON.stringify()
A common use of JSON is used to send data to a web server.
While sending data to a web server, the data has to be a string.
Let’s suppose we have this object in JavaScript:
var obj = {name:”John”, age:30, city:”New York”};
Use the JavaScript function JSON.stringify() to convert it into a string:
var myJSON = JSON.stringify(obj);
This results in string following the JSON notation.
myJSON is now a string, and ready to be sent to a server:
Example
<!DOCTYPE html>
<html>
<body>
<h2>Create a JSON string from a JavaScript object.</h2>
<p id=”demo”></p>
<script>
const obj = {name: “John”, age: 30, city: “New York”};
const myJSON = JSON.stringify(obj);
document.getElementById(“demo”).innerHTML = myJSON;
</script>
</body>
</html>
Output
Create a JSON string from a JavaScript object.
{"name":"John","age":30,"city":"New York"}
Date.now()
Date.now() is used to return the number of milliseconds since zero date (January 1. 1970 00:00:00 UTC).
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Date.now()</h2>
<p>Date.now() is new in ECMAScript 5 (2009):</p>
<p id=”demo1″></p>
<p id=”demo2″></p>
<script>
document.getElementById(“demo1”).innerHTML = Date.now();
var d = new Date();
document.getElementById(“demo2”).innerHTML = d.getTime();
</script>
</body>
</html>
Output
JavaScript Date.now()
Date.now() is new in ECMAScript 5 (2009):
1657298628893
1657298628893
Date toISOString()
The toISOString() method converts a Date object to a string, using the ISO standard format:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript toISOString()</h2>
<p>The toISOString() method converts a date to a date string, using the ISO standard format:</p>
<p id=”demo”></p>
<script>
const d = new Date();
document.getElementById(“demo”).innerHTML = d.toISOString();
</script>
</body>
</html>
Output
JavaScript toISOString()
The toISOString() method converts a date to a date string, using the ISO standard format:
2022-07-08T16:45:02.141Z
Date toJSON()
toJSON() is used to convert a Date object into a string, formatted as a JSON date.
JSON dates consists of same format as the ISO-8601 standard: YYYY-MM-DDTHH:mm:ss.sssZ:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Date.toJSON()</h2>
<p id=”demo”></p>
<script>
d = new Date();
document.getElementById(“demo”).innerHTML = d.toJSON();
</script>
</body>
</html>
Output
JavaScript Date.toJSON()
2022-07-08T16:46:11.979Z
Property Getters and Setters
ES5 specifies object methods with a syntax that looks like getting or setting a property.
This example creates a getter for a property called fullName:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Getters and Setters</h2>
<p>Getters and setters allow you to get and set properties via methods.</p>
<p>This example creates a getter for a property called fullName.</p>
<p id=”demo”></p>
<script>
// Create an object:
var person = {
firstName: “John”,
lastName : “Doe”,
get fullName() {
return this.firstName + ” ” + this.lastName;
}
};
// Display data from the object using a getter:
document.getElementById(“demo”).innerHTML = person.fullName;
</script>
</body>
</html>
Output
JavaScript Getters and Setters
Getters and setters allow you to get and set properties via methods.
This example creates a getter for a property called fullName.
John Doe
This example creates a setter and a getter for the language property:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Getters and Setters</h2>
<p>Getters and setters allow you to get and set properties via methods.</p>
<p>This example creates a setter and a getter for the language property.</p>
<p id=”demo”></p>
<script>
// Create an object:
var person = {
firstName: “John”,
lastName : “Doe”,
language : “NO”,
get lang() {
return this.language;
},
set lang(value) {
this.language = value;
}
};
// Set an object property using a setter:
person.lang = “en”;
// Display data from the object using a getter:
document.getElementById(“demo”).innerHTML = person.lang;
</script>
</body>
</html>
Output
JavaScript Getters and Setters
Getters and setters allow you to get and set properties via methods.
This example creates a setter and a getter for the language property.
en
Object.defineProperty()
Object.defineProperty() is used to define new Object method in ES5.
It allows you to specify an object property and/or change a property’s value and/or metadata.
Example
<!DOCTYPE html>
<html>
<head>
<meta content=”text/html; charset=iso-8859-2″ http-equiv=”Content-Type”>
</head>
<body>
<h2>JavaScript defineProperty()</h2>
<p id=”demo”></p>
<script>
// Create an Object:
var person = {
firstName: “John”,
lastName : “Doe”,
language : “NO”,
};
// Change a Property:
Object.defineProperty(person, “language”, {
value: “EN”,
writable : true,
enumerable : true,
configurable : true
});
// Enumerate Properties
txt = “”;
for (var x in person) {
txt += person[x] + “<br>”;
}
document.getElementById(“demo”).innerHTML = txt;
</script>
</body>
</html>
Output
JavaScript defineProperty()
JohnDoe
EN
Next example is the same code, except it hides the language property from enumeration:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript defineProperty()</h2>
<p id=”demo”></p>
<script>
// Create an Object:
var person = {
firstName: “John”,
lastName : “Doe”,
language : “NO”,
};
// Change a Property:
Object.defineProperty(person, “language”, {
value: “EN”,
writable : true,
enumerable : false,
configurable : true
});
// Enumerate Properties
txt = “”;
for (var x in person) {
txt += person[x] + “<br>”;
}
document.getElementById(“demo”).innerHTML = txt;
</script>
</body>
</html>
Output
JavaScript defineProperty()
JohnDoe
This example creates a setter and a getter to secure upper case updates of language:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript defineProperty()</h2>
<p id=”demo”></p>
<script>
// Create an Object:
var person = {
firstName: “John”,
lastName : “Doe”,
language : “NO”
};
// Change a Property:
Object.defineProperty(person, “language”, {
get : function() { return language },
set : function(value) { language = value.toUpperCase()}
});
// Change language
person.language = “en”;
// Display language
document.getElementById(“demo”).innerHTML = person.language;
</script>
</body>
</html>
Output
JavaScript defineProperty()
EN
E5 Object Methods
ES5 added a lot of new Object Methods to JavaScript:
Example
Managing Objects
// Create object with an existing object as prototype
Object.create(parent, donor)
// Adding or changing an object property
Object.defineProperty(object, property, descriptor)
// Adding or changing object properties
Object.defineProperties(object, descriptors)
// Accessing Properties
Object.getOwnPropertyDescriptor(object, property)
// Returns all properties as an array
Object.getOwnPropertyNames(object)
// Accessing the prototype
Object.getPrototypeOf(object)
// Returns enumerable properties as an array
Object.keys(object)
Protecting Objects
// Prevents adding properties to an object
Object.preventExtensions(object)
// Returns true if properties can be added to an object
Object.isExtensible(object)
// Prevents changes of object properties (not values)
Object.seal(object)
// Returns true if object is sealed
Object.isSealed(object)
// Prevents any changes to an object
Object.freeze(object)
// Returns true if object is frozen
Object.isFrozen(object)
Learn more in Object ECMAScript5
Function Bind()
The bind() method allows an object can borrow a method from another object.
This example creates 2 objects (person and member).
The member object borrows the fullname method from the person object:
Example
<!DOCTYPE html>
<html>
<body>
<p>This example creates 2 objects (person and member).</p>
<p>The member object borrows the fullname method from person:</p>
<p id=”demo”></p>
<script>
const person = {
firstName:”John”,
lastName: “Doe”,
fullName: function() {
return this.firstName + ” ” + this.lastName;
}
}
const member = {
firstName:”Web”,
lastName: “Host”,
}
let fullName = person.fullName.bind(member);
document.getElementById(“demo”).innerHTML = fullName();
</script>
</body>
</html>
Output
This example creates 2 objects (person and member).
The member object borrows the fullname method from person:
Web Host
Trailing Commas
ES5 enables trailing commas in object and array definitions:
Object Example
person = {
firstName: “John”,
lastName: ” Doe”,
age: 46,
}
Array Example
points = [
1,
5,
10,
25,
40,
100,
];
WARNING !!!
JSON does not allow trailing commas.
JSON Objects:
// Allowed:
var person = ‘{“firstName”:”John”, “lastName”:”Doe”, “age”:46}’
JSON.parse(person)
// Not allowed:
var person = ‘{“firstName”:”John”, “lastName”:”Doe”, “age”:46,}’
JSON.parse(person)
JSON Arrays:
// Allowed:
points = [40, 100, 1, 5, 25, 10]
// Not allowed:
points = [40, 100, 1, 5, 25, 10,]