DEV Community

pjparham
pjparham

Posted on

Declaring Variables in JavaScript

Hello! Welcome to my first post, and thank you for checking out my blog. We are going to start with something simple: the different ways to declare variables in JavaScript.

There are three ways to declare variables in JavaScript, and those are let, const, and var. Today we will just be covering let and const, which were introduced in 2015 and are now used much more often than var.

let

Using let allows us to declare a variable that we may want to change the value of at a later time. You can declare a variable using let without immediately assigning it a value.

let dog;
//=> undefined
Enter fullscreen mode Exit fullscreen mode

Later you could assign a value to your variable with the following syntax:

dog = 'Ted';
//=> Ted
dog;
//=> Ted
Enter fullscreen mode Exit fullscreen mode

When using let, you can assign a different value to the variable at any time.

dog;
//=> Ted
dog = 'Libby';
dog
//=> Libby
Enter fullscreen mode Exit fullscreen mode

const

We use const when we want to assign a value to a variable that will remain constant throughout our code. You cannot reassign a variable declared with const, and its value must be set when declaring the variable.

const breed = 'chihuahua';
//=>undefined

breed;
//=> chihuahua

breed = 'beagle'
//=> Uncaught TypeError: Assignment to constant variable.
Enter fullscreen mode Exit fullscreen mode

If you try to declare a variable using const without assigning a value, you will get an error message.

const breed
//=> Uncaught SyntaxError: Missing initializer in const declaration
Enter fullscreen mode Exit fullscreen mode

I hope this helped you learn more about different ways to declare a variable in JavaScript, and when to use let and when to use const. Thanks for reading!

Resources

MDN - let
MDN - const

Top comments (0)