GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing www.tutorialspoint.com — JavaScript - ES5
Selected Reading
JavaScript - ES5JavaScript ES5, also known as ECMAScript 5, was released in 2009. It was the first major revision of JavaScript. It introduced many new features, including getters and setters, and 'use strict' directive. ES5 has provided significant improvement over the previous versions of JavaScript. The new features introduced in ES5 make code more powerful, concise and easier to maintain. New Added Features in JavaScript ES5Here are the new methods, features, etc., added to the ES5 version of JavaScript.
Here, we have explained each feature in detail. JavaScript Array every()The array.every() method checks whether each element of the array follows a particular condition. ExampleIn the below code, we use the array.every() method to check whether each element of the array is even. <html>
<body>
<div id = "output"> All elements of the array are even? </div>
<script>
const arr = [10, 20, 30, 40, 2, 6];
function even(element) {
return element % 2 == 0;
}
document.getElementById("output").innerHTML += arr.every(even);
</script>
</body>
</html>
OutputAll elements of the array are even? true JavaScript Array filter()The array.filter() filters array elements and gets filtered elements in the new array. ExampleIn the below code, we filter the array elements which are divisible by 10. <html>
<body>
<div id = "output"> Elements divisible by 10 are </div>
<script>
const arr = [10, 20, 8, 30, 40, 2, 6];
function divide(element) {
return element % 10 == 0;
}
document.getElementById("output").innerHTML += arr.filter(divide);
</script>
</body>
</html>
OutputElements divisible by 10 are 10,20,30,40 JavaScript Array forEach()The array.forEach() traverses the array elements. It is similar to loops in JavaScript. ExampleThe below code uses the array.forEach() method to traverse the array and print each array element in the new line. <html>
<body>
<div id="output"> </div>
<script>
const arr = ["TATA", "Honda", "Toyota", "Maruti"];
arr.forEach(traverse); // Using the array.forEach() method
function traverse(element) {
document.getElementById("output").innerHTML += element + "<br>";
}
</script>
</body>
</html>
OutputTATA Honda Toyota Maruti JavaScript Array isArray()The Array.isArray() method checks whether the object passed as an argument is an array. ExampleThe below code checks whether the arr is an array using the Array.isArray() method. <html>
<body>
<div id = "output"> </div>
<script>
const arr = ["TATA", "Honda", "Toyota", "Maruti"];
let bool = Array.isArray(arr);
document.getElementById("output").innerHTML += "Is arr array? " + bool;
</script>
</body>
</html>
OutputIs arr array? true JavaScript Array indexOf()The array.indexOf() method returns the first index of the particular element in the array. ExampleThe below code finds the first index of 23 in the array, which is 0. <html>
<body>
<div id = "output"> The first index of 23 in the array is </div>
<script>
const arr = [23, 45, 32, 12, 23, 56];
document.getElementById("output").innerHTML += arr.indexOf(23);
</script>
</body>
</html>
OutputThe first index of 23 in the array is 0 JavaScript Array lastIndexOf()The array.lastIndexOf() method returns the last index of the particular element in the array. ExampleThe code below finds the last index of the 45 in the array, which is 4. <html>
<body>
<div id = "output"> The last index of 45 in the array is </div>
<script>
const arr = [23, 45, 32, 45, 45, 56];
document.getElementById("output").innerHTML += arr.lastIndexOf(45);
</script>
</body>
</html>
OutputThe last index of 45 in the array is 4 JavaScript Array map()The array.map() method returns a new array after mapping current array elements with new ones. ExampleThe below code uses the map() method to create a new array by doubling the array elements. <html>
<body>
<div id = "output"> The new array is </div>
<script>
const arr = [1, 2, 3, 4, 5];
function doubleEle(element) {
return element * 2;
}
document.getElementById("output").innerHTML += arr.map(doubleEle);
</script>
</body>
</html>
OutputThe new array is 2,4,6,8,10 JavaScript Array reduce()The array.reduce() method reduces the array to a single value. ExampleThe below code multiples all elements of the array using the array.reduce() method. <html>
<body>
<div id = "output">The multiplication result of the array elements is </div>
<script>
const arr = [1, 2, 3, 4, 5];
function multiplier(multiplication, element) {
return multiplication * 2;
}
document.getElementById("output").innerHTML += arr.reduce(multiplier);
</script>
</body>
</html>
OutputThe multiplication result of the array elements is 16 JavaScript Array reduceRight()The array.reduceRight() method reduces the array from right to left instead of left to right. Example<html>
<body>
<div id = "output">The merged array elements in the reverse order is: </div>
<script>
const arr = ["How", "are", "you", "doing?"];
function merge(res, element) {
return res += element + " ";
}
document.getElementById("output").innerHTML += arr.reduceRight(merge);
</script>
</body>
</html>
OutputThe merged array elements in the reverse order is: doing?you are How JavaScript Array some()The array.some() method is used to check whether some elements of the array follow the particular condition. ExampleThe code below checks whether the array contains 1 or more strings with lengths greater than 3. <html>
<body>
<div id = "output">Array contains one or more strings with lengths greater than 3? </div>
<script>
const arr = ["How", "are", "you", "doing?"];
function func_len(element) {
return element.length > 3;
}
document.getElementById("output").innerHTML += arr.some(func_len);
</script>
</body>
</html>
OutputArray contains one or more strings with lengths greater than 3? true JavaScript Date now()The Date.now() method is used to get the total number of milliseconds since 1st January 1970. ExampleThe below code finds the total milliseconds from 1st January 1970. <html>
<body>
<div id = "output">Total milliseconds since 1st January, 1970 is: </div>
<script>
document.getElementById("output").innerHTML += Date.now();
</script>
</body>
</html>
OutputTotal milliseconds since 1st January, 1970 is: 1702540225136 JavaScript Date toJSON()The date.toJSON() method converts the date into the JSON date format. The JSON date format is the same as the ISO format. The ISO format is YYYY-MM-DDTHH:mm:ss.sssZ. ExampleThe below code prints the current date in JSON format. <html>
<body>
<div id = "output">The current date in JSON format is: </div>
<script>
const date = new Date();
document.getElementById("output").innerHTML += date.toJSON();
</script>
</body>
</html>
OutputThe current date in JSON format is: 2023-12-18T06:12:52.366Z JavaScript Date toISOString()The date.toISOString() method is used to convert the date into the ISO standard format. ExampleThe below code prints the current date in the standard ISO string format. <html>
<body>
<div id = "output">The current date in ISO string format is: </div>
<script>
const date = new Date();
document.getElementById("output").innerHTML += date.toISOString();
</script>
</body>
</html>
OutputThe current date in ISO string format is: 2023-12-18T06:13:50.159Z JavaScript Function bind()The bind() method is used to borrow the method from another object. ExampleIn the below code, the bird object contains the properties and printInfo() method. The animal object contains only name and category properties. We used the bind() method to borrow the printInfo() method from the bird object for the animal object. In the output, the printInfo() method prints the information of the animal object. <html>
<body>
<div id = "result"> </div>
<script>
const output = document.getElementById("result");
const bird = {
name: "Parrot",
category: "Bird",
printInfo() {
return "The name of the " + this.category + " is - " + this.name;
}
}
const animal = {
name: "Lion",
category: "Animal",
}
const animalInfo = bird.printInfo.bind(animal);
output.innerHTML += animalInfo();
</script>
</body>
</html>
OutputThe name of the Animal is - Lion JavaScript JSON parse()The JSON.parse() method is used to convert the string into the JSON object. ExampleThe code given below converts the string into an object. Also, we have printed the values of object properties in the output. <html>
<body>
<div id = "demo"> </div>
<script>
const output = document.getElementById("demo");
const objStr = '{"name":"Sam", "age":40, "city":"Delhi"}';
const obj = JSON.parse(objStr);
output.innerHTML += "The parsed JSON object values are - <br>";
output.innerHTML += "name : " + obj.name + "<br>";
output.innerHTML += "age : " + obj.age + "<br>";
output.innerHTML += "city: " + obj.city + "<br>";
</script>
</body>
</html>
OutputThe parsed JSON object values are - name : Sam age : 40 city: Delhi JavaScript JSON stringify()The JSON.stringify() method converts the object into a string. ExampleThe code below converts the obj object into the string using JSON.strringify() method. <html>
<body>
<div id = "output">The object in the string format is - </div>
<script>
const obj = {
message: "Hello World!",
messageType: "Welcome!",
}
document.getElementById("output").innerHTML += JSON.stringify(obj);
</script>
</body>
</html>
OutputThe object in the string format is - {"message":"Hello World!","messageType":"Welcome!"}
JavaScript Multiline StringsYou can use the backslash (\) to break the line of the string and define the string in multiline. ExampleIn the below example, we have defined the str string in multiple lines and used the backslash to break the line. <html>
<body>
<div id = "output"> </div>
<script>
let str = "Hi \
user";
document.getElementById("output").innerHTML += "The string is - " + str;
</script>
</body>
</html>
OutputThe string is - Hi user JavaScript Object MethodsIn ES5, object-related methods are added to manipulate and protect the objects. Methods to Manipulate the Object
Methods to Protect the Object
JavaScript Object defineProperty()You can use the Object.definedProperty() method to define a single property of the object or update the property value and metadata. ExampleThe code below contains the car object's brand, model, and price properties. We used the defineProperty() method to define the gears property in the object. <html>
<body>
<div id = "output">The obj object is - </div>
<script>
const car = {
brand: "Tata",
model: "Nexon",
price: 1000000,
}
Object.defineProperty(car, "gears", {
value: 6,
writable: true,
enumerable: true,
configurable: true
})
document.getElementById("output").innerHTML += JSON.stringify(car);
</script>
</body>
</html>
OutputThe obj object is - {"brand":"Tata","model":"Nexon","price":1000000,"gears":6}
JavaScript Property getters and settersThe getters and setters are used to access and update the object properties securely. ExampleIn the below code, the watch object contains the brand and dial properties. We have defined the getter using the get keyword to access the brand property value. Also, we have defined the setter using the set keyword to set the dial property value in the upper case. In this way, you can secure the updating object property value. <html>
<body>
<div id = "demo"> </div>
<script>
const output = document.getElementById("demo");
const watch = {
brand: "Titan",
dial: "ROUND",
// Getter to get brand property
get watchBrand() {
return this.brand;
},
// Setter to set Watch dial
set watchDial(dial) {
this.dial = dial.toUpperCase();
}
}
output.innerHTML = "The Watch brand is - " + watch.watchBrand + "<br>";
watch.watchDial = "square";
output.innerHTML += "The Watch dial is - " + watch.dial;
</script>
</body>
</html>
OutputThe Watch brand is - Titan The Watch dial is - SQUARE JavaScript Reserved words as property namesAfter ES5, you can use the reversed words as a property name in the object. ExampleIn the below code, delete is used as an object property name. <html>
<body>
<div id = "output">The obj object is - </div>
<script>
const obj = {
name: "Babo",
delete: "Yes",
}
document.getElementById("output").innerHTML += JSON.stringify(obj);
</script>
</body>
</html>
OutputThe obj object is - {"name":"Babo","delete":"Yes"}
JavaScript "use strict"The strict mode was also introduced in the ES5. The strict mode allows you to overcome errors and write clear code. You can use the use strict directive to declare the strict mode. ExampleIn the below code, you can uncomment the num = 43 line and observe the error. The strict mode doesnt allow developers to define the variables without using var, let, or const keywords. <html>
<body>
<div id = "output">The value of num is: </div>
<script>
"use strict";
let num = 43; // This is valid
// num = 43; // This is invalid
document.getElementById("output").innerHTML += num + "<br>";
</script>
</body>
</html>
OutputThe value of num is: 43 JavaScript String[number] accessBefore ES5, the charAt() method was used to access the string character from a particular index. After ES5, you can consider the string as an array of characters and access string characters from the specific index as you access array elements. Example<html>
<body>
<div id = "output1">The first character in the string is: </div>
<div id = "output2">The third character in the string is: </div>
<script>
let str = "Apple";
document.getElementById("output1").innerHTML += str[0];
document.getElementById("output2").innerHTML += str[2];
</script>
</body>
</html>
OutputThe first character in the string is: A The third character in the string is: p JavaScript String trim()The string.trim() method removes the whitespaces from both ends. ExampleIn the below code, we used the string.trim() method to remove the whitespaces from the start and end of the str string. <html>
<body>
<div id = "output"> </div>
<script>
let str = " Hi, I am a string. ";
document.getElementById("output").innerHTML = str.trim();
</script>
</body>
</html>
OutputHi, I am a string. JavaScript Trailing commasYou can add a trailing comma (A comma after the last element) in the array and object. ExampleIn the below code, we have added the trailing comma after the last object property and array element. The code runs without error and prints the output. <html>
<body>
<div id = "demo1"> </div>
<div id = "demo2"> </div>
<script>
const obj = {
name: "Pinku",
profession: "Student",
}
document.getElementById("demo1").innerHTML =JSON.stringify(obj);
let strs = ["Hello", "world!",];
document.getElementById("demo2").innerHTML = strs;
</script>
</body>
</html>
Output{"name":"John","profession":"Student"}
Hello,world!
Note The JSON string doesnt allow the trailing comma. For example, let numbers = '{"num1": 10,"num2": 20,}';
JSON.parse(numbers); // Invalid
numbers ='{"num1": 10,"num2": 20}';
JSON.parse(numbers); // Valid
In ES5, mostly array and object-related methods are introduced. Advertisements
| ||||||||||||||||||||||||||||||||||||||||||||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |