Advice for directing further learning

Posted on
  • I've stumbled across a problem that I can't get my head around and am not sure what to search for to learn how to resolve it. Can anyone help name a technique or method which I can read up on?

    I'm trying to access a propety of an object which changes depending on the output of a function. This is a simplified example:

    var days = {
      Monday: {hour: 6, minute: 30},
      Tuesday: {hour: 7, minute: 0},
    };
    
    var today = function() {
      return "Tuesday" // simplified for this example - not sure if return is best approach
    };
    
    console.log(days[today].hour);
    

    Espruino says:

    Uncaught Error: Cannot read property 'hour' of undefined
     at line 1 col 24
    console.log(days[today].hour);
                           ^
    

    Do I need to get today to return a string instead? Any help would be much appreciated.

    This is a situation where I don't know enough to help myself :)

  • @user101594

    in line 10 you pass the function reference of the today function. What you want to use for the property access is the value the function returns... therefore, just execute the function by beating its but with ()... ;-) ...give it a kick to get a kick out of it...

    var days = {
      Monday: {hour: 6, minute: 30},
      Tuesday: {hour: 7, minute: 0},
    };
    var today = function() {
      return "Tuesday"; // simplified for this example (yes string is just perfect)
    };
    
    console.log(days[today()].hour);
    
  • Mon 2020.02.03

    @user101594

    'not sure what to search for to learn how to resolve it'

    to learn
    Asking here was a good choice to start the learning process
    Asking there will be the choice to resolve

     
    W3Schools has always been a good place to start:

    Google:   array javascript site:w3schools.com

    https://www.w3schools.com/js/js_arrays.a­sp



    Array String Indexers

    http://www.java2s.com/Tutorial/JavaScrip­t/0220__Array/Usestringasthearrayindexer­.htm

  • Thank you very, very much indeed. This makes sense now, but I couldn't find any examples which illustrated it in usual places (W3, StackOverflow, etc.). Probably wasn't searching for the right terms.

  • I restructured my data in "days" a few times and lost understanding of what I was dealing with. I thought that it was an object as I couldn't reference its contents with an index e.g

    console.log(days[2].hour);
    

    Firefox console says:

    TypeError: days[2] is undefined
    

    If it's an array after all, then I'll do some more reading about arrays. Thanks

  • Tue 2020.02.04

    'I'm trying to access a propety of an object which changes depending on the output of a function'

    I get that some identifier will be returned from the results of a completed task within a function. And, . . . that value will somehow reference items in a list perhaps?



    @user101594 are we attempting to work with an array, or Json Object Notation?

    https://www.w3schools.com/js/js_json_syn­tax.asp

    L1 in code block found in post #1 is creating a Javascript variable whose content is a JSON object.

    Is the attempt to reference that JSON object 'key' by 'name' and extract it's corresponding 'value'?

    . . . or, . . .

    Is the thinking to access an array by it's indexer? Or an array of a two dim array elements by an indexer?

    ref: snippets in post #5


    I'm not at a development station with an active Espruino device connected, doing the following from memory. . . .

    Debug tip should this not yet be understood

    Typing dump() in Left-Hand console should reveal if declared variables are initialized.

    http://www.espruino.com/Reference#l__glo­bal_dump

    ref: second snipper in post #1
    'Uncaught Error: Cannot read property 'hour' of undefined'

    Entering the variable by name days should do the same. This might also provide a clue as to how the Espruino WebIDE sees what is declared and how it is initialized, and might clear up some mental insight.

  • When you have an object with (named) properties - var o = {n:3,s:"str"}, think of the square brackets

    • either as

      • short form of getter and setter methods to access properties n and s with the property name as string "n" and "s":

    o.getN = function() { return this.n; };
    o.setN = function(n) { this.n = n; };
    
    • which you use as, for examples

    o.getN();  o.setS("me");
    
    • that equals to

      • o["n"]; o["s"]="me";

    • or

      • (pseudo) array accessors with arbitrary index, where index is property name as string

    • or

      • map or directory (object) accessors with key, where key is property name as string

    After all, it is just syntax, and the interpreter knows what kind 'thing' it is that is in front of the square brackets:

    • either

      • a real Array object (w/ consecutive, numerically indexed series of - usually - adjacent storage slots - then the value in the brackets has to be a number

    • or

      • a real Object (w/ arbitrary 'indexed'/ named properties) - then the value in the brackets has to be a property name as string (see also JSON - JavaScript Object Notation - an object declaration in string form: oAsJSONString = '{"n":3,"s":"str"}' - see JSON.stringify(o)/.parse(oAsJsonString) - PS: also supporting arrays... )

    Even though the Array is also an object... it is fundamentally different intrinsic to the implementation and behaves as such differently, even though it has similar looks and analogue functionality - as JSON shows.

    On the other hand, you can think reverse:

    o.n is the short form of o["n"]...

    After all it is just a notation by convention and pure syntax - sugar or salt, what ever you like - that spices up the code... (hence it's name code, coding, codified meaning).

    There is more of the CS Formal Languages theory/philosophy around this... like What are the real, realm specific differences between {n:3,s:"str"} and [3,"str"] and '{"n":3,"s":"str"}' ? ... may be at another post's time...

  • Wed 2020.02.05

    TypeError: days[2] is undefined
    

    re: post #5

    OPTION BASE ZERO   vs   OPTION BASE ONE

    Referencing the element using indexer 2 when there are only two elements using Option Base Zero, will yield undefined as a result, since there is only element zero and element one.

  • If you have an object var o = {n:3,s:"str"}and you try array-access the properties, no matter what numeric value you put into the square bracket, it does not give you properties back... because the number is just another 'name'... but you can use it to add more attributes, for example:

    var o = {n:3,s:"str"};
    console.log("o[1]:", o[1]); // ---> undefined
    o[1]="x1"; // ---> adds new property w/ (numeric)  name ```1``` to object ```o```
              //       and set the properties value to string "x1"
    console.log("o[1]:",o[1]); // ---> access/show property w/ name ```1```: ---> "x1"
    
    
    
    
    o[1]: undefined
    o[1]: x1
    
  • @Robin and @allObjects
    Right after you gave me your advice I went through a long patch of not having any quality thinking time, due to having two very young kids.

    But I came back to it over the weekend, reflected more on what I was doing and got pretty much to where I wanted to get to. Thanks very much for taking the time to reply - it did help. And knowing about dump() is going to be a big help going forward.

    For the record, I think that I'd been getting confused by looking at code examples which featured JSON without really clocking that they were JSON. I simplified my data to being an "object of objects", adapted my functions to not rely on indexers and now it works.

    The only thing which would have made life a bit nicer is the Object.values() method which I learnt about while reading around. I guess there isn't enough space to include everything in Espruino - shouldn't be greedy :)

  • Mon 2020.03.16

    'The only thing which would have made life a bit nicer'
    'I guess there isn't enough space to include everything in Espruino'

    In all fairness to the analysis;

    The Object.values() method is a built in object of the Javascript language.

    https://medium.com/@benastontweet/lesson­-1a-the-history-of-javascript-8c1ce3bffb­17
    https://en.wikipedia.org/wiki/JavaScript­

    Espruino is an Interpreter of the JavaScript language.

    https://www.espruino.com/FAQ#what-is-esp­ruino-

    The reference that may have been used:

    https://www.espruino.com/Reference#softw­are

    is the API for Espruino and not the Javascript language itself.

    https://developer.mozilla.org/en-US/docs­/Web/JavaScript/Reference


    'having two very young kids'

    Congrats are in order. Two future Espruino developers. . . .

  • @user101594,

    Right after you gave me your advice I went through a long patch of not having any quality thinking time, due to having two very young kids.

    Don't be that hard on yourself... first of all: there are the real 'things', that secure the future: the kids, and there are the imaginary / imagined things: formal languages, among them: JS.

    I'm convinced if someone had provided you with the right bench to sit on and overlook the CS landscape, you would say: nothing easier than that - and a great, relaxing balance - to rearing two children... and tend to their comprehensive / challenging everything every minute needs.

    If you were asked to build and present - show and tell about - a (logical) machine / computer / mc that can memorize things by name - property name, such as mail slots for Miller, Fox, Whale,... - and location - (storage) index / place, such as first, second, third,... - you would have come up with congruent patterns for describing and coding of it. Any interpreter - human or machine - listens / reads the data and processes it according to conventions to information and executable instructions... just as you listen to your kids' expressions - visual and audible - and you do as you go.

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Advice for directing further learning

Posted by Avatar for user101594 @user101594

Actions