Last Updated: January 13, 2019
·
1.271K
· patrickrbc

Javascript Curiosities

JavaScript is undoubtedly the most important language on the web. However some people don't take it seriously and don't look for learning it right.

Yes, JavaScript has a lot of quirky parts that make things complicated sometimes, but it's not the end of the world. In this post I will try to expose some minor details, common mistakes and tricks of this wonderful language.

The type attribute in script tag

You should have seen something like this
<script type="text/javascript"></script>
or this
<script type="application/javascript"></script>

Although it's very common to find it, it's unecessary. In the second case it's actually wrong and it will block your script in older browsers.
The first one probably won't be a problem, but there's no reason to use. The default programming language in all browsers is JavaScript.
If you want to validate your code maybe it will be required. But again, there's no reason.

Casting

In JavaScript most beginners learn type conversion with standard objects String, Number, Boolean.
However there is an easier way using operands.

'' + 1     // turns to string '1'
+'1'       // turns to number 1
!!'1'      // turns to boolean true

Conditional Operators

JavaScript programmers are bold in their way to write code, if you look at some open source projects you will come face to face with some things like this

condition ? true : false; // ternary operator

// which is equivalent to
if ( condition ) {
    return true;
} else {
    return false;
}

Simple, isn't it? Although this operator can be nested like in this piece of code from jQuery source.

return operator === "=" ? result === check :
    operator === "!="javascript ? result !== check :
    operator === "^=" ? check && result.indexOf(javascript check ) === 0 :
    operator === "*=" ? check && result.indexOf( checkk ) > -1 :
    operator === "$=" ? check && result.slice( -check.length ) === check :
    operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
    operator === "|=" ? result === check || result.sliceice( 0, check.length + 1 ) === check + "-" :
    false;

This is just a couple of if/elses statements, if none of the conditions are true this will return false.
Another situationt that I found was like this

return mustBeTrue && otherThruth && oneMore && 'All the conditions are true';

This is useful when you want to check values quickly.

Profiling

You can make benchmarks with your functions to know what's taking more time to run, you could do this with Developer Tools, but here is another way :)

console.time('medium-loop');
for(var i = 0; i < Math.pow(10,5); i++);
console.timeEnd('medium-loop');

console.time('big-loop');
for(var i = Math.pow(10,8); i > 0; i--);
console.timeEnd('big-loop');
// medium-loop: 2ms
// big-loop: 104ms