JavaScript Example (Program)
Learn Details

What is Object Literals ?


Object literals एक object है। जिसे es5 के object को modify करके उसे एक advance रूप दिया गया है । इसमेँ object को create करने या access केने के लिया आसान (easy ) syntax बनाया गया है।


1. Use variable name as a object propery



<script>    
   let firstname = "Teach";
    let lastname = "Coders";

    let obj = {
      fname : firstname,
      lname : lastname
    }
    document.write(`${obj['fname']} ${obj['lname']}`)
</script>
 

2. Variable Name = Object Property & Variable Value = Object Value

<script> let firstname = "Teach"; let lastname = "Coders"; let obj = { firstname, lastname } document.write(`${obj['firstname']} ${obj['lastname']}`) </script>

3. use "variable value" as a "object property"

<script> var fuser ="fname" var luser ="lname" let obj = { [fuser] : "Ram", [luser] : "Kumar" } document.write(`${obj['fname']} ${obj['lname']}`) </script>

4. use object property value as a function

<script> let firstname = "Teach"; let lastname = "Coders"; let obj = { firstname, lastname, fullname : function(){ return `${firstname} ${lastname}` } } console.log(obj) document.write(`${obj.fullname()}`); </script>

5. use multiple word as a "object property" name

<script> let mlt = { ['first name'] : "Teach", ['last name'] : "Coders" } document.write(`${mlt['first name']} ${mlt['last name']}`) </script>

6. Create object by function

<script> function myfunc(x, y){ let full = `${x} ${y}` return {x,y,full} } var c = myfunc("Teach", "Coders"); console.log(c); document.write(c['full']) </script>

Object Declaration 1

<script> // Declaration Tricks 1 let marks = {}; marks['hind'] = 80; marks["eng"] = 50; marks["ttl"] = function (){ return marks['hind'] + marks["eng"] } //access Trick 1 document.write(` Hindi Marks : ${marks['hind']}
Englis Marks : ${marks["eng"]}
Total Marks : ${marks["ttl"]()} `) </script>

Object Declaration 2

<script> // Declaration Tricks 2 let marks = {} marks.hind = 80; marks.eng = 50; marks.ttl = function (){ return marks['hind'] + marks["eng"] } //access Trick 1 document.write(`Hindi Marks : ${marks.hind}
Englis Marks : ${marks.eng}
Total Marks : ${marks.ttl()} `) console.log(marks) </script>