loverajoel / jstips Goto Github PK
View Code? Open in Web Editor NEWThis is about useful JS tips!
Home Page: http://jstips.co
License: GNU General Public License v3.0
This is about useful JS tips!
Home Page: http://jstips.co
License: GNU General Public License v3.0
Hey,
I highly suggest you read these:
http://mrale.ph/blog/2014/02/23/the-black-cat-of-microbenchmarks.html
http://mrale.ph/blog/2012/12/15/microbenchmarks-fairy-tale.html
http://jsperf.com/string-concat-fast/9#comment-1
Most of those microbenchmarks are illusions, I suggest you shift from those performance tips killing code readability to some actually useful tips, I really like the idea of repository 👍, but not like this.
To my understanding, this microbenchmark is an illusion:
var arr = [1,2,3,4,5];
arr.unshift(0);
[0].concat(arr); // 98% faster in Chrome 47.0.2526.106 on Mac OS X 10.11.1
Why? because [0].concat(arr)
is generating a new array which is not used, so the VM doesn't run it at all! That's why it's 98 percent faster, because it's not running anything. Most probably if you are using this in some real-life example, they run at the same speed.
JavaScript engines are too smart to require us to use such tricks in order to make them run fast, these tricks just making our code hard to understand.
Thank for the tips.
We can also use this trick to do a safe string concatenation :
var one = 1;
var two = 2;
var three = '3';
var result = '' + one + two + three; // "123"
it's less verbose and faster !
Worth noting that Strict Mode is always on on ES6/ES2015 modules.
We don't need to add "use strict" for ES6/2015 modules.
"undefined means a variable has not been declared"
A variable that has not been declared doesn't exists, so this statement is contradictory.
Hence, if you reference a variable that is not declared, it's value is not undefined as a reference error is thrown instead. (If you talk about referencing a non existing property of an object, that shouldn't be called a variable).
Is Pseudomentatory even a word? What does this mean?
I think the author meant pseudo-mandatory parameters?
!!value
converts value
to a Boolean
. This much is true.
It's also arguably "too clever" and a source of confusion to inexperienced JS programmers--it's in the same category as using ~
with Array.prototype.indexOf()
.
An alternative which I have found to be much more obvious (though perhaps too verbose for some) is instead using Boolean(value)
, which does the same.
Just wanted to start a conversation around this. I think this project is a good idea, but it's my hope the tips will show great ways to solve problems instead of just ways to solve problems in the fewest amount of characters.
I was thinking that it would be cool to add a section about the upcoming/transpiled stuff that can be used with the new es6/7 drafts. For example http://blog.jeremyfairbank.com/javascript/javascript-es7-function-bind-syntax/ has some stuff that would be nice for the very first tip
const { map, filter } = Array.prototype;
nodeList::map( node => node.xxx )
When giving (especially performance-related) tips, any GC-related implications should be noted. For example, the sample tip in the readme shows a "faster" arr.unshift()
by concatenating arrays. If this operation is performed very often, the GC will be collecting a bunch of temporary arrays that are immediately discarded.
I tried (and failed) to set up an index/toc. I couldn't get the link from my toc to link to the id of the tip. This would be a good feature.
I am watching the repo, which means I get all issues, comments, and PRs. I'd like to just follow the tips themselves, is there any way (without Twitter)?
Any Security Issue and Solution?
In tip https://github.com/loverajoel/jstips/blob/master/README.md#21---shuffle-an-array, the alternate shuffle function by @mvedie ( which I really like, btw) appears to assume that shuffle
is defined on the Array.prototype
as it contains a slice()
method on this
, rather than on an array
parameter ~ but that throws an error:
function shuffle() {
return this.slice(0).sort(function() {
return 0.5 - Math.random();
});
};
shuffle([1,2,3,3,4,5,6]);
// TypeError: this.slice is not a function
Fix that by specifying array
as a parameter, and calling slice()
on that instead:
function shuffle(array) {
return array.slice().sort(function() {
return 0.5 - Math.random();
});
};
shuffle([1,2,3,3,4,5,6]);
// (e.g.) [3, 1, 2, 3, 5, 4, 6]
the (cache[n]=cache[n-1]+cache[n-2]) part can't work, because the values arent't computed first if you don't call the function for every number smaller than the one you want.
this works:
var fibonacci = (function(){
var cache = {
0: 0,
1: 1
};
return function(n){
return n <= 1 ? cache[n] : (cache[n] = (cache[n-1] || fibonacci(n-1) + cache[n-2] || fibonacci(n-2)));
}
})();
mistake?
I have issued a PR #100 that will help to start the formation of a repo that can continue to increase as the tips come in overt the year. My proposal has it where there is a 2016 directory with a README that has a link to each month for the year, and then a directory for each month inside of that directory that has a README for the tips of that month. This will help to keep the README to a minimum for just that month.
Most correct and semantic way:
- if (!module.parent) {
+ if (require.main === module) {
// ran with `node something.js`
app.listen(8088, function() {
console.log('app listening on port 8088');
})
} else {
// used with `require('/.something.js')`
module.exports = app;
}
Since the README.md starts getting longer it would be nice to split the tips into several files, and has only a list of titles on the README.md with links to the tip's md file. It will make the reading easier and also people will have less conflicts since the will work in different files and not on the README.
made a quick jsperf...
In this test, it looks like Math.floor is faster.
On Chrome 48.0.2540.0 32-bit on Windows NT 10.0 64-bit
, concat
looks much faster than join
.
I know of several different ways to show loading images during Ajax calls, but would like to know the method most preferred for maintainability and performance.
Firefox 43.0.4 on Mac
Hi. This project is going to be really big. So, I've been thinking about categories. What if tips will be divided by categories like:
Plain JS
ES2015
Angular JS
React JS
etc..
It will be easier to find tips for your needs.
@loverajoel What do you think?
Array.from()
I propose use of the ISO 8601 Date format (e.g. 2016-01-03 for January 3rd, 2016)
https://en.wikipedia.org/wiki/ISO_8601
Exhibit A, https://github.com/loverajoel/jstips/blob/cc8584a7f5812ac7d34f483c9269f846dad35169/README.md
#03 - Improve Nested Conditionals
01/03/2016 by AlbertoFuente
Exhibit B, https://github.com/loverajoel/jstips/blob/cc8584a7f5812ac7d34f483c9269f846dad35169/README.md
#02 - ReactJs - Keys in children components are important
02/01/2016 by @loverajoel
I could not find proper minify compliers for JS minify? Can any one suggest?
The stakes at risk if you inaccurately explain the => behavior for this are that you end up thinking things like, “arrow functions are just syntax sugar for function…” They clearly are not. Nor are they sugar for var self = this or .bind(this).
var arr = [1,2,3,4,5];
arr.push(6);
arr[arr.length] = 6; // 43% faster in Chrome 47.0.2526.106 on Mac OS X 10.11.1
Why not use concat here as well?
arr.concat(6);
@loverajoel Either I'm entirely missing something or this first example doesn't do anything:
https://github.com/loverajoel/jstips/blob/gh-pages/_posts/en/2016-01-29-speed-up-recursive-functions-with-memoization.md
var fibonacci = (function(){
var cache = {
0: 0,
1: 1
};
return function(n){
return n <= 1 ? cache[n] : (cache[n] = cache[n-1] + cache[n-2]);
}
})()
I think what this might be going for is something like this?
var fibonacci = (function() {
cache = {
'0': 0,
'1': 1
};
function f(n) {
var result;
if (n in cache) {
result = cache[n];
} else {
result = f(n - 2) + f(n - 1);
cache[n] = result;
}
return result;
}
return f;
})();
偶尔从论坛上发现了这个项目,每天早晨上班之前看一看,今天怎么没有更新?
I found this project from the forum by accident and always look through it before going to work every morning,but why doesn't it update as usual today?
In example you have this object
var myObject = {
name: '@tips_js'
};
and this check
if (typeof myObject['name'] !== 'undefined') { ... }
and then these words saying that that kind of check is ok.
Thats ok, but you have to know that there are two native methods for this kind of thing
Actually it is not ok, consider this example:
var myObject = {
name: '@tips_js'
}
console.log(typeof myObject['name'] === 'undefined') // false
myObject.name = undefined
console.log(typeof myObject['name'] === 'undefined') // true
Which clearly shows that typeof myObject['name'] === 'undefined'
is not checking existence of property, but checks type of that property value
## Tip 99
balabala...
...
## Tip 02
balabala...
## Tip 01
balabala...
Otherwise, we may have to scroll to the end of the page in order to find the latest tip.
Tip #6 suggests that it's code returns the first letter capital rather than the whole word.
printUpperCase("cactus");
// => Cactus
Ideally, if the end result wanted to look like that, the code should reflect something like this:
function printUpperCase(words) {
var elements = [].concat(words);
for (var i = 0; i < elements.length; i++) {
var tmpArr = elements[i].split(''),
retVal = tmpArr.shift().toUpperCase() + tmpArr.join('');
console.log(retVal);
}
}
Just wanted to assist! Thanks!
-Chris
The question of the tip is formatted as follows:
How can we improve and make more efficient nested if statement in javascript.
if (color) { if (color === 'black') { printBlackBackground(); } else if (color === 'red') { printRedBackground(); } else if (color === 'blue') { printBlueBackground(); } else if (color === 'green') { printGreenBackground(); } else { printYellowBackground(); } }
With the given information (the if-clause and the function names), the most obvious choice would be just to refactor the functions itself
printBackground(color);
/**/
function printBackground(color = "yellow") {
// do something with the color, default being yellow
}
which is a good tip in itself, but maybe not in the same vain the original #3 is. Obviously this isn't always possible (or feasible) with all of the cases, so the example could be / should be easily modified to something that looks more non-trivial 😸
How about keep one tip per file instead one page for all ?
In the future can do view tips like tldr ? can generate the one page tips with each tip .
In addition to Twitter, it would be nice to receive a tip in a daily email.
Would be nice to play with tip's code to grasp the topic better, wouldn't it?
This repository is not really suited for pull requests: there is only one file to edit and we don't exactly know how. Why not use forms to let people post their tips, then select one every day?
I am talking about the algorithm about the following algorithm by @mvedie:
function shuffle(array) {
return array.slice(0).sort(function() {
return 0.5 - Math.random();
});
};
Information why this algorithm does not work (and shouldn't be used) can be found for example in this awesome blog post and by googling a bit.
I'm therefore proposing to remove the corresponding section from the tip.
it's not declarative, but still curious about the performance
var arr = [1,2,3,4,5];
// add element at the end
arr.splice(arr.length, 0, 6);
// add element at the beginning
arr.splice(0, 0, 6);
Would it be worth it to add Disqus for being able to comment on the tips? I had some issues with the Fibonnaci examples, and if there was a way to comment for feedback, that would be great.
👍
There are many JS developers in China, and I, a tech discussion/sharing community host, want to help translate this great series of tips to a Chinese version.
Do we have any official guidelines for this?
var debug = function(){console.log(arguments);};
Model 1:
function class1(){
this.name="github1";
}
obj1 = new class1();
debug(obj1.name);
Model 2:
var class2 = function(){
this.name= "github2";
}
obj2 = new class2();
debug(obj2.name);
Model 3:
function class3(){
var _this = this;
_this.name="github3";
}
obj3 = new class3();
debug(obj3.name);
Model 4:
var class4 = function (){
var _this = this;
_this.name="github4";
}
obj4 = new class4();
debug(obj4.name);
Please update if you feel any other format?
Make sure, If you prefer using prototype Why?
thnx.
For example, this line:
console.log(~~1.999); // 1
Rounding 1.999 should give 2, not 1. 1 is either flooring or truncating. And as the example shows that negative values are like Math.ceil
, it means ~~
is only truncating.
Also, on another note, truncating could be done using parseInt
, which is the cleaner way I think.
Hey, thanks for making this awesome project! I'm wondering if framework specific tips should be included? Including these might make more difficult for beginners to understand, not to mention harder to maintain, since frameworks update, get rewritten, and become anti-patterns rather quickly.
Alternatively, allowing only vanilla javascript content will better serve beginners looking to understand language fundamentals, while promoting a better understanding of the language that so many frameworks and libraries depend on.
Maybe better to
value = [].concat(value || [])
For the sake of clarity, I'd recommend to the verbose semantic:
Array.prototype.slice.call(nodelist);
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.