Finding javascript seemingly easy should i slow down?

im finding javascript seemingly easy to learn since i already know a lot of programming concepts from python. is this normal or should i slow down?

1 Like

I don’t know, I started learning JS and now I am pursuing Python. JS can be very, very nasty…

i see i am probably not far enough into it then x.x

although to be fair if javascript was your first language i can see why you said that. i would have said python was very difficult when i first started it

most of the stuff i learned from python is just converting over to javascript with some minor differences

as long as i am able to make those typical to do list apps and calculator apps i would say i know enough javascript but i do not know if it is enough for a first job. i am mainly specialising in django anyway so i am assuming it would be the least expected of me

There is no switch instruction in Python? How can I use Python if I don’t have a switch method in it? JS has switch? Why isn’t this available in Python? Argh… I must use a dictionary in Python to do something as simple as a switch… Gimme a break! Oh well! JS is very nasty… I hate/love JS…

BTW, my first language was MSBASIC, then Pascal, then Fortran 77, then… By that time, of course, I didn’t properly learn how to code and it was all half-assed…

I started learning to code when I started using R (But then again, R let’s you do nasty, nasty things… It is very easy to fool yourself while using R) and became sort of proficient in R… JS was an accident for me but I started liking it and using it despite it being even nastier than R in my humble opinion but I had some reasons for studying it:

  1. JS appears consistently in the top five in many rankings: From DistantJob most of the rankings are shown.

  1. JS is everywhere… Sure, if you want to do more with JS perhaps it is required to study HTML and CSS as well.
  2. I am just curious about the paradigms in JS.

Of course, Python is also everywhere and that’s the second language I am trying to learn (one never ends learning.) In the rankings image I am sharing Python is also the boss. But Python is, per people that knows about the subject, slow.

What will be next for me? Julia…

1 Like

I will check it out @camperextraordinaire Thanks!

Apparently there are people out there who don’t like switch and consider it a code smell. You can find a lot of articles arguing against its use.

True story. I have been contributing to the FCC code base for quite a while now. Early on when I first started, I used a switch in one of my PRs and was told to change it to and given a link to this article. So if you plan on contributing to FCC then forget about the switch :slightly_smiling_face:

1 Like

Please! Run away from the JS spell! :laughing: I am actually enjoying Python a lot and I am about to complete a project from FCC. For instance today I needed to create a dictionary for the days of the week and to be able to get thevalue (day) given the key and to get the key given the value. I googled this and adapted it to my needs from How to Extract Key from Python Dictionary using Value:

Days_of_Week = { 
    
    0: "Monday", 
    1: "Tuesday", 
    2: "Wednesday", 
    3: "Thursday", 
    4: "Friday", 
    5: "Saturday", 
    6: "Sunday"
    
}

key_list=list(Days_of_Week.keys())
val_list=list(Days_of_Week.values())
ind=val_list.index("Sunday")
print(key_list[ind])

Pretty cool, huh? Indeed, this very same routione with a dictionary can be used instead of a switch.

What is this… There’s no data in the article to back up any of the claims about performance… I would imagine the memory cost of creating objects and nested function calls to perform worse.

Personally, I think switch is great. Though I do wish we had match in JS.


Anyway, here’s my cool utility function ternFn that is super fast because it’s not procedural.

function ternFn(condition, whenTrue, whenFalse) {
  const key = String(Boolean(condition));
  return {
    "true": whenTrue,
    "false": whenFalse,
  }[key];
}

(this is satire)

1 Like

I have to jump on this switch vs object lookup because this is absolutely true! They were absolutely correct to have you switch it up. :rofl:

Switch statements are, far more often than not, slower than an object lookup. On a single iteration, about 9 times out of 10, the switch will underperform compared to the object lookup. But, in cases of multiple iterations, an object lookup far outperforms the switch 19 times out of 20.

If you’re not running the switch statement in a for loop that’s executed thousands of times, there will be no difference to the end user whether you used a switch, object lookup, if-else if, etc. But, I do find that object lookups come in handy when your web app is data driven, because you aren’t locked into a static set of cases to choose from.

