JavaScript: Things To Watch Out For

Discussion in 'Learning Javascript' started by Kino, Jul 14, 2017.

  1. Kino

    Kino EIS Game Dev Veteran

    Messages:
    515
    Likes Received:
    672
    Location:
    United States
    First Language:
    English
    Primarily Uses:
    RMMV
    JavaScript: Things To Watch Out For
    Today's post isn't about new techniques. Today we cover some things to be wary of in JavaScript. These include Function Hoisting, pass by value, scoping rules, and this.



    Function Hoisting
    Function hosting can be a problem. When you create a function without passing it to a variable, JavaScript pushes the function to the top of your file. Here's an example:



    This kind of behavior can be a cause for error if you don't understand it, because functions may be available when you don't expect them to be. If you don't want this effect, assign your functions to variables. Now since we're on functions, let's discussing scoping rules:



    Scoping Rules
    There three ways to declare a variable in JavaScript; you can use let, const, or var. Both let and const are block scoped; var is function scoped. This is an important distinction to make. Now, here's an example illustrating that property:



    As you can see var drips out of the block scope and is available throughout the entire function; const and let do not. Furthermore, they also throw errors if used incorrectly. In most cases, let and const are preferred over var; const and let can accomplish more consistent rules when compared to var. Well, since we're on variables, let's discuss pass by value & cloning.



    Pass By Value
    JavaScript is a pass by value language; if you pass 2 to a variable and change it to 1, then the variable's value is 1. Well, objects and arrays are not so simple. Arrays and objects can be passed to new variables as new arrays or objects, but still, change the properties on the original. Here's an example:



    Now, for me, this behavior can be confusing. See, many times JavaScript makes a shallow copy of the original array or object. This means the array of objects or list of arrays within your array refers to the same object in memory. If you're not careful, this can trip you up as a developer.

    This is why you should value immutability, or when passing around objects, clone them (similar to the solution). Now, in JavaScript clone and copy are different; the clone does not reference the same object in memory -- copy does.

    These are just some of the things to watch out for in JavaScript; be careful on your JavaScript coding journey. ~
     
    #1
  2. LTN Games

    LTN Games Veteran Veteran

    Messages:
    609
    Likes Received:
    459
    Location:
    Canada
    First Language:
    English
    Primarily Uses:
    RMMV
    Object references are by far the most deceiving and #1 to watch out for. Makes you wonder why JS has never included a way to natively deep clone a function something like:
    PHP:
    Object.deepClone(object)[/PHP
     
    #2
  3. Sarlecc

    Sarlecc Veteran Veteran

    Messages:
    454
    Likes Received:
    209
    First Language:
    English
    Primarily Uses:
    RMMV
    Technically there are four ways to declare a variable; though the fourth really doesn't have a solid use case and should not be used as it floods the global scope. This also means that garbage collection will never free this variable as it is considered to always be in use.
    Code:
    function globalVariable () {
     global = 8;
     console.log(global);
    };
    
    //returns 8
    globalVariable();
    
    //also returns 8
    console.log(global);
    The cloning issue was/is quite prevalent in Ruby as well. I first ran into to it when creating my Time_Machine script :p.
     
    #3
    Kino likes this.
  4. Jonforum

    Jonforum Veteran Veteran

    Messages:
    1,577
    Likes Received:
    1,353
    Location:
    Canada / Québec
    First Language:
    French
    Primarily Uses:
    RMMV
    the best fast native way i found is to use valueOf !
    it will return a new valur Instead of cloning the reference.
    PHP:
    var pID this._PID.valueOf(); // 5
    pID++; //6
    pID++; //7
    console.log(this._PID); //5

    // but without valueOf/////////////////
    var pID this._PID// 5
    pID++; //6
    pID++; //7
    console.log(this._PID); //7 !!
    nativli in the core is do that
    PHP:
    function ObjectValueOf(){
    return 
    ToObject(this);
    }
     
    #4
    Kino and LTN Games like this.
  5. LTN Games

    LTN Games Veteran Veteran

    Messages:
    609
    Likes Received:
    459
    Location:
    Canada
    First Language:
    English
    Primarily Uses:
    RMMV
    This works for primitive properties only not if you have objects, arrays or functions as an object property.
    PHP:
      const obj = {
        
    anum22// works
        
    aString'Yes'// works
        
    anObj: {o1}, // Won't work
        
    myFunc () {} // Won't work
      
    }
     
      const clone = 
    obj.valueOf()
      clone.
    anObj.5555
      
    clone.myFunc = () => console.log('new function')
     
      
    console.log('Cloned: ', clone, 'Original: ',obj)
    but you could make a function with valueOf() which recursivly goes through object applying valueOf and returns the new obejct when complete.
     
    #5
    Kino and Jonforum like this.
  6. Jonforum

    Jonforum Veteran Veteran

    Messages:
    1,577
    Likes Received:
    1,353
    Location:
    Canada / Québec
    First Language:
    French
    Primarily Uses:
    RMMV
    I had never tested for the objects{} it is good to know;
    for array i know,
    In my structure, I prefer to create a direct inheritance in new bracket, [ , ] I find it cleaner and readable
    example here: f46e42 inherit d8a757 valur
    PHP:
    //□▼↓▼□═══════════════════════════════════════════════════□□═══════════════════════════════════════════════════□↓↓↓
        
    _displace.prototype.iniPosition = function(position){ // 'hide' ,'default', 'custom'
            
    var this._posXY[position], p.base[0], p.base[1];
            
    p.d8a757 = [X,Y]; //#d8a757 DisplaceHud BG
                
    p.f46e42 = [p.d8a757[0] ,p.d8a757[1]-10]; //#f46e42 TEXT STAMINA PLAY
        
    return p//END
        
    };
    //□▲↑▲□═══════════════════════════════════════════════════□□═══════════════════════════════════════════════════□↑↑↑
     
    #6
  7. Kino

    Kino EIS Game Dev Veteran

    Messages:
    515
    Likes Received:
    672
    Location:
    United States
    First Language:
    English
    Primarily Uses:
    RMMV
    The object bit is my main gripe, but it is manageable, but when running into more complex types, such as classes. Copying over the properties can be a bit of a pain. I'm kind of lazy so what I often do is use Object.assign for creating just about all the objects I need, but only after serializing the problem object with the JSON.parse JSON.stringify trick.

    Object.assign does work in MV and can be useful if you want to enumerate all the properties on an object quickly, but to make it not a copy...well...
    PHP:
    function MyTest() {
      
    this.initialize()
    }

    MyTest.prototype.initialize = function() {
      
    this.prop 3;
    };

    const 
    test1 = new MyTest();
    const 
    test1Clone Object.assign(new MyTest(), JSON.parse(JSON.stringify(test1))); //Breaks the link
    test1Clone.prop 5;
    console.log(test1test1Clone);
    Though I think you might be able to use type coercion and change the prototype. But this is cleaner and allows you to copy over the prototype methods.
     
    #7
  8. Mister.Right

    Mister.Right Veteran Veteran

    Messages:
    249
    Likes Received:
    83
    Not sure RMMV supports ES6 but ES5 block scope can only be done with function immediate since let is ES6's feature.
     
    #8
    Kino likes this.
  9. Kino

    Kino EIS Game Dev Veteran

    Messages:
    515
    Likes Received:
    672
    Location:
    United States
    First Language:
    English
    Primarily Uses:
    RMMV
    Let and const have support in RMMV but only if you use 'use strict'. The support is spotty though, but you do have generator functions, classes, template strings, and a couple of the new methods!!!
     
    #9
    Mister.Right and Jonforum like this.
  10. Jonforum

    Jonforum Veteran Veteran

    Messages:
    1,577
    Likes Received:
    1,353
    Location:
    Canada / Québec
    First Language:
    French
    Primarily Uses:
    RMMV
    ! I didn't know , thank you for the info
     
    #10
  11. Kino

    Kino EIS Game Dev Veteran

    Messages:
    515
    Likes Received:
    672
    Location:
    United States
    First Language:
    English
    Primarily Uses:
    RMMV
    #11
    Jonforum likes this.
  12. Jonforum

    Jonforum Veteran Veteran

    Messages:
    1,577
    Likes Received:
    1,353
    Location:
    Canada / Québec
    First Language:
    French
    Primarily Uses:
    RMMV
    Do you have an idea about the performance of switching to strick mode and allow es6 methods?
    Is there a gain or slight loss?
     
    #12
  13. Kino

    Kino EIS Game Dev Veteran

    Messages:
    515
    Likes Received:
    672
    Location:
    United States
    First Language:
    English
    Primarily Uses:
    RMMV
    In MV itself there might be some loss, but most browsers support es6 currently. I wouldn't use it without a transpiler in MV though. Furthermore, use strict forces you to write good code and should help JS optimize your code.

    I would only use the basic stuff like let, const, template literals to not introduce too many factors. Those make your life easy along with Object.assign
     
    #13
  14. Mister.Right

    Mister.Right Veteran Veteran

    Messages:
    249
    Likes Received:
    83
    Interesting, How will MV works with the browsers don't support ES6? It compiles down to ES5?
     
    #14
  15. Kino

    Kino EIS Game Dev Veteran

    Messages:
    515
    Likes Received:
    672
    Location:
    United States
    First Language:
    English
    Primarily Uses:
    RMMV
    In that case, I use BabelJS, but from the looks of it, a lot of browsers support es6 now. It was more of an issue a couple years ago. I think the only ones that aren't supported are certain versions of Opera (mobile version) and Internet Explorer, which was abandoned for Edge.
    Here's a nice site that shows you what browsers have the support: http://caniuse.com/#

    So, it really depends on how much ES6 you want to use. @Mister.Right
     
    #15
    LTN Games likes this.
  16. LTN Games

    LTN Games Veteran Veteran

    Messages:
    609
    Likes Received:
    459
    Location:
    Canada
    First Language:
    English
    Primarily Uses:
    RMMV
    Geez, yeah, web technology moves really quick and it's worth keeping an eye on these things because soon enough a bunch of libraries, frameworks like PIXI are going to be, or already are, written all in ES6. Almost all browsers support 98% of ES6, in fact, they're already starting to support ES2017 and beyond.
    I have been writing in ES6 for the last 7 or 8months, luckily BabelJS is what allowed me to do so and have all browsers including ancient ones to be compatible with my plugins. ES6 is the not really the future anymore it's more like today's standard and almost all new tutorials from late 2016 and up are written with ES6 and I would definitely urge everyone who has not already, to learn it. Kino does a great job with his tutorials by writing both ES6 and the ES5 counterpart, so you could start there for a basic overview.
     
    #16
    Kino likes this.
  17. Mister.Right

    Mister.Right Veteran Veteran

    Messages:
    249
    Likes Received:
    83
    Good thing to hear ES6 is becoming standard. ES5 prototype inheritance is the hard way. There still many enterprise/government projects reply on older browsers, even Angular 4 Typescript default compile to ES5.
     
    #17
    Kino likes this.
  18. Kino

    Kino EIS Game Dev Veteran

    Messages:
    515
    Likes Received:
    672
    Location:
    United States
    First Language:
    English
    Primarily Uses:
    RMMV
    You know, I'm secretly starting to love some of the power Typescript gives us along with what it does for documentation.
    http://prntscr.com/fyckwe <-- My next project.
     
    #18
  19. Mister.Right

    Mister.Right Veteran Veteran

    Messages:
    249
    Likes Received:
    83
    Not a fan of Typescript but it does make code easier to debug, read, in contrast, Javascript ES5 is a nightmare to work with, lacks many OOP features and flaws in design. I find only two things I like from JS are the dynamic typing and functional concept. If your background is C# or Java would take about 2 hours to learn Typescript. Typescript is cool but at the end of the day, it will be compiled to Javascript anyway.

    Interface, Static type, Access modifier are 3 main things JS don't have. Module is ES6 feature, Decorator is proposed for ES7.
     
    #19
    Kino likes this.
  20. Jonforum

    Jonforum Veteran Veteran

    Messages:
    1,577
    Likes Received:
    1,353
    Location:
    Canada / Québec
    First Language:
    French
    Primarily Uses:
    RMMV
    I discovered recently, this super tool that allows to convert TypeScript(.TS) into Javascript(.JS)
    http://www.typescriptlang.org/play/

    This is very useful for reading modules because most module are written in TS
     
    #20
    Kino likes this.

Share This Page