adsterra

Variables and their scope in Java Script!!!



Variables in JS

                   There are three keywords in JS used to declare variable:

1.var:-a variable declare with var is defined throughout the program as compares to let.

2.let:-It is declare a block scope local variable ,optionally initializing it to a value.Var is function scoped whereas let is block scoped.

3.Constants: are read-only, therefore you can not modify them later on.


let fname='Prit '

var lname=123

// 3 ways of printing 

console.log(fname + '-' + lname)

let fullname = fname +'**'+ lname

console.log(fullname)

// constant
var score = 100

score = 130

const bonus = 50

var finalscore = (score + bonus) *1.8


console.log(finalscore)





Scope of different Variables in JS


let iamGlobal ='something global'

if (true) {
    //using let scope of local variable only inside block
    let iamLocal='some local value '
    
    //change the value
    iamGlobal='New value'
    console.log(iamGlobal);
    console.log(iamLocal);
//scope anywhere
console.log(iamGlobal);
//getting error while try access it. 
//console.log(iamLocal);

//<*---Var---*>
if (true) {

    console.log('Concept of var keyword')
    var imLocal = 'some local values i have :)'
    console.log(imLocal)

}
//using var local variable can access outside the block

console.log(imLocal)


In the next post we will go with Undefined and null values in js.
Don't forget to comment 😍😍

Post a Comment

2 Comments