DEV Community

codeWithNithin
codeWithNithin

Posted on

How to create a variable in JS?

To create a variable in JS, we have 3 keywords, let, var and const.
where let and const is introduced in ES6, and var is the old keyword used to declare the variables.

For Example:

let firstName = 'Nithin';
const age = 23;
var lastName = 'kumar';
Enter fullscreen mode Exit fullscreen mode

here let and var behaves in the same way, that is, we can change the value of the variable which is declared as let or var.

For example:

let firstName = 'Nithin';
var lastName = 'kumar';

firstName = 'Varsha';
lastName = 'kumari';
Enter fullscreen mode Exit fullscreen mode

But const is a keyword, which doesnt change its variable value once it is being assigned.

For example:

const age = 23;
age = 24; // will give error
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

You can also create one without using any of let, var, and const if you're not in strict mode

Collapse
 
marzelin profile image
Marc Ziel • Edited

You can also create one without using any of let, var, and const if you're not in strict mode

You should mention that this is an antipattern.

Also, when you declare a function you're creating a variable since a function is just a value in JS and can be overridden.
What's interesting about this is that functions are block-scoped so technically JS had block-scoped variables before ES2015.

Collapse
 
codewithnithin profile image
codeWithNithin

ok