Skip to content

Latest commit

 

History

History
140 lines (132 loc) · 2.29 KB

17. JavaScript Objects.md

File metadata and controls

140 lines (132 loc) · 2.29 KB

JavaScript Objects

const person = {
    name: "John",
    age: 20,
};
console.log(person);

Output

{name: "John", age: 20}

To find Type

const person = { 
    name: "John",
    age: 20,
};
console.log(person);
console.log(typeof(person));

Output

{name: "John", age: 20}
object

Accessing Object Properties

Using dot notation

const person = { 
    name: "John", 
    age: 20,
};
console.log(person.name);
console.log(person.age);

Output

John
20

Change the value of an object

const person = { 
    name: "John", 
    age: 20,
    student: true
};
console.log(person.name);
console.log(person.age);

person.age = 29;
console.log(person.age);

Output

John
20
29

Using bracket notation

const person = { 
    name: "John", 
    age: 20,
};
console.log(person["name"]);
console.log(person["age"]);

Output

John
20

Object Methods

const person = {
    name: "John",
    age: 30,
    greet: function() { console.log('hello') }
}
person.greet();

Output

hello

Programming Task

Can you create an object named student with keys name, rollNo, totalMarks. Give any values you prefer. Also, create two functions: first function to print the information about the student and a second function to check if the student passed the exam or not. If the totalMarks is less than 40, print 'You failed'. If the totalMarks is greater than or equal to 40, print 'You passed'.

Solution:

const student = {
    name: 'Jack',
    rollNo: 12,
    total_marks : 40
}

function studentInfo() {
    console.log(student.name);
    console.log(student.rollNo);
    console.log(student.total_marks);
}

function checkResult() {
    if (student.total_marks < 40) {
        console.log('You failed.')
    } else {
        console.log('You passed.')
    }
}

studentInfo();
checkResult();

Output

Jack
12
40
You passed.

Programiz Quiz

Q. What is the correct way to call this access the object value name?

const student = {
    name: "Sarah",
    class: 10
}
  1. student[name]
  2. student.name
  3. student.name()
  4. student"name"

Answer: 2