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.

1
  • 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. Commented Apr 25, 2017 at 13:57

3 Answers 3

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?

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

4 Comments

It's webpack, not React.
I think it's the linter that comes bundled with create-react-app. It's not necessarily webpack.
@Andrei, webpack is what specifies eslint as a preloader before babel runs. Code is here. github.com/facebookincubator/create-react-app/blob/v0.9.5/…
Of course: the error is triggered by eslint loader IN webpack, but not BY webpack alone. That's what I meant. Sorry if I wasn't clear enough.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.