logo

NJP

NOWCommunity Live Stream - Lessons Learned - More fun with JavaScript objects

Import · Jun 11, 2020 · video

[Music] good morning good afternoon good evening wherever you are and whenever you are welcome to the community live stream this is the ServiceNow show that helps you learn more about the ServiceNow platform as a developer as an admin as an architect so you can take the insight the journey of discovery the reverse engineering that we do here on this show and bring it to your organization to be more effective my name is Chuck Tomasi senior developer evangelist at ServiceNow and I am happy to be here on June the 11 2020 had to check the date real quick I wasn't sure if we had gotten past the 10th it is going by rather quickly this is done live so anything can happen usually does one-man show I'll charge the lighting of the cameras in everything else you see here so appreciate it any patience you've got good day to everybody who's checking in on the chat we do this live so we've got a YouTube chat going on we also do this on Twitch let me give you the you YouTube URL right there youtube.com slash user slash ServiceNow community as I mentioned to this live go over there like subscribe hit the notifications comment you know what to do it's YouTube it's been around for what about 15 years or more it's it's nothing to do that we don't know how to do that lets other people know there's some stuff out there we do as a back-up plan or if you prefer to watch this on Twitch over at twitch.tv slash now community again URL right there thank you everybody who's checking in Rajat sim ha who else we have HP singh carolyn ram sport good to see you as always submit Dhruv nice to see you happy to be here it's it's another a lessons learned today today this was something I came across a week or two ago and I said oh my gosh that is too good to know too good to pass up must share this because I spent about an hour beating my head against a wall going what is going on here and if I have to go through the pain and suffering I want to share it so the you have to so that's today's topic is JavaScript objects there's more to them than just defining a set of things that go in a container and you pass it around there's some really cool stuff that I learned off the Mozilla developer Network and I want to share that with you but before I continue when I remind you that knowledge is winding down but the content still lives on as on-demand content go over to knowledge that's service now.com you can find it six weeks of infamy No six weeks of wonderful content the the labs the hands-on labs the workshops the the breakout sessions the keynotes there's the heck snacks from creator con it's all there good morning Sanjay and sweet R I'm looking up at the board John Feist is checking in durga Wow we have a great group today and thank you as always for coming at me we also have a webinar coming up on the 23rd which is by my calculations in about a week and a half away this is the 11th it's a 23rd so coming up quickly Michael slobotnik will be joining us to talk about all things this is titled why flow designer and integration R palla for allies I think you know that already the the real underlying topic I'm not sure who came up with this title for the social media card but it's it's really about the features the capabilities the things we've added to integration hub in an flow designer in Madrid New York in Orlando we want to sum that up because we haven't come to this topic in a long time and a lot has changed so current streams bitrate is 1760 1.37 is lower than recommended well that's nice YouTube I'm just the status message popped up hope you're seeing the video okay on your end it looks okay on this end I'm watching a playback as well so apologize for that join us register for this webinar at the bitly link you see there bitly /tn 76 reg i will be doing a little bit of javascript in this episode and you can learn more about javascript if you want to learn more objects I got three at least little episodes about objects and how you define them and how you pass them and all this good information we also did a dedicated episode of this not too long ago about passing objects in and out of functions so you can get more than one thing in and one thing out and when you return a value well you can go back and watch all that but these lessons get you up to speed and ready for the scripting course ready for that next promotion if you want to go from admin to developer or junior developer to senior developer this is a great place to start if you don't know JavaScript or you don't know JavaScript on the now platform this cover some of those idiosyncrasies that we've got I'll beat ups somehow I managed the title let's turn that off yeah we'll get their page to title off page 1 back to where we were sorry bump the wrong button one man show live you can find the code that we're writing today in the bitly lake you see there SF CLS verified is still working good morning swap know who else is checking in dergah hope everyone is safe and healthy yes I do as well so thank you for sharing that everybody stay safe stay healthy be kind tolerant you know all the stuff that's it's really coming to the fore I don't want to turn this into a news channel but it bears mentioning that it's a rough place right now there's a lot of change going on change for the better I might add in many cases so be open-minded be kind tolerant and we'll get through all this the where were we let's get speaking of getting through all this let's get through all the intro stuff and get to this these episodes are inspired directly from your posts on the community so I see ideas there I'm working on personal projects it all comes together this would make for a lot of fun so let's have some fun with JavaScript objects I forgot to mention the developer community let me just get that real quick because I am using a free personal developer instance if you haven't got one go over to developer.com get yourself an instance you can follow along you can tweak these you can practice you can play and and learn more as you go free from the risk of anything you might incur on your organization's developer instance so anything you do on your personal developer instance you can always wipe take it off mess it up and do what you turn on plugins your organization will then have a smarter you to go do your development learning plans are they're totally free we've got videos we can links to it we got events you know what I haven't checked the events calendar in a while we should do that let's go to developer done service now calm I know there are some meetups coming so let's go to connect events you don't even need to login to do this part you can be part of this community Boston is coming up on June 22nd I really want to be part of that so I'm going to put that on my calendar Vancouver June 25th I think I could make that as well these are Thursday ones a Monday event should be good Wednesday Thursday event be good Richmond October 13th well Richmond really plans him out November 10th Richmond's got them scattered way out there good for you Richmond for planning on that hopefully everybody's got a clear calendar out there and there are no conflicts so I'm going to try and make as many of these virtual meetups as possible hopefully I will see you at one of those but meanwhile back to our instance let's talk about that free personal developer instance I know I said that before can we expect from you to take some session on learn Ajax JSON on ServiceNow - I have a series on JSON from techno series on Glide Ajax go back to episodes 5 is on client scripting 6 I believe is script includes and 33 so if you look through the technology in the show notes but it's bitly slash ServiceNow - tech now that's a minus sign - check now and you will find 5 6 and 33 you should have a good feeling of what Glide Ajax is all about after watching those so well not to say I've already done it and been there but been there and done that let's go through some JavaScript object all right first things first what is a JavaScript object I'm going to bring up our old friend scripts background and I also have a pre-baked scripting here normally let me put the files away for just a moment normally this is how you would see an object defined you might also see it defined as var okay like this with a real clever name it might be new object okay that is the legacy way of doing it still works you're defining an object space more modern approach that I've seen and preferred from all the documentation I've seen is to use the empty curly braces then you could start saying obj dot ID equals one two three four five that kind of thing and you can fill these in with dot notation or you could create new properties obj with what they call bracket notation name equals this is also known as a hash array because it's not using a numeric index it's using a string index which technically makes it an object so I'm not going to do that I'm going to do it all in one lump sum well almost all in one lump sum because my variable user is an object OVS code we love you but when you hover over something you try to help too much and it obscures what I'm trying to say I'm going to make an array inside of an object incident list not gonna do anything with it but just want to show you what types of things you could do you could do boolean's you can do integers any of those primitive native datatypes that you've seen in JavaScript are available to put in here so I've got first name Chuck last name Tomasi and this mode okay I'm whatever mode is it's going to tell me where it goes and what I want now my exercise that I was working on my my pet project needed to set a message in here somewhere this was done in service portal and I was trying to retrieve a message based on where it was in the screen so if you're on the settings screen it will go do a GS get message and say these are the settings you know trans things we'll get to that more in live coding happy hour on Friday okay so which would be tomorrow if you're around for watching that or if not you watch it later but that's our exercise a little bit of advertising for another series live coding happy hour we're going to be doing this live I'm looking more into translations specifically the i18n provider but again another story for another time one of the ways that I was doing this originally was let's just go and set another property called you i dot message and use our old pal on the server server side GS get message and say go get the key that aligns to user dot mode which is CLS user message where is that stored glad you asked that is under UI system UI messages I like to type messages and it's at the way bottom under system UI messages right there and when I click that it has this table of translations this is some of the translation stuff in your instance okay this is things for buttons this is things for status messages that get put out a whole other episode on that I think we have a pretty sure we did technolon localization translation and internationalization as well but you can see here's my CLS user message and if I open that up it says I belong to the scope CLS 323 which is fine this is a key which is purposely ugly I've mentioned this before if I just said hello world it becomes very difficult to translate if there isn't an entry in here it will show whatever's in the GS gap message key parameter and then here's the translation in English so it tells me the language so if I wanted to send this off say to a translation service and and good you know what I need this in Japanese and French and German they could take this text export a spreadsheet say translate these please change the language bring it back in and I've got the right key for that language in that translation and then Jia's get message does its job it says well since you're in Japanese I'll go get you the Japanese version that's what we're after back to my script so I'm passing in this key that says please go translate for me and then I'm simply going to print out what the result of that was as user dot message this is this is what I did for step a brute-force let's see what happens we're going to put that into scripts background which is right here paste tab enter and it says exactly what I expect user dot message is users are the lifeblood of our system okay did all right that wasn't too bad so I now have an entire object if we want to print the entire JavaScript object if I just tried to do user let's put this in strings user equals it doesn't do what an array would do in that it says hey I'm gonna convert you to a string implicitly because we're doing text output I'll put in some commas for you is life is nice if you try to print an object and just say what does user look like it will say it's an object that's not very friendly what you can use is JSON dot stringify and say pretty the user object very nice but it's all on one line a little hard to read I'd rather have it formatted there are a couple other arguments that I often throw in here null for okay for says how far do you want to indent it you could seem dead one space you get in debt ten spaces I think for is pretty readable without taking up a lot of white space and I get a nice output of what the user object looks like including my new appended message property with the ggs get message so that is wonderful we've got step one done and you learned a little there is a what was a JSON script include that you would say I need a new JSON and I'm going to encode it or decode it it was a legacy ServiceNow thing for expert three which was around until about 2015 I think on ServiceNow when we went to EC five might have been a little after that but this is the standard way works on client script works on server scripts works on pretty much everything json dot stringify is a standard atmosphere of five which is what we're using on the platform today so I encourage you to use that very flexible use it all the time I'm uses so often I'd like to make a shortcut for it okay back to our Ichiro's hate it when that happens let's go back to our files and see plan B now I'm going to sneeze I promise I will try to mute if I do that back to our files getters and setters number two so what I discovered after looking through the Mozilla developer Network was that I could declare this but also put in a getter didn't know this till I looked around my objective was I'd like to set this all at once set the user mode and then reference like at this property do how do you do that in an object did a little research how do you set this based on that if you will and I can access this dot mode using a get like ah the object has self references that was awesome that made my day so when I run this to see what is user message become let's go throw that into scripts background it does the same thing but it's done when the object is set up so once I set user mode then anytime I reference the message property it says oh in order to get that I need to run this and go reference mode and we're good okay so I'm not sure if it does this at run time or if it does this I mean if it does it here I haven't checked if it happens here on the GS info or if it happens here on the varsity there's really the two statements of the script of our statement and a GS info so looking at that I couldn't tell you I guess we find out somehow that was Plan B worked very well then I found wait there's more than getters there setters let me walk you through this one same kind of thing only instead of get it uses a set and to call the set you access whatever the set is so this one says set set message so if I call in effect it's like a mini function and you can act on the object it has a reference to this but it sets something based on something else so it's not returning a value which getters do it's actually doing like a little internal operation so I I can't access whatever user message is without setting it somehow it almost looks like an assignment statement well it is an assignment statement but it takes that as parameter you can only pass in one parameter but you can do a whole bunch of other stuff to the object within that Center function so let's take a look at what that does and how it works and you just say gee Chuck it looks a lot the same users are the lifeblood of our system message is in fact set because of that other rule what is message that's what I want to know is what is message before come on give me the whole line I'm trying to triple click and it's not helping what is message before the set message comes along it's not even defined so it's going to say it's undefined it doesn't exist until the center sets it so when would you use which and why well that's up to you depends on your situation getters are used to in my case the getter was almost exactly the same functionality it sets a property but the property just returns message it looks like a property but it's fetching it I'm pretty sure this is happening when you acts when you ask for it asks for it where did that come from and then this one sets it when you when you trigger the set function and again if you had like user dot a is 10 user dot B is 5 you could use a setter to set those values through different values and perhaps even trigger a sum and say well C is a plus B okay 5 and 10 so C would be 5 you could use a getter or Center to adjust some of those and say well let's increment or decrement or so you could set other properties based on it's a little mini function in your object very cool this was all fine and dandy until I got to service portal that's where the wheels fell off my wagon and I went what is going on so let's - over to service portal which is my object tester widget here and I have set up instead of var user I'm doing data user so I can pass it to my client and my HTML columns I've client turned off I'm not using it for this exercise and I'm going to render the data user object with this pipe JSON in a pre tag so it comes out nice and pretty in the preview window just an easier way to display it on service portal great way of debugging by the way if you haven't seen it there is a service portal debugging video on the ServiceNow support channel that I learned this from I didn't do this I narrated it as I was narrating oh wow that's cool I want to do that that's what I'm going to use that so the fun of doing voiceovers mmm back to the tee and the service now Yeti good stuff all right so here we have our original plan B excuse me plan a where we just set data user messages equals get message and you could see message is in fact set to that get message that we got let's switch this up to plan B in order to do that Plan B has this kind of thing I replace I have mode so down here I'm going to paste in a get message and it's going to complain it's gonna say uh no it's gonna complete because I don't have a comma there and it's also going to say yeah well these are es five features and I'm not sure what that's trying to tell me what is service portal is it if it's not es five is it six I don't know is it hopefully it's not three but the good news is let me reformat that a little cleaner the good news is it works so instead of setting this I can simply just say go get me this stuff and when I said it I run it I save it the preview comes back up and message is in fact set by that getter because this says go get me the entire data dot user this is printing a GS info log which may in fact be calling the getter first what happens if I don't call that it still works okay so getters appear okay even though you get this crazy stopping unable to continue 52% scanned but yet it's working so use it your own risk I guess can we also use this dot mode in a getter setter yes yes in fact I hope that answered your question John I was looking up there a little little older what would be the difference between D declaring var object equals new curly brace and compared to var object equals new curly brace you wouldn't use a new deny type new no use a new when declaring an object it's if you're declaring an object based on a class like a script include then yes you would do that new instantiates a class I have no clue I have no class here okay that's why it is just declaring it as here's your object here's your properties so get into that when I get into classes on the JavaScript video so good question I know idea we could use getters and setters and objects neither did I that's why I'm sharing this is fun so just picking up a few comments from the transcript thank you everybody for joining in on this the okay let's go to Plan C what happens if you use a center in service portal this is where it gets even more fun so I'm going to do this and let's first replace the get with a set and that should look the same incident list first name last name mode is now here I don't have a mode it's just using this I don't have a mode property which is fine I don't need one in this case because what would be the value of having mode I guess I could set the mode from here user that set message user dot mode that might be another way to do it so let's take that out I want to make it look the same then I'm going to define that message with our data dot user it got a reference the same object data is one of those special things in service portal you can pass stuff around and we should be good there's Plan C this is where things get a little wonky or at least they used to when I was playing around with it I save it it loads I have no idea how I got message this was not working before set message mode mode message is set already then is this wasn't working I couldn't reference it it was saying I have no idea what you're talking about what is this message you speak of now it could have been I had forgotten a data dot something somewhere in my call so apparently you can use a min service portal I was having all kinds of problems which was half the fun of showing you this part like this is where it goes crazy but could have been a dumb user error that I was tired you know how that goes you're writing script and you spent an hour going that's a curly brace instead of a it's parenthesis you're kidding me I forgot I spelled user wrong yeah it's a comma not a dot what's going on here so yes that happens all the time let's go on I have a little bit more to tell you that's getters and setters in a nutshell and apparently work better in service portal and I was led to believe the other exercise I wanted to show you is how to identify if something is available in an object now I got caught in my client script trying to ex reference a property in an object that wasn't defined and it gets nasty on your nose hey you can't do that there's no ID and the location object of the user object so let me give you the example I was working on if I have this user object similar to before incident first name last name and I say let's go get user dot setting dot active do you recognize this right away go Chuck there's no setting so how can you dot walk to active and the JavaScript machine will tell me the same thing which is what nope let's get this going which is what this message tells you it says no you can't you cannot set a property active of something that is undefined and you can't access it from undefined and it will come up and say you are undefined and I was doing this all over the place because I was saying here's my user record user has a feel a reference field go pick up some properties off of user and make me an object and go pick up the values off of this reference field and make a sub object and object within it and if that field was empty you'd get nothing for the sub object you know say it was customer and location if location wasn't set you'd have no location object whoo that would be bad because at certain points in my script I was saying customer dot location dot city for example and it goes no no city doesn't exist because location doesn't exist that's bad so I wanted to set up this error proofing as it were the way to check to say well wait a minute does location exist if it does then I'm confident that it will have the properties I need in it so what you can do this is first example yes all right let's go over in this editor looks better okay here's my object once again and you can use this in this is again straight off the Mozilla developer Network fortunately it works in ServiceNow - because I know we've got a slightly modified version of es 5 and sometimes when you're reading the mdn Doc's they're actually referring to es6 so you gotta be a little careful when you're referring to online Doc's this is my interpretation of what I read and experimented with and you can use this in to say is there a setting in user if there is then I will go ahead and set the active flag if there is not then I will err tell you straight up on the screen hey I don't have this you can't do this have a nice day or you could do a try/catch that kind of thing would be another option go watch this javascript video on try and catch an error and finally I think is another piece of that so let's see what happens when we try this with our fix which says if setting in user and it says hey setting does it exist in user no throw an error now I want to take that same example because this I believe is still an issue in service portal let's go back to a very simple object we're not going to set message but what we are going to try to do is that same type of operation and say if data got user user dot setting we need to do a set excuse me let's do this if setting you gotta put it in quotes single or double doesn't matter yeah and notice how in is highlighted as a keyword it is a keyword don't name your variables in okay there you go in data user so I can drill in and say just let's just set it data dot user dot setting got active that's three T's setting dot active equals true save and view and if I'm not mistaken there is a message in the console log that says that's not the message I was after oops I hit reload instead of save I just want to hit save I'm not sure where this bad request is coming from but I thought it said in is not a supported feature either well we're all learning together today so encourage you do some testing on this stuff before you put it in production next the better way that I found let's go back to our editor the better way cuz I did I swear I ran into this somewhere it said you can't do the in feature okay so I can't what can I do there is another one called has own property this one I've known about for a while but I don't use it as much as I should in most cases to do some error proofing of my code now that I've got an explicit case where I know that field can sometimes be empty and I'm not going to bring back the sub object appropriately I'm used to give all the time this is my go-to mechanism more so than in I know Ian reads a little more friendly but this jumps out if you're going whoa that seems a little more heavy-duty in my opinion totally up to you do some experimentation these two functionally appear to do the same thing let's go back to scripts background I'm going to paste that in and it really just checks same thing does user have a property or an object or something in it called setting what do you got if you don't it will say hey I don't have a setting well if I go up here and make one and say setting and I can even just make it a blank nothing object it goes yeah a setting exists now we can use it okay so it falls into that same condition very easy to do so getters and setters in and has own property use those when you're dealing with objects and you may be able to save yourself some time headache pain and suffering any questions up there if gstl user dot setting again you're gonna get a year you could I tend not to use GS nil a whole lot it doesn't seem to provide any value I mean let me give you an example of that let's take setting out of here so what roopam is suggesting and I've seen this a lot in our scripts if GS nil it'll work user dot setting it's going to say is this undefined is it empty is it no it will check a number of things you say gee estar error hey there's no setting here oh good I'm using a double quotes I can do this I was getting nervous what I throw a quote in a string and of course it will say there's no sitting here and because it's a GS error it says no throw error alright here let's make it a little less hostile there there's no sitting here if you just take this out though it will effectively JavaScript has gotten a lot smarter it will do the same thing oh it won't do the same thing oh-ho all right so learn something else today there was another one I think there's a GS util that does the same that UJS util dot nil was it somebody clarify me on this one we have a lot of script includes that I can't keep all the methods straight in them there's nothing here there's my pose for the picture but a lot of times if I just want to check variables like let's do the incident list or let's set a couple other values in here let's just make name is empty string and I don't know we'll call it value is no you can't actually define null that way those are defined so apparently GS nil checks for undefined and the straight-up if doesn't oh you know what I didn't do user dot setting I forgot to put the not in there weren't weren't okay this does the same thing okay GS nil to me and jsut tilt nil afford no extra value to me you may say it's easier to see in your code fine go use that but to me less typing is more fun keeps it keeps it handy er so this does the same thing to me in my mind anyway unless somebody can prove a use case where it doesn't for checking for nil null empty undefined values same kind of thing I could do the same for let's do a quick copy and paste for name there's no name let's do the same thing for value there's no value and incident list I don't know if this does this for empty arrays I think you might have to do incident that list dot length because it is an array let's find out oh well apparently it works there's no setting there's no name there's no value and because setting is undefined name is empty value is no incident list is empty array if I were to put something in here 4 5 6 that last one should now be gone ok we have a nice way to check with just using the the knot exclamation point to say check if it's a truth e or a false e value and I get all into that in my value in my in my JavaScript series I know this is kind of pointing at that one a lot but truthy and falsy are not necessarily the values true and false could be 0 and 1 it could be empty and not it could be defined or not there's a lot of ways to say truthy and falsy if you hear somebody say truthy and falsy it's an extended version of true and false but it works equally well in JavaScript expressions like this so use it anybody else got anything yeah it someone to put jsut tell up there I think we're good that's it for today thank you very much for joining me I do have to run to another meeting at the top of the hour thank you let's go back to this and I don't have next week's lineup lined up yet I do that on Friday mornings but I invite you to come back on Monday at 2:00 p.m. UTC and see what we're up to and Thursdays at 2 p.m. UTC for another wonderful sharing of how things go on the ServiceNow platform that you could take to your organization I've got lots of ideas in the backlog but if you want to hear more please feed them in the comments or either on the community or on YouTube I love to hear them there's there's people coming at me all the time with ideas I go ok that one needs research that one that one I can do I love to share this stuff with you it's what gets me out of bed in the morning until Monday the 15th of June doing a little math in my head it's Thursday still the 11th I will see you again real soon so let me play that wonderful music and I am out of here bye [Music]

View original source

https://www.youtube.com/watch?v=GY1ub7BdDAs