Correct format structure creating variables

Can I create vars

with spaces and slashes?

Same:

var PICKUPS / TRUCKS = {};

      

+3


source to share


4 answers


No, variable names cannot have spaces , but some special characters are allowed.

To refer to the list of allowed characters, you can refer to this answer .

In your case, this is not valid in Javascript:

// INVALID!
var PICKUPS / TRUCKS = {};

      

First, the operator /

is this divide operator

, so the Javascript interpreter will treat it as a mathematical operation, trying to "split PICKUPS with TRUCKS", which will throw an error, especially after the var

keyword, it won't know how to figure it out (for example, it will first see that you are trying to create a variable and then it will see that instead of creating a variable, you are trying to do some math that will confuse the javascript interpreter).



But you can do something like this:

// Valid Javascript; No spaces or illegal characters
var pickups_trucks = {};

      


Also, if names are embedded in javascript objects , you can name the objects using string identifiers, where any legal string can work:

var Automobiles = {
    "Trucks & Pickups": [],
    "Three Wheelers": []
};

console.log(Automobiles["Trucks & Pickups"]);

      

Hope it helps!

+4


source


No, this name is NOT VALID in javascript. It cannot contain spaces or slashes.



Here https://mothereff.in/js-variables you can check if variable name is correct or not

+2


source


This is invalid javascript.

I recommend that you specify variables separately:

var PICKUPS = 0,
    TRUCKS = {};

      

I recommend using a tool like JSLint or JSHint to check your code.

+1


source


It is not recommended in any programming language to use spaces or slashes in variable names. There are several ways to write vars using underscores, the camel case or the snake case to name just a few.

0


source







All Articles