Home > Web Front-end > JS Tutorial > Objects in JavaScript

Objects in JavaScript

Susan Sarandon
Release: 2024-09-19 22:30:49
Original
1075 people have browsed it

Objects in JavaScript

has key-value pairs, separated by colon. The key is also known as property
Similarity: index of arrays are replaced by keys in objects.
Object literal syntax is directly writing properties inside {}
Order during retrieval does not matter in case of objects whereas order matters in arrays.

Arrays: used for structured data
Objects: used for unstructured data

Property lookup methods in objects:

  1. using dot notation
  2. using brackets notation: key is defined as string in [] inside quotes, the key name can be an expression also. Ex. obj['firstName']; Ex. obj[2 3]; Putting an expression won't work with dot notation. We need to use the final property name, and not the computed property name.

Hence, when we have a computed property name its recommended to use brackets notation.

undefined will be returned if a property doesn't exist and we try to access it.

obj['insta-id'] = '@juju';

Refer operator precedence table on MDN for more info.

Object Methods

Fns are a type of value. Hence, we can create key-value pair in which the value is a fn. Means, we can add fns to objects.
Fn expression becomes methods inside objects i.e a fn attached to an object as a value for a key.
Fn declaration inside an object won't work.
method is also a property on the object which holds a fn value.
We can have values in the form of : array, string, boolean, fn etc.
obj.propName(); // will get the fn value and execute it using the ()

'this' : refers to the object on which its called

const person = {
  fName: 'Raja',
  lName: 'Rajeshwar',
  bYear: 1970,
  job: 'King',
  friends: ["Billu","Penchu","Ramesh"],

  calcAge: function(){
    // this will be the object which has called this method.
    // Its used to reference the object, and not hardcode it.
    console.log(this);
    // a new property is created on the person object named 'age'
    this.age = 2024 - this.bYear
    return this.age;
  }
}

person.calcAge(1970);
// age property will only exist if this fn was called atleast once else it won't exist.
person.age;
Copy after login

Arrays, Fns are all under the hood objects in JS. Hence, they have their own methods.

The above is the detailed content of Objects in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template