what is += in js code example

Example 1: what does += mean in JavaScript

/* JavaScript shorthand +=
+= is shorthand to add something to a
variable and store the result as that same variable.
*/

// The standard syntax:
var myVar = 2; 
console.log(myVar) // 2
var myVar = myVar + 3;
console.log(myVar) // 5

// The shorthand:
var myVar = 2;
console.log(myVar) // 2
var myVar += 3;
console.log(myVar) // 5

/* In JavaScript, += can also concatenate strings */

// The standard syntax:
var myName = "Hi, I'm" 
console.log(myName) // Hi, I'm
var myName = myName + " Joe."
console.log(myName) // Hi, I'm Joe.

// The shorthand:
var myName = "Hi, I'm" 
console.log(myName) // Hi, I'm
var myName += " Joe."
console.log(myName) // Hi, I'm Joe.

Example 2: javascript ... operator

//The operator ... is part of the array destructuring.
//It's used to extract info from arrays to single variables.
//The operator ... means "the rest of the array".
var [head, ...tail] = ["Hello", "I" , "am", "Sarah"];
console.log(head);//"Hello"
console.log(tail);//["I", "am", "Sarah"]

//It can be used to pass an array as a list of function arguments
let a = [2,3,4];
Math.max(a) //--> NaN
Math.max(...a) //--> 4

Tags:

Cpp Example