Tuesday 18 July 2017

node js underscore tutorial with examples

node js underscore tutorial with examples

Question: How to install underscore in nodeJS?
npm install underscore





Question: How to include underscore in nodeJS?
var _ = require('underscore');





Question: What is map in underscore? How to use? Give example?
Produces a new array of values by mapping each value in list through a function. The iterates is passed three arguments: the value, then the index (or key) of the iteration, and reference.


console.log(_.map([1, 2, 3], function(num){ return num * 2; })); //2, 4, 6
console.log(_.map([1, 2, 3], function(num){ return num * 3; })); //3,6,9



Question: Give an example of underscore.each?
console.log(_.each([1, 2, 3], function(value, key){
     console.log(key+'>>'+value)
 }));



Question: Give an example of underscore.reduce?
console.log(_.each([1, 2, 3], function(value, key){
     console.log(key+'>>'+value)
 }));



Question: Give an example of underscore.reduce?
console.log(_.each([1, 2, 3], function(value, key){
     console.log(key+'>>'+value)
 }));



Question: How to check if variable is empty OR Not?
_.isEmpty({});//true
_.isEmpty({'1'});//false



Question: How to create range values?
_.range(6);//[1,2,3,4,5,6]



Question: Can we use underscore for Web Client?
Yes, for this you need to include following JS.
https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js



Question: What are collections available in underscore?
each
map
reduce
reduceRight
find
filter
where
findWhere
reject
every
some
contains
invoke
pluck
max
min
sortBy
groupBy
indexBy
countBy
shuffle
sample
toArray
size
partition



Question: What are array are available in underscore?
first
initial
last
rest
compact
flatten
without
union
intersection
difference
uniq
zip
unzip
object
indexOf
lastIndexOf
sortedIndex
findIndex
findLastIndex
range



Question: What functions are available in underscore?
bind
bindAll
partial
memoize
delay
defer
throttle
debounce
once
after
before
wrap
negate
compose