Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment a value in a JavaScript object?

Tags:

javascript

var map = {}; map[key] = value; 

How can I

  • assign value 1 if key does not yet exist in the object
  • increment the value by 1 if it exists

Could I do better than:

if (map[key] == null) map[key] = 0; map[key] = map[key]++; 
like image 966
membersound Avatar asked Sep 20 '16 09:09

membersound


People also ask

How can I increment the value of a variable in JavaScript?

JavaScript has an even more succinct syntax to increment a number by 1. The increment operator ( ++ ) increments its operand by 1 ; that is, it adds 1 to the existing value. There's a corresponding decrement operator ( -- ) that decrements a variable's value by 1 . That is, it subtracts 1 from the value.

What is i ++ in JS?

The value i++ is the value of i before the increment. The value of ++i is the value of i after the increment. Example: var i = 42; alert(i++); // shows 42 alert(i); // shows 43 i = 42; alert(++i); // shows 43 alert(i); // shows 43. The i-- and --i operators works the same way.

How does ++ work in JavaScript?

Description. If used postfix, with operator after operand (for example, x++ ), the increment operator increments and returns the value before incrementing. If used prefix, with operator before operand (for example, ++x ), the increment operator increments and returns the value after incrementing.

How do you increment a value in Java?

If we use the "++" operator as a prefix like ++varOne; , the value of varOne is incremented by one before the value of varOne is returned. If we use ++ operator as postfix like varOne++; , the original value of varOne is returned before varOne is incremented by one.


2 Answers

Here you go minimize your code.

map[key] = (map[key]+1) || 1 ; 
like image 181
ricky Avatar answered Sep 20 '22 22:09

ricky


Recently it could be

map[key] = (map[key] ?? 0) + 1; 

Nullish coalescing operator

like image 25
kawauso Avatar answered Sep 21 '22 22:09

kawauso