The modern web is ever-changing and JavaScript is the number one programming language in the world, the language of the web, of mobile apps, of the server side and has many other implementations.
In this article, I’ll try to share some of JavaScript Secrets : Tips and Tricks I normally use, hope it help others too!
Using var for creating variables doesn’t result in global variables. Avoid global variables, they sometimes create issues, unless required.
Yes, you heard that right! Semicolons aren’t required due to the nature of JavaScript’s automatic semicolon insertion, but they’ve been been considered a best practice for years.
The == /!= operator performs an automatic type conversion, if needed. The === /!== operator will not perform any conversion!
alert('' == '0'); //false
alert(0 == ''); // true
alert(0 =='0'); // true
== is not transitive. If you use === it would give false for all of these statements as expected.
The || operator first evaluates the expression on the left, if it is truthy, it returns that value. If it is falsy, it evaluates and returns the value of the right operand (the expression on the right).
You can also use the logical or operator || in an assignment expression to provide a default value :
var a = b || c;
The a variable will get the value of c only if b is falsy (if is null, false, undefined, 0, empty string, or NaN), otherwise a will get the value of b.
The && operator first evaluates the expression on the left. If it is falsy, false is returned; it does not bother to evaluate the right operand.
var x = 1;
var y = 3;
var list = {0:0, 1:0, 2:0};
x in list; //true
y in list; //false
1 in list; //true
y in {3:0, 4:0, 5:0}; //true
function sum() {
var foo = 0;
for (var i = 0, len = arguments.length; i < len; ++i) {
foo += arguments[i];
}
return foo;
}
sum(0, 1, 2) // returns 3
This statement allows you to put breakpoints programmatically in your code just by:
// ...
debugger;
// ...
If a debugger is present or active, it will cause it to break immediately, right on that line. Otherwise, if the debugger is not present or active this statement has no observable effect.
Thanks for reading. These are some of the tricks, I usually use, hope it helps you!
You can follow me on Twitter, and checkout my experiences at www.srijanagarwal.me!