0

I try this example given below for looping using for loop in normal js file and in reactjs.

for(var a=[i=0];++i<20;a[i]=i);

when i run this code in react it shows

'i' is not defined

import React, { Component } from 'react';
import './App.css';
export default class Board extends Component
{

    move (e)
    {
        for(var a=[i=0];++i<20;a[i]=i);
        console.log(a)
    }
    render () {
        return (
            <div className="boxes" onClick={this.move.bind(this)}></div>
        );
    }
}

enter image description here

when i run it in the normal js file it works fine.any ideas why it happens in reactjs.

Uwe Keim
  • 38,279
  • 56
  • 171
  • 280
vijay
  • 204
  • 1
  • 13
  • 4
    It's not React doing anything, it seems Webpack doesn't like that way of writing code. Which is good since that kind of code shouldn't be written anyway as it is very unclear to read. – Sami Kuhmonen Apr 25 '17 at 13:57

3 Answers3

1

Your bundled code has 'strict mode' at the top of the file. Strict mode will throw an error if an undeclared variale is used.

Kyle Richardson
  • 5,331
  • 2
  • 16
  • 39
1

It's because your React application is using strict mode:

"use strict";

for(var a=[i=0];++i<20;a[i]=i);

If you don't want to disable strict mode, you can get around this issue by simply declaring the i variable beforehand:

"use strict";

var i;
for(var a=[i=0];++i<20;a[i]=i);

However the software you're using to bundle your application most likely supports minifying the files for you anyway, so I'm not sure what benefit you'd get from minifying them yourself. If you're using Webpack, for instance, you can refer to this question: How to build minified and uncompressed bundle with webpack?

Community
  • 1
  • 1
James Donnelly
  • 122,518
  • 33
  • 200
  • 204
0

Webpack is transpiling your code and does not allow variables to be used without being declared. Javascript on its own will allow the use of undefined variables.

Todd Chaffee
  • 6,616
  • 30
  • 41