[JavaScript] What is the diffrence of var and let?
zplusfour (916)


Some people ask a lot, is there a diffrence between the var keyword and the let keyword? Well, yes, there is.


We use let and var to declare variables, to use them with our program.

For example:

let age = 10;
// or
var age = 10;
console.log('Your age is', age);

But then you'll tell me: "If we declare variables with both, why there is a diffrence?".
Ok, have an example:

function greet() {
  if (true) {
    let s = "ahah";

greet() // s is not defined, RefrenceError

Why s is undefined? Well because we use let to declare variables in brackets or we can just call them local variables.
You can't use it outside the brackets that it is declared in.

But with var:

function greet() {
  if (true) {
    var s = "ahaa"
greet() // ahaa

With var, you declare global variables which you can use it anywhere (of course not outside a function or a class).


I hope you enjoyed this tutorial, have a great day!

  • ZDev1
You are viewing a single comment. View All