JavaScript Method parenthesis | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

JavaScript Method parenthesis

Why does document.write(p.yearOfBirth()); work only with parenthesis after yearOfBirth??

11th Apr 2020, 5:14 PM
Shipra Waghmare
Shipra Waghmare - avatar
5 Answers
0
Because the p.yearOfBirth is a method. And not just in JavaScript but in all languages, parentheses are used to call/execute functions. Like print(), log() etc.
11th Apr 2020, 5:18 PM
XXX
XXX - avatar
0
Okay, thank you. I was confused because when we want to print the changed Name or Age or whatever and we use the method changeName or changeAge and in document.write we don't call it using "p.changeName" or "p.changeAge". Rather we write document.write(p.name); without using methodName and parenthesis.
11th Apr 2020, 5:24 PM
Shipra Waghmare
Shipra Waghmare - avatar
0
Yes because they are attributes. Attributes are variables which are present inside an object. And methods are functions present inside an object. Just like you don't need parentheses to access variables, you don't need them for attributes to. For example, let obj = { name : "XXX", age : 100, sayHello : function(){ document.write( "I said hello" ) } } Now name and age are attributes. You can access them by doing obj.name obj.age But add is a function, and you need parentheses to call it. sayHello()
11th Apr 2020, 6:46 PM
XXX
XXX - avatar
0
attribute / property have quite same meanings (and are often missused), but in JS and all the more in web context, common usage is to talk about object properties rather than attributes (wich in web context, are related to the inlined attribute of the element tags)... Anyway, in JS global variables under the hood are properties of the global object (window in browsers context)... and always under the hood, properties of any object is implemented less or more with getter and setter (i.e.: hidden function, wich are called). So, you may see properties as shorthand for implicit function call (with none or once argument, in regard to the operation: read or write -- assign -- value). ... And you could define your customs properties with getter and/or setter (implicitly or explicitly) thanks to Object.defineProperty() and defineProperties() ;) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty (Object.create also allows defining custom properties)
11th Apr 2020, 8:46 PM
visph
visph - avatar
0
Thank you for your informative answers 🙂
11th Apr 2020, 8:52 PM
Shipra Waghmare
Shipra Waghmare - avatar