Home > Net >  What are objects in js and what are the ways in which they can be created?
What are objects in js and what are the ways in which they can be created?

Time:03-20

i've been doing basic js and react native for some time now, but i've never understood objects. i'm also trying to understand the this keyword, but for that i need to know objects. a few questions:

  1. What are objects in js?
  2. What are the ways to create objects?
  3. i've commonly seen people create objects by using const keyword. eg: const a = {}. however, if i create it as var a = {}, is it still an object?
  4. why is the const keyword frequently used to create objects?
  5. in 3), if the var a = {} is an object, then in this case can a still be considered a variable, or is it an object?

CodePudding user response:

Objects in javascript are basically containers that have different properties for example

let student = {
   studenId:1,
   studentName: John,
}

these properties can be anything you want and can be accessed like this

console.log(student.studentId)

The most common way to create an object is simple assigning it to a variable like the above student example, student is still a variable, it just contains or references an object altho I'd advise you to use let or const instead of var.

another way would be

const student = new Object()
student.studentId = 1 //doesn't have to be a number this can also take the value of some variable you have
student.studentName = "John"

The reason you see people using const is because objects are mutable and you can still change their content even when using const, but you're safe to use let or var instead without issues.

Since you tagged react-native in your question I think I should mention this too: Sometimes in react native you'll notice that the component that relies on some object in state will not rerender when you change that object like

student.studentId = 3 //or any other new value you wanna assign to studentId

the reason for this is that the refrence to the object is still the same so the component won't detect the change, so if you ever encounter this make it a habit to copy the new object using spread operator and then do the change like this

setStudent({
   ...student,
   studentId:3,
})

http://es6-features.org/#Constants

Hope this answers your questions.

CodePudding user response:

In JavaScript. An object is a non-primitive, structured data type in JavaScript. that allows you to store multiple collections of data.

There are different ways to create new objects as mention below:

  1. Using an object literal.
  2. Using New keyword.
  3. Create an Object using Constructor function.
  4. Create an object using Object.create().
  • Related