Hi dev,
In this article we will learn about Scope in javascript.
Variable is the fundamental part in programming. We declare variable to store different data types. To declare a variable we use the key word var, let and const. A variable can declared at different scope. In this section we will see the scope, scope of variables when we use var or let. Variables scopes can be:
Window
Global
Local
Variable can be declared globally or locally or window scope. We will see both global and local scope. Anything declared without let, var or const is scoped at window level.
Let us image we have a scope.js file.
Window Scope
Without using console.log() open your browser and check, you will see the value of a and b if you write a or b on the browser. That means a and b are already available in the window.
//scope.js
a = 'JavaScript' // is a window scope this found anywhere
b = 10 // this is a window scope variable
function letsLearnScope() {
console.log(a, b)
if (true) {
console.log(a, b)
}
}
console.log(a, b) // accessible
Global scope
A globally declared variable can be accessed every where in the same file. But the term global is relative. It can be global to the file or it can be global relative to some block of codes.
//scope.js
let a = 'JavaScript' // is a global scope it will be found anywhere in this file
let b = 10 // is a global scope it will be found anywhere in this file
function letsLearnScope() {
console.log(a, b) // JavaScript 10, accessible
if (true) {
let a = 'Python'
let b = 100
console.log(a, b) // Python 100
}
console.log(a, b)
}
letsLearnScope()
console.log(a, b) // JavaScript 10, accessible
Local scope
A variable declared as local can be accessed only in certain block code.
//scope.js
let a = 'JavaScript' // is a global scope it will be found anywhere in this file
let b = 10 // is a global scope it will be found anywhere in this file
function letsLearnScope() {
console.log(a, b) // JavaScript 10, accessible
let c = 30
if (true) {
// we can access from the function and outside the function but
// variables declared inside the if will not be accessed outside the if block
let a = 'Python'
let b = 20
let d = 40
console.log(a, b, c) // Python 20 30
}
// we can not access c because c's scope is only the if block
console.log(a, b) // JavaScript 10
}
letsLearnScope()
console.log(a, b) // JavaScript 10, accessible
Now, you have an understanding of scope. A variable declared with var only scoped to function but variable declared with let or const is block scope(function block, if block, loop etc). Block in JavaScript is a code in between two curly brackets ({}).
//scope.js
function letsLearnScope() {
var gravity = 9.81
console.log(gravity)
}
// console.log(gravity), Uncaught ReferenceError: gravity is not defined
if (true) {
var gravity = 9.81
console.log(gravity) // 9.81
}
console.log(gravity) // 9.81
for (var i = 0; i < 3; i++) {
console.log(i) // 1, 2, 3
}
console.log(i)
In ES6 and above there is let and const, so you will not suffer from the sneakiness of var. When we use let our variable is block scoped and it will not infect other parts of our code.
//scope.js
function letsLearnScope() {
// you can use let or const, but gravity is constant I prefer to use const
const gravity = 9.81
console.log(gravity)
}
// console.log(gravity), Uncaught ReferenceError: gravity is not defined
if (true) {
const gravity = 9.81
console.log(gravity) // 9.81
}
// console.log(gravity), Uncaught ReferenceError: gravity is not defined
for (let i = 0; i < 3; i++) {
console.log(i) // 1, 2, 3
}
// console.log(i), Uncaught ReferenceError: gravity is not defined
The scope let and const is the same. The difference is only reassigning. We can not change or reassign the value of const variable. I would strongly suggest you to use let and const, by using let and const you will writ clean code and avoid hard to debug mistakes. As a rule of thumb, you can use let for any value which change, const for any constant value, and for array, object, arrow function and function expression.
Hope it can help you…
Categories : JavaScript
Tags : JavaScript
order tricor 200mg sale tricor 200mg uk buy tricor 200mg online cheap
cialis 10mg without prescription cost sildenafil order sildenafil online
buy acarbose 25mg for sale prandin 2mg cheap griseofulvin pills
aspirin 75mg without prescription aspirin 75mg sale buy zovirax generic
dipyridamole 100mg pill buy dipyridamole generic purchase pravastatin generic
order dydrogesterone generic sitagliptin online jardiance 25mg price
prasugrel 10 mg pill purchase tolterodine pills detrol 1mg over the counter
monograph 600mg cost cilostazol 100 mg oral buy pletal online
buy generic mestinon online pyridostigmine 60 mg cost buy rizatriptan 5mg online cheap
zovirax online buy xalatan generic buy rivastigmine 6mg online
premarin 0.625mg canada order viagra 100mg for sale viagra 100mg without prescription
order omeprazole 10mg generic order metoprolol 50mg pills buy generic lopressor
buy telmisartan without prescription purchase micardis buy molnunat 200mg generic
order tadalafil pills order sildenafil 100mg online sildenafil australia
cenforce 50mg brand order cenforce 50mg generic aralen 250mg brand
generic provigil 100mg order deltasone generic buy prednisone online
omnicef 300mg ca lansoprazole 30mg oral brand lansoprazole 30mg
cheap isotretinoin accutane 20mg without prescription order generic azithromycin 250mg
buy azipro 500mg online cheap brand gabapentin neurontin 100mg drug
lipitor drug buy proventil paypal cost norvasc
roulette online with real money buy lasix generic order lasix 40mg generic
protonix 20mg drug pantoprazole price how to buy phenazopyridine
no deposit casino ventolin canada buy ventolin without prescription
best online gambling play live poker online ivermectin 3mg for humans
symmetrel 100mg ca buy atenolol 100mg sale order avlosulfon 100mg generic
real poker online buy augmentin 1000mg without prescription order levothyroxine pill
clomiphene 100mg sale generic clomiphene imuran 50mg oral
methylprednisolone 16mg tablets triamcinolone oral purchase triamcinolone pills
levitra 10mg over the counter buy vardenafil 10mg generic order tizanidine sale
order perindopril online cheap desloratadine online buy buy allegra 180mg pill
purchase phenytoin pill cyclobenzaprine 15mg cost ditropan 2.5mg brand
baclofen order online order generic baclofen 25mg toradol generic
buy claritin online cost loratadine cost priligy 30mg
ozobax pill order toradol online cheap cheap toradol 10mg
buy alendronate pills order furadantin pills cost macrodantin
glimepiride without prescription purchase misoprostol online order etoricoxib 120mg pill
purchase pamelor online cheap paracetamol 500mg ca cost anacin 500mg
buy orlistat paypal buy orlistat cheap buy generic diltiazem 180mg
buy generic famotidine 40mg order generic cozaar 50mg prograf order
azelastine 10 ml ca order generic acyclovir avapro 150mg uk
esomeprazole tablet buy generic esomeprazole topamax 200mg ca
purchase zyloprim how to get rosuvastatin without a prescription buy crestor 20mg without prescription
order imitrex 50mg order sumatriptan 50mg online cost avodart
oral buspirone 5mg cost amiodarone 100mg amiodarone 100mg for sale
zantac 300mg price generic ranitidine 150mg celecoxib 200mg pill
buy domperidone 10mg pills order domperidone 10mg sale order sumycin 250mg pills
flomax 0.2mg pill order simvastatin generic zocor 10mg canada
order aldactone 100mg without prescription buy finasteride 5mg for sale purchase finasteride for sale
good academic writing affordable thesis writing pay for essay writing uk
buy diflucan 100mg sale cost diflucan 200mg how to buy cipro
buy sildenafil 50mg sale sildenafil dosage order estrace 1mg
flagyl 200mg over the counter buy cephalexin 250mg sale order cephalexin 250mg without prescription
lamictal 200mg us minipress 2mg sale nemazole buy online
cleocin pills buy fildena medication order fildena
where can i buy retin tadalis 10mg pill order avana
order nolvadex buy budesonide paypal buy budesonide online
tadalafil for sale online indocin brand buy indomethacin online
cefuroxime 250mg without prescription buy ceftin no prescription methocarbamol 500mg without prescription
purchase desyrel online sildenafil us purchase clindamycin
lamisil for sale order terbinafine for sale real money poker online
buy aspirin pill aspirin 75 mg oral pala casino online
essays for sale online custom essay writing services reviews buy cefixime 100mg generic
my mother essay writing play real money online casino slots free
order trimox sale biaxin 250mg without prescription buy macrobid pills for sale
buy rocaltrol generic rocaltrol where to buy buy cheap fenofibrate
buy generic clonidine tiotropium bromide medication spiriva 9 mcg drug
prescription medication for blackheads best acne treatment for adults oxcarbazepine 300mg generic
minocycline price minocycline 100mg tablet ropinirole canada
order uroxatral 10mg online cheap buy uroxatral 10mg sale best treatment for abdominal pain
purchase letrozole generic abilify drug aripiprazole 30mg price
best sleep aid at walgreens alopecia areata getting worse buy weight loss medications online
most effective smoking cessation drugs order pain meds online legally most effective pain killer tablet
medroxyprogesterone 5mg cheap order hydrochlorothiazide pills buy generic microzide
best antiviral pills vitamins to prevent herpes outbreaks type 2 diabetes lab values
order periactin without prescription order cyproheptadine 4 mg pills order generic nizoral 200 mg
best vitamin for toenail fungus best medication for hsv 2 how to lower blood pressure instantly in 10 mins
buy cymbalta generic cymbalta pill buy modafinil 100mg
how to heal a stomach ulcer fast best otc treatment for uti bladder infection medications list
promethazine medication buy generic phenergan stromectol coronavirus
birth control pills by mail birth control patch near me premature ejaculation treatment online
prednisone 10mg brand buy deltasone 20mg generic order amoxicillin 500mg pill
prescription medication against stomach acid vitamin for mucous membranes prescription drugs for excessive gas
order zithromax 500mg generic gabapentin 100mg generic buy gabapentin 600mg pills
actigall online buy bupropion 150 mg ca cheap zyrtec
buy generic atomoxetine online buy sertraline without prescription buy sertraline pills for sale
order furosemide 100mg online order albuterol generic order albuterol inhaler
lexapro cost buy cheap revia buy naltrexone generic
buy cheap generic augmentin serophene over the counter buy clomiphene 100mg generic
buy ipratropium 100mcg cheap zyvox 600mg purchase linezolid pill
buy starlix generic buy candesartan 16mg pill candesartan 16mg canada
vardenafil 10mg ca buy levitra 10mg pill buy plaquenil paypal
buy carbamazepine sale buy generic carbamazepine cost lincocin 500 mg
buy generic cenforce 100mg generic chloroquine glucophage 500mg cheap
buy lipitor 80mg without prescription norvasc 5mg generic zestril 5mg canada
buy duricef 250mg pill ascorbic acid cost purchase combivir online
generic prilosec 10mg where can i buy tenormin order atenolol 100mg
buy generic dostinex over the counter priligy 90mg without prescription buy priligy 30mg generic
medrol 16mg otc order aristocort 10mg generic desloratadine 5mg without prescription
order cytotec online cheap purchase orlistat online brand diltiazem 180mg
generic piracetam 800mg buy nootropil for sale brand clomipramine 25mg
acyclovir 800mg uk order crestor 20mg pill brand rosuvastatin 10mg
buy itraconazole online cheap buy tinidazole no prescription purchase tindamax generic
ezetimibe 10mg oral order ezetimibe 10mg sale buy generic tetracycline online
order zyprexa 10mg generic nebivolol 20mg ca order diovan 80mg online cheap
cyclobenzaprine 15mg price cyclobenzaprine online order toradol without prescription
gloperba pill purchase plavix generic methotrexate 2.5mg generic
acne treatment for teenage girl deltasone cost oral medication for cystic acne
best cold medicine without antihistamine depo-medrol tablets generic allergy pills
nausea medication names buy allopurinol 300mg pill
diphenhydramine hcl nighttime sleep aid buy melatonin 3mg for sale
buy deltasone 10mg sale prednisone 20mg over the counter
list of prescription nausea medicine retrovir 300mg tablet
strongest acne medication prescription buy aczone online hormonal acne treatment near me
best otc heartburn medicine reviews order accupril 10 mg generic
Жена исполнилось годика старше, и я хотел порадовать ее необычным букетом. Заказал на "Цветов.ру" яркий микс. Улыбка на ее лице – лучшая рекомендация для этого сервиса. Советую! Вот ссылка https://mscs-boost.ru/sykt/ - цветы с доставкой
generic accutane 10mg accutane 10mg pills accutane 10mg sale
Решил устроить романтический вечер для жены. Заказал на "Цветов.ру" букет роз и украсил им наш ужин. Рекомендация: добавьте свежести в вашу жизнь с помощью цветов, и "Цветов.ру" в этом ваш надежный союзник. Советую! Вот ссылка https://net-wizards.ru/tihoretsk/ - магазин цветочный
Сделал нелепую ошибку и решил ее исправить. Купил на "Цветов.ру" восхитительный букет, чтобы передать свои извинения. Ребята, сервис просто волшебен – быстро, удобно, и цветы свежайшие! Советую! Вот ссылка https://extralogic.ru/sochi/ - заказ букетов с доставкой
Хотя далеко от родителей, я не забыл о Дне Матери. Заказал на "Цветов.ру" букет для мамы. Она была в восторге от красоты цветов и волнующего сюрприза. Рекомендую всем, кто ценит прекрасные моменты в жизни. Советую! Вот ссылка https://net-wizards.ru/kaluga/ - монобукет
buy amoxil 250mg online cheap amoxicillin without prescription buy amoxicillin paypal
7 day sleep prescription melatonin over the counter
order zithromax online cheap cost zithromax 500mg order generic zithromax
buy neurontin 600mg pill neurontin oral
generic azithromycin 250mg cost azipro 500mg buy generic azithromycin for sale
furosemide order online order lasix 100mg pill
cheap omnacortil 10mg omnacortil 5mg us order prednisolone pills
buy amoxil generic amoxil buy online order amoxil 1000mg pill
buy generic monodox doxycycline 200mg canada
ventolin inhalator over the counter ventolin 2mg without prescription purchase albuterol without prescription
clavulanate us buy clavulanate sale
order synthroid 150mcg online synthroid 150mcg generic synthroid 75mcg pill
brand levitra 10mg vardenafil order online
buy cheap clomid buy clomiphene 50mg generic purchase clomid online cheap
В моем стремлении к здоровому питанию, я нашел идеального помощника - https://blender-bs5.ru/collection/sokovyzhimalki-dlya-granata - выжималку для граната от 'все соки'. Это устройство стало неотъемлемой частью моего утра.
brand zanaflex buy tizanidine 2mg generic purchase tizanidine for sale
Решение купить шнековую соковыжималку изменило моё представление о здоровом питании. Благодарю 'Все соки' за их чудесную продукцию. Их https://h-100.ru/collection/ruchnye-shnekovye-sokovyzhimalki - шнековая соковыжималка купить оказалась лучшим вложением в моё здоровье.
semaglutide 14 mg brand buy semaglutide without a prescription buy semaglutide 14 mg pill
prednisone 10mg sale order prednisone 20mg purchase prednisone pills
generic semaglutide buy semaglutide tablets order semaglutide 14 mg online cheap
Решение купить шнековую соковыжималку изменило моё представление о здоровом питании. Благодарю 'Все соки' за их чудесную продукцию. Их https://h-100.ru/collection/ruchnye-shnekovye-sokovyzhimalki - шнековая соковыжималка купить оказалась лучшим вложением в моё здоровье.
purchase accutane without prescription purchase isotretinoin generic order accutane 20mg for sale
Когда я решил серьезно заняться своим питанием, я понял, что мне нужно купить шнековую соковыжималку. 'Все соки' предоставили прекрасный выбор. Теперь свежие соки - это часть моего каждодневного ритуала. https://blender-bs5.ru/collection/shnekovye-sokovyzhimalki - Купить шнековую соковыжималку было лучшим решением!
buy ventolin generic buy ventolin generic buy ventolin inhalator
buy amoxil paypal amoxicillin 250mg us buy amoxil 250mg for sale
augmentin canada augmentin 1000mg price augmentin 375mg cheap
order azithromycin 500mg sale buy zithromax tablets buy zithromax generic
buy synthroid sale levothyroxine pill levoxyl buy online
brand semaglutide 14 mg order rybelsus online cheap buy rybelsus for sale
hollywood casino online real money play online casino real money free blackjack games
levitra 20mg canada purchase vardenafil pills vardenafil canada
lyrica order cost lyrica 75mg pregabalin price
buy hydroxychloroquine 400mg for sale purchase plaquenil generic plaquenil usa
where to buy triamcinolone without a prescription buy aristocort paypal order triamcinolone 4mg pills
buy cialis 40mg sale buy cialis 20mg generic tadalafil 10mg without prescription
clarinex usa clarinex 5mg brand where to buy clarinex without a prescription
order cenforce without prescription where to buy cenforce without a prescription cenforce 50mg cost
cheap claritin 10mg claritin 10mg us order claritin generic
highest rated canadian pharmacies cialis-canadian pharmacy cialis canadian pharmacy's Get the facts
cheap aralen generic chloroquine chloroquine online buy
how to get glycomet without a prescription buy metformin sale brand glucophage 1000mg
order generic xenical 60mg orlistat 120mg pills diltiazem 180mg over the counter
buy amlodipine online cheap buy amlodipine tablets amlodipine 10mg pills
zovirax medication zyloprim 100mg tablet purchase allopurinol
zestril 5mg tablet order lisinopril 5mg pill order zestril 2.5mg pill
rosuvastatin drug rosuvastatin brand ezetimibe 10mg tablet
pharmacy rx one Pharmacy canada pharmacy for cialis Canadian Pharmacy Shipping Usa Cialis, Viagra Whithout Prescription
order prilosec 10mg generic buy generic omeprazole 20mg order omeprazole generic
order motilium 10mg sale buy tetracycline 250mg online order sumycin 500mg sale
how to get flexeril without a prescription baclofen ca order ozobax pill
purchase lopressor for sale buy lopressor generic cost metoprolol 100mg
order toradol 10mg online cheap order colchicine buy gloperba pills
buy tenormin 100mg purchase atenolol online cheap atenolol uk