user4184124
user4184124

Reputation:

Correct format structure creating variables

Is it ok to create vars with spaces and forward slashes?

Like so:

var PICKUPS / TRUCKS = {};

Upvotes: 3

Views: 80

Answers (4)

radiovisual
radiovisual

Reputation: 6468

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

To reference the list of valid characters you can refer to this answer.

In your case, this is invalid in Javascript:

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

First, the / operator is the divide operator, so the Javascript interpreter will look at this like a Mathematical operation, trying to "divide PICKUPS with TRUCKS", which will cause an error, especially after the var keyword, it won't know how to make sense of that (for example, first it will 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, which will confuse the javascript interpreter).

But you can do something like this:

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


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

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

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

Hope this helps!

Upvotes: 4

Prabu
Prabu

Reputation: 4197

This is invalid javascript.

I recommend you declare variables separately like such:

var PICKUPS = 0,
    TRUCKS = {};

I recommend you use a tool like JSLint or JSHint to verify you code.

Upvotes: 1

Nick
Nick

Reputation: 927

In any programming language its not a good idea to use spaces or slashes in your variable names. There are several ways to write vars using underscores, camel case or snake case are just a few.

Upvotes: 0

Ashima
Ashima

Reputation: 4824

No, this is NOT VALID variable name in javascript. It cannot have spaces or forward slash in it.

Here https://mothereff.in/js-variables you can test if your variable name is valid or not

Upvotes: 2

Related Questions