Loading ...
If tutorials available on this website are helpful for you, please whitelist this website in your ad blocker😭 or Donate to help us ❤️ pay for the web hosting to keep the website running.
js comma (,) Operator
JavaScript में comma (,) operator अपने प्रत्येक operand(बाएं से दाएं) को evaluate करता है और last operand को return
करता है।
for example
let x = 1;
x = (x++, x);
console.log(x);
// now use values directly.
x = (2, 3);
console.log(x);
2 3
Description :
Example में अगर आप देखेंगे तो पहले x
की value को 1 से increment किया गया है और , जैसा कि अभी आपने पढ़ा कि comma operator हमेशा last operand return करता है।
अब चूंकि x
की value increase हो गयी है इसलिए output में आपको 2
मिला।
ठीक इसी तरह से जब number को directly use किया गया तो last value output में मिली।
हालाँकि जरूरी नहीं है कि आप 2 ही variables / values use में लें , आप अपनी need के according multiple variables / values को use में ले सकते हैं but , output में हमेशा last value ही मिलेगी।
for example
let x = 1;
x = (x++, x++, x++, x++, x++, x);
console.log(x); // 6
comma operator को आप वहां पर use में ले सकते हैं जहाँ पर आपको किसी single statement में multiple expressions की जरूरत हो। किसी for loop में multiple updaters supply करने के लिए आप इसका use कर सकते हैं।
see below example
// function to get random numbers.
function num() {
return Math.floor(Math.random() * 100);
}
// create 10×10 array of random numbers
const arr = Array.from({ length: 10 }, () =>
Array.from({ length: 10 }, num),
);
// now iterate using comma operator.
for (let i = 0, j = 9; i <= 9; i++, j--) {
console.log(`arr[${i}][${j}] = ${arr[i][j]}`);
}
Output
arr[0][9] = 43 arr[1][8] = 10 arr[2][7] = 62 arr[3][6] = 74 arr[4][5] = 84 arr[5][4] = 34 arr[6][3] = 64 arr[7][2] = 17 arr[8][1] = 89 arr[9][0] = 46
Comma operator का use आप multiple assignment expressions में भी कर सकते हैं।
let a, b, c, res;
res = (a = b = 3, c = 4);
console.log(`a : ${a}`);
console.log(`b : ${b}`);
console.log(`c : ${c}`);
console.log(`res : ${res}`);
output
a : 3 b : 3 c : 4 res : 4
example में , a = b = 3
expression में पहले 3 , b को assign फिर b , a को जिसका मतलब है कि a
और b
दोनों में same value है , लेकिन जैसा कि आपने ऊपर पढ़ा कि comma operator में last operand ही return होगा इसलिए , उससे पहले के सभी expression evaluate होने के बाद res
में 4 मिला।
आपको JavaScript में comma operator के बारे में समझ आ गया होगा।
0.
Loading ...
Hi ! My name is Rahul Kumar Rajput. I'm a back end web developer and founder of learnhindituts.com. I live in Uttar Pradesh (UP), India and I love to talk about programming as well as writing technical tutorials and tips that can help to others.
Get connected with me. :) LinkedIn Twitter Instagram Facebook