For a quick skim => read underlined material along with code examples
If you're learning JavaScript for the first time then let's start off with JavaScript fundamentals. Understanding the basics of JavaScript can start by learning what variables are. And if you're like me then you might need someone to really break it down and spell it out for you.
What are variables?
- Variables stores the data value that can be changed later on
- Imaginary box that you store your information/value in to use later
Ways to declare a JavaScript variable w/ reserved words:
- var
- let
- const
How to declare a variable :
When we want to declare a variable we need to use a reserve word, a unique name that identifies it , and whatever value it is equal to.
Rules for naming your variable :
- start with lowercase
- no spaces
- camelCase if using multiple words
var uniqueName = value
let uniqueName = value
const uniqueName = value
var
Unless your coding from the year 1995 to 2015 then var is not really needed in JavaScript. Var can create scope issues that caused it to be difficult to diagnose bugs in your code. Many resources have advised against using var as there is no good reason to use it in your code.
> Lesson : No use for var when declaring variable
const
This option should be our go-to when declaring variables. Const cannot be redeclared or reassigned.
Let's declare a variable with const :
const myAge = 25
Let's try to reassigned the value :
const myAge = 25
myAge = 2
//=> Uncaught TypeError: Assignment to constant variable.
> Lesson : We can assume that the variable will remain the same every time we reference it.
let
We can't redeclare let but we can reassign it's value.
Let's declare a variable with let :
let myAge = 25
Let's try to reassign the value:
let myAge = 25
myAge = 2
myAge;
=> 2
> Lesson : Use let whenever you know the the value of the variable will change.
Resources
Top comments (0)