Here is a test case that I ran about 20 times and can show the massive performance difference between switch and object lookup. And if you notice, I’m even assigning a variable in every iteration of the object lookup, and it still outperforms the switch statement. We are talking often times double the performance from the object lookup compared to the switch.

I saved this so that I could run it multiple times easily by using the “Snippets” section under the “Sources” tab in Chrome’s Developer Tools:

!function () {
    const startTime = performance.now();
    
    const word = 'apple';

    for (let i = 0; i < 10000; i++) {
        switch (word) {
            case 'banana':
                //do nothing
                break;
            case 'mango':
                //do nothing
                break;
            case 'apple':
                //do nothing
                break;
        }
    }

    console.log('time to execute switch in ms', performance.now() - startTime);
}()

!function () {
    const startTime = performance.now();
    
    const word = 'apple';

    const objectLookup = {
        banana: 'banana',
        mango: 'mango',
        apple: 'apple'
    }

    for (let i = 0; i < 10000; i++) {
        const myLookup = objectLookup[word];
    }

    console.log('time to execute object lookup in ms', performance.now() - startTime);
}()

I would be very careful this sort of ad hoc benchmarking.

You don’t have any guarantees about what sorts of optimizations may be occuring by the engine during JiT for this code.

Getting proper microbenchmarks is really hard.

Tragically, since JS lacks fully functional enums, this discussion misses how switches are used in other languages. They help you make sure every relevant case is covered.

And TypeScript doesn’t even get this right :cry:
It is tragic.

1 Like

Well, like I said in the 3rd paragraph, when it comes to JS switch statements or object lookups or long and tedious “if-else if” blocks, the end user is not going to care what you used because they won’t notice a difference in performance. And I love switches! They are handy and efficient and can cover all necessary blocks.

But, if you run the benchmarks for long enough (and even care to), the object lookup methodology wins out 99% of the time lol

Your benchmark is flawed though.

To get a proper microbenchmark, you need to make the repeated code inside of the loop opaque to the control flow of the loop. Otherwise you are testing how well the engine is filtering out meaningless loop iterations.

If anything, the switch for loop has the advantage because there isn’t the need for fresh memory allocation each time the loop is ran in the switch for loop as compared to the object lookup for loop in my benchmark.

And do you have a source where it mentions the JS compiler filters out meaningless loop iterations? I’m genuinely curious because I want to read more about that.

Every engine is free to make whatever optimizations it wants to so long as the end behavior matches the spec. There is no guarantee as to what optimizations your engine is doing.

I’d really more focus on benchmarks in context. It doesn’t matter if a switch or object lookup is better in theory. It matters if there is any meaningful difference in your code.

Well, I can tell you that the JS compiler absolutely does not filter out “meaningless” loop iterations. There are optimizations happening behind the scenes, but the JIT compiler for JavaScript is still going to execute each one of those loops the same amount of iterations.

If that were true, I wouldn’t be able to crash a page by simply putting:

for (;;) {
  console.log('hehehe');
}

The JS compiler in the browser should see that as being a completely useless loop that is obviously going to crash the page, except for the fact that it’s not on the compilter to ensure that the developer didn’t do something as incomprehensibly stupid as that.

And we are talking specifically about JavaScript, so my benchmarks still hold their water. And again, I agreed with you twice now about the usefulness of switch statements, but I started talking specifically about performance of switch vs object lookup. You seem very intent on arguing.

So, I will say good night from my side of the world, and thank you for coming to this TED talk.

For certain? On every single JS engine ever? I’m not sure. Optimizating out loop bodies that have a non-op is a pretty common compiler optimization, so I’d expect at least one JS JiT compiler can do it.

I don’t think this is necessarily true or guaranteed to be true in the future.

This loop actually takes an action. It’s body isn’t meaningless in terms of computational activity occuring.

Benchmarking, and microbenchmarking in particular, is hard to get right. A simple loop with a timer can be very misleading, unfortunately. That’s why there are many different packages dedicated to benchmarking.

I can see the question of ‘faster’ depending upon usage very much here.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.