If you have already register Login here.
A variable is a literal assigned to an identifier.
A variable must be declared before you can use it. There are 3 ways to do this, using var, let or const, and those 3 ways differ in how you can interact with the variable later on.
What is var:
Until ES2015, var was the only construct available for defining variables.
var x = 0
If you forget to add var you will be assigning a value to an undeclared variable, and the results might vary.
In modern environments, with strict mode enabled, you will get an error. In older environments (or with strict mode disabled) this will simply initialize the variable and assign it to the global object.
If you don’t initialize the variable when you declare it, it will have the undefined value until you assign a value to it.
var x= 'undefined'
You can redeclare the variable many times, overriding it:
var x = 1
var x = 2
What is let:
let is a new feature introduced in ES2015 and it's essentially a block scoped version of var. Its scope is limited to the block, statement or expression where it's defined, and all the contained inner blocks.
Modern JavaScript developers might choose to only use let and completely discard the use of var.
If let seems an obscure term, just read let color = 'red' as let the color be red and it all makes much more sense
Defining let outside of any function - contrary to var - does not create a global variable.
What is const:
Variables declared with var or let can be changed later on in the program, and reassigned. Once a const is initialized, its value can never be changed again, and it can't be reassigned to a different value.
const x = 'test const'
We can’t assign a different literal to the a const.
© 2023 Easy To Learning. All Rights Reserved | Design by Easy To Learning