bo256
bo256

Reputation: 153

JavaScript - Why doesn't the addition assignment operator work as expected?

I'm currently enhancing a website with a few animations.

I tried this code:

// Opacity is 0 in the beginning. Set 
//  in CSS. 
// 1. Parameter: Boolean - true if making the
//  element visible; false if making it vanish.
// 2. Parameter: Object

var changeOpacity = function(direction, element) {
  var css = element.style;
  var goStep = function(signedStep) {
    css['opacity'] += signedStep;
    changeOpacity(direction, element);
  };

  if (direction) {
    if (css['opacity'] < 1.0) {
      setTimeout(function() {
        goStep(0.1);
      }, timeStep);
    }
  } else {
    if (css['opacity'] >= 0.1) {
      setTimeout(function() {
      goStep(-0.1);
  }, timeStep);
    } else {
      css['display'] = 'none';    
    }
  }
};

It haven't worked.

I wrote a few console.logs in the code: 'opacity' always stayed at 0.1 after the assignment.

What I expected was: 0.0 - 0.1 - 0.2 - 0.3 ...

Now I use this code:

// ...
var goStep = function(signedStep) {
  css['opacity'] = +css['opacity'] + signedStep;
  changeOpacity(direction, element);
};
// ...

Works fine. But I still wonder why using the combined assignment addition operator failed.

Has anyone an idea?

Upvotes: 0

Views: 332

Answers (2)

jolmos
jolmos

Reputation: 1575

You are adding string with Number, so in first case you are actually concatenating the values

See here: https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Addition_assignment

The second aproach works because you are converting css['opacity'] to a number: +css['opacity']

Try this:

    var test = "0.1",
    test2 = "0.1";
    signedStep = 0.1;

    test += signedStep;
    alert(test+" is a "+typeof test);
    test2 = +test2 + signedStep;
    alert(test2+" is a "+typeof test2);

Upvotes: 1

Guillaume Badi
Guillaume Badi

Reputation: 749

css['opacity'] is a string. If you add a number to a string, it will convert the number into a string and concat the two final strings.

css['opactity'] = 0.1
css['opacity'] += 0.5 // => "0.10.5"

Upvotes: 0

Related Questions