user13709754
user13709754

Reputation:

How do I define keywords in Javascript?

I try something like this:

var varr = var;
varr x = 10;

It doesn't work, for obvious reasons, but you get the idea. How do I define keywords in Javascript, like how I can in C:

#define var int
var x = 10;

The above code wouldn't work, but is there a way to do something similar in Javascript? Not that I would absolutely need to, but just wondering.

Upvotes: 2

Views: 425

Answers (3)

Xetera
Xetera

Reputation: 1479

The reason why this is possible in C is because #define allows you to declare macros that are replaced in the source code before compilation. Javascript doesn't have a concept of macros so it's not a part of the language however there are tools in JS that let you add this kind of compilation step even though it's not a part of JS itself.

Babel is probably the most popular way to do this and https://github.com/kentcdodds/babel-plugin-macros is pretty useful although I'm not sure if you can use it to redefine parts of the language.

You can instead use something like https://github.com/sweet-js/sweet-core to do what you want which lets you add a pre-processor step to replace macros however like I said, JS doesn't support macros so this is a step you have to execute to generate valid Javascript.

syntax varr = function (ctx) {
  return #`var`;
};
varr test = 10;
$ sjs test.sweet
var test = 10;

It's also important to mention that in C this is something that's built into the language so IDEs understand how to deal with macros, but if you're using an external tool you're not going to have a fun time using macros that redefine keywords, especially when it comes to things like syntax highlighting. This is something I'd definitely discourage, but it is technically possible if you're willing to step outside the bounds of just Javascript.

Upvotes: 0

Ericgit
Ericgit

Reputation: 7073

JavaScript doesn't allow you to use the reserved keyword as the identifier's value, What you're gonna do is a pretty clear mistake here. you defined variable and assign as value unsupported datatypes which js don't know, Learn more

var  <variable-name> = <reserved-keyword>

expected value:

var <variable-name> = <value>

javascript support all datatypes which you use in C, Int, Float, String, Obj...

Example of:

var x; // declare empty variable
x = 1;

var y   = "String";
var z   = [];
var foo = {};

Upvotes: 0

Subrata Banerjee
Subrata Banerjee

Reputation: 299

var is a reserved token by Javascript and thus cannot be used incorrectly, or as part of variable names.

When JavaScript parses our code, behind the scenes it’s converting everything into appropriate characters, then the engine attempts to execute our statements in order and as var is a reserved token it will throw Uncaught SyntaxError: Unexpected token 'var'

Upvotes: 2

Related Questions