Symbols tutorial in Advance JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Symbols Advance JavaScript</title>
<link rel="stylesheet" href="">
</head>
<body>
<script>
//Here Symbol means "A Unique Value"
let id1 = Symbol("Hello World");
let id2 = Symbol("Hello World");
console.log(id1);
console.log(typeof id1);
console.log(id1 == id2); //Here both "id1" and "id2" are Unique Value(Because of Symbol)
let str1 = "Hello";
let str2 = "Hello";
console.log(str1 == str2); //Here both "str1" and "str2" are Same Value
// alert(id1.toString());
// alert(id1.description);
document.write(`${id1.toString()}<br>`);
document.write(id1.description);
let age = Symbol("age");
let ageTwo = Symbol("ageTwo");
let user = {
name: "Hello brother",
class: "BTech",
country: "India",
language: "English",
[age]: 25 //This is First way for adding Symbol value in Object
};
user[ageTwo] = 34; //This is second way for adding Symbol value in Object
console.log(user);
console.log(user.name); //Getting individual Object Value in Console
console.log(user.class);
console.log(user[age]); //Getting individual Object Symbol Value in Console
console.log(user[ageTwo]);
//NOTE : We can not use Symbols with for in Loop
for (let key in user) {
console.log(`${key} : ${user[key]}`);
}
//NOTE : When we convert Object to JSON using JSON.stringify() then Symbol value will be skipped in JSON Format
console.log(user);
console.log(`${age.description}`);
console.log(JSON.stringify(user)); //Here Symbol value will be skipped after converting in JSON Format
</script>
</body>
.png)
.png)
.png)
Comments
Post a Comment