JavaScript Getters and Setters | Mosh
- January 3, 2024
- Posted by: MainInstructor
- Category: JavaScript
Video Title: JavaScript Getters and Setters | Mosh
In this lecture we’re going to look at a special kind of methods in objects called getters and setters so let’s imagine we have a person object with two properties first name set this to marche and last name set this to a Madani now somewhere in our application we want to
Display a person’s full name so we have to do something like this consult a lot we can either get the person that first name concatenated with space and then last name or a better way as I told you before is to use a template literal so
We use the back tick and then we add a couple of arguments here so here’s the first one the argument is person that first name now we have a space and here is the second argument person dot last name however the problem with this approach is that maybe there are multiple places
In our application where we want to display someone’s full name with the current implementation we’ll have to repeat this template literal in multiple places a better approach is to define a method in this object call it full name and move this expression right there and then whenever we want to display a
Person’s full name we simply call that method so we can add another key value pair full name but we set the value to a function or as I told you before in es6 we have a shorter syntax to add a method to an object so instead of adding it as
A key value pair we can add it as a function without the function keyword so if you want to define a function outside of an object what do we do we add function the name of the function parentheses and curly braces however when we need to add this inside of an
Object we just drop the function keyword so you can see this new syntax is shorter and cleaner than the older syntax okay so here’s our full-name method we simply return this expression here so I’m gonna cut this and move it here now with this new implementation every time we need to
By someone spooling would simply call person dot full name save the changes we get Marsh comma daddy beautiful however there are a couple of problems with this approach the first problem is that this is read only in other words we cannot set a person’s full name from the
Outside it would be nice if we could do this and then the first name and last name properties would be automatically set based on what we pass here the other issue is that I don’t like to call this like a method it would be nicer if you
Could treat this as a property so we could drop the parentheses like this so how do we do this well that’s where getters and setters come in the picture we use getters to access properties in an object and setters to change or mutate them so in
This object we should add a getter and with that Gator we can read this person’s full name like a property and with the setter we can set it from the outside so here is how it works we prefix this method with a get keyword and now this method is a getter so we
Can access the full name like a property on line 15 let me temporarily comment out this line save the changes you can see our program is still working beautiful so this is our getter now to be able to set this from the outside we need to add a setter
A setter is very similar so we add the set keyword the name of the property or method and then code block however this method needs a parameter we can call it value or anything and the value of this parameter would be what we have on the right side of the assignment operator so
Here let’s assume that value is a valid string we need to split that string by a space take the parts and set the first name and last name properties so value we call the split method of strings you want to split it by a space this will return an array we can call
That parts now we can set the first name two parts of zero a last name two part of one and finally instead of logging the person’s full name let’s just log the person object so initially we set the first name and last name to Muhammad Ani now with this new property which is
Actually a setter we’re changing the name to John Smith save the changes here’s our personal object you can see first name and last name properties are updated also note that full name its value is dot dot dot sometimes when you’re logging objects in the console you may
See properties with this kind of value as we can see from the tooltip this is a getter in order to read the manual you need to click here and now this method is executed and the result is returned in the console so this is the benefit of
Getters and setters in the next lecture we’re going to look at error handling hi guys thank you for watching my javascript tutorial this tutorial is part of my JavaScript course where you learn all the essential JavaScript features that every web and mobile application developer must know if
You’re an absolute beginner or have some experience in JavaScript and are looking for a fun and in-depth course that teaches you the fundamentals of JavaScript this course is for you this course is also packed with tons of exercises that help you master what you learned in the course in fact many of
These exercises are questions that come up in technical programming interviews so if you’re pursuing a job as a front-end or a back-end developer or if you simply want to have a more in-depth understanding of JavaScript I highly encourage you to enroll in the course for a limited time you can get this
Course with a discount using the link in the video description click the link to find out more about the course and enroll
-
Sale!
Wireless WIFI Repeater Extender Amplifier Booster 300Mbps
$29.99$14.99 Add to cartWireless WIFI Repeater Extender Amplifier Booster 300Mbps
Categories: Electronics, Wi-Fi Router, Wireless Wi-Fi Extender Tags: 300Mbps, 802.11N, Amplifier, Booster, Extender, mobile wi-fi booster, Remote, WIFI, Wireless, Wireless WIFI, Wireless WIFI Repeater, Wireless WIFI Repeater Extender, Wireless WIFI Repeater Extender Amplifier, Wireless WIFI Repeater Extender Amplifier Booster, Wireless WIFI Repeater Extender Amplifier Booster 300Mbps$29.99$14.99 -
Sale!
Full RGB Light Design Gaming Headset Headphones with Mic
$24.99$14.99 Add to cartFull RGB Light Design Gaming Headset Headphones with Mic
Categories: Electronics, Gaming, Gaming Headsets Tags: Design, Full, Full RGB Light Design Gaming Headset, Full RGB Light Design Gaming Headset Headphones, Full RGB Light Design Gaming Headset Headphones with Mic, Gamer, Gaming, Gaming Headset Headphones, gaming headset wireless, Headphone, Headphones, Headset, Light, Mic, Package, RGB$24.99$14.99 -
Sale!
Wireless BlueTooth Multi-Device Keyboard Mouse Combo
$39.99$19.99 Add to cartWireless BlueTooth Multi-Device Keyboard Mouse Combo
Categories: Electronics, Gaming, Gaming Keyboards, Keyboard Mouse Combos Tags: Combo, Keyboard, keyboard mouse combos, Mouse, MultiDevice, Set, WireKeyboard Mouse Combo, Wireless, Wireless BlueTooth Keyboard Mouse Combo, Wireless BlueTooth Keyboard Mouse Combos, Wireless BlueTooth Multi-Device Keyboard Mouse Combo, Wireless BlueTooth Multi-Device Keyboard Mouse Combos$39.99$19.99 -
Sale!
High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
$199.99$139.99 Add to cartHigh Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
Categories: Gaming, Gaming Chairs Tags: Adjustable, Chair, computer chairs, Desk, Executive, Gaming, Girl, Headrest, High, High Back Leather Executive Adjustable Swivel Gaming Chair, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar, High Back Leather Executive Adjustable Swivel Gaming Chairs, Leather, Lumbar, Office, Racing, Swivel$199.99$139.99 -
Sale!
Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
$29.99$19.99 Select optionsProfessional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
SKU: N/A Categories: Electronics, Gaming, Gaming Headsets Tags: Cancelling, Gaming, Gaming Headphones with Noise Cancelling Microphone, gaming headset, Headphones, Headset, LED, Light, Mic, Microphone, Noise, Professional, Professional LED Light Wired Gaming Headphones, Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone, Wired, Wired Gaming Headphones, Wired Gaming Headphones with Noise Cancelling Microphone$29.99$19.99 -
Sale!
Gaming Desk with LED Lights USB Power Outlets and Charging Ports
$349.99$249.99 Select optionsGaming Desk with LED Lights USB Power Outlets and Charging Ports
SKU: N/A Categories: Computer Desk, Gaming, Gaming Desk Tags: and Charging Ports, Charging, Desk, Desks, Gaming, gaming desk with led lights, Gaming Desks with LED Lights, Home, LED, Lights, Monitor, Office, Outlets, Port, Power, Room, Stand, USB, USB Power Outlets, White, Workstation$349.99$249.99 -
Sale!
Wired Mixed Backlit Anti-Ghosting Gaming Keyboard
$99.99$79.99 Add to cartWired Mixed Backlit Anti-Ghosting Gaming Keyboard
Categories: Electronics, Gaming, Gaming Keyboards Tags: Antighosting, Backlit, Blue, brown, Gaming, Gaming Keyboard, gaming keyboards, gaming keyboards and mouse, Keyboard, Laptop, Switch, Wired, Wired Mixed Backlit Anti-Ghosting Gaming Keyboard, Wired Mixed Backlit Anti-Ghosting Gaming Keyboards, Wired Mixed Backlit Gaming Keyboard$99.99$79.99 -
Sale!
Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
$119.99$59.99 Add to cartWireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
Categories: Electronics, Gaming, Gaming Headsets Tags: 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, ANC, Audio, Bluetooth, Cancellation, Ear, Earphone, gaming headset, Headphones, Headset, Hi-Res Over the Ear Headphones Headset, HiRes, Noise, Wireless, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Headphones, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headsets$119.99$59.99 -
Sale!
Wired Sports Gaming Headset Earbuds with Microphone
$19.99$9.99 Select optionsWired Sports Gaming Headset Earbuds with Microphone
SKU: N/A Categories: Gaming, Gaming Headsets Tags: Accessories, Earbud, Earphone, Earphones, Gaming, gaming headset with microphone, Headphones, Headset, IOS, Microphone, Sports, Wired, Wired Sports Gaming Headset Earbuds, Wired Sports Gaming Headset Earbuds with Microphone, Wired Sports Headset Earbuds$19.99$9.99 -
Sale!
150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
$49.99$29.99 Add to cart150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
Categories: Charging Stations, Electronics Tags: 150W, 150W Charging Station, 150W Universal Multi USB Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Stations, 150W Universal Multi USB MAX Charging Station, 16 Port MAX Charging Station, 3.5A, Charger, Charging, Fast, laptop charging stations, Max, Multi, Port, Stand, Station, Universal, USB$49.99$29.99
Love your Christmas ad. Its epic.
set can be more elegant like
set fullname(value){
[this.firstname,this.lastname] = value.split(' ')
}
I can not thank you enough
Thank you for explaining this from first principles.
Starting with a simple object, giving scenarios for why you'd need to implement this, and going from there.
perfectly explained, thank you!
I can't believe I was able to understand this in 6 minutes compared to 3 hours of lectures. Saved my life for the exam, thanks lol
with in 5 minutes Mosh helped me to understand the topic 😀
Very simply explained! Formerly I got lost when other people described the same topic. Thank you very much!
Hiii
Your lastname is so similar to iranian's
👌👌
only half way in, but wow what an amazing explanation
That's awesome, understood it fast because of your explanation. What theme are you using, btw?
This made so much more sense, thank you for the video. Hope you are doing well.
Awesome explanation! I was struggling a bit with this concept. Thanks!
the only thing that is unique to setter and getter is the fact that you access them as properties and not as methods? When you say on setter that you can change name inside the object from outside, you can do the same with normal methods.
jesus, i need to sleep
Thank you!
3.18 mouse will get incremented in size haha
Fantastic brother thank you very much!
Gay or German?
Please I have a question….
Why does the "this" keyword work when we put them into objects when initializing since objects cannot be accessed before initialisation?Is it because of hoisting,please just explain this to me…
Wow! That's well explained 👏🔥
感謝分享🙏
Insane explanation🌟
Ohhhh, so that's the difference, I finally understood, thank you very much. 💕 Awesome explanation.
This is the kind of stuff I read before for the question "What's the difference/advantage of a getter over a simple method?", I don't know if it resolves the question because I didn't understood a thing:
-"Given that without a getter, all we can do is poll the attribute for its value, anything else would require a special method which we would have to invoke on the value. Not insurmountable, but will take some thought."
Reading that again made me forget what I saw in the video, I need to rewatch. 😂
In setter without using the variable name const the split return an string
Why it happens?
Really god thank you!
مجتبى جان چرا ایستگاه میگیری داداش . کار نمیکنه این کدی که نوشتی
thank you
As someone who isnt far in JS, i dont see why i would bother adding this complexity for that result.
I dont mind writing object.method() like this, and i dont know often i would need to change something outside the object
Great , professional way
if you execute the line 10 (person.fullName = 'John Smith') in 2:44, the object method would be replaced with a property having "John Smith" as its value.
Great explanation, thanks!
Thanks Hamadani!
i really like this explanation – u earn my sub badman!
@2:34 you say that a disadvantage with regular methods is that they are 'read-only' and therefore "We cannot set the person's fullName from the outside."
How do you mean?
person.fullName = "Bob Brown" <– this will successfully change the 'fullName' property of the 'person' object..
Still don't get it
I don't understand the setting new full name part. Why did it work with just person.fullName = 'John Smith' ? Shouldn't it be person.fullName( 'John Smith' ) ?
anyone knows which is the theme he's using ?
Does anyone know how to do this part
set fullName(value) {
const parts = value.split(" ");
this.firstName = parts[?];
this.lastName = parts[?]
}
if someone's first and/or last name is more than 1 word => so not parts[0] and parts[1]? Like for example "Juan García Reyes" where "García Reyes" is the last name, or "Anne Marie Smith" where Anne Marie is the first name.
thank you very much for this video. I couldn't understand this topic as I am learning at codeacademy. You managed to explain it in a simple logic way. So happy to come across you video
You know why this is great? Because instead of just telling someone what to write and blow their mind you actually explain HOW what you are explaining came to be and WHY you would need it. Not just write this and try to get this. That is the x factor when it comes to coding tutorials. Well done as usual Mosh, I hope that made sense.
this is one of the hardest types of syntaxes to grasp. The second you look away and try to write on your own, you feel lost.
very informative and straight to the point thank you so much !
tried to find the next lecture's video and couldn't, can i get a link or the name of it? thanks!
Your example is useful in most circumstances, but a bit dangerous with peoples names. Best to keep is separate with a first name, last name and optional middle name variable in the setter. There is many people with surnames like Du Pont or De Villiers or even De Bruyn, and if you are going to splice it you will end up with weird results.