Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why foo() output 2 in react-native, but Chrome console output 3?

foo(x, y = function() { x = 2; }) {
    var x = 3;
    y();
    console.warn(x);
}

foo();

Why foo() output 2 in react-native, but Chrome console output 3?

like image 297
Yan Avatar asked Feb 02 '26 01:02

Yan


2 Answers

React-Native, by default, compiles code to ES2015 so the code actually runs should be similar to:

function foo(x) {
  var y = arguments.length > 1 && arguments[1] || function() {
    x = 2;
  }
  var x = 3;
  y();
  console.warn(x);
}

So when you run y() the x referenced is the x declared with var x = 3;. In Chrome console that actually supports default arguments, x references the variable in the arguments. See the code below:

function foo(x, y=function() { console.warn(x); x = 2; }) {
  var x = 3;
  y();
  console.warn(x);
}

When you run foo(5) you'll see:

5
3
like image 148
Lucas Avatar answered Feb 03 '26 18:02

Lucas


The reasion is @Lucas answered. ES2015 can not support default args. react native compiles code to ES2015.

foo(x, y=function() { console.warn(z); x = 2; z = 3}) {
  var x = 3;
  y();
  console.warn(x);
}

So, foo(5) show "Can't find variable:z".

Chrome can support default args.

 function foo(x, y=function() { console.warn(z); x = 2; z = 3 }) {
  var x = 3;
  y();
  console.warn(x);
}

foo(5), you'll see:

3
3
like image 37
Yan Avatar answered Feb 03 '26 17:02

Yan