codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

JavaScript: Learn & Understand Scope

Brandon Morelli
codeburst
Published in
5 min readJan 15, 2018

--

Scope Benefits

Types of Scope

Global Scope

var cat = 'Jerry';

Local Scope

// *GLOBAL*
var cat = 'Jerry';
function localScopeExample(){
// *LOCAL*
var dog = 'Marley';
}
var cat = 'Jerry';
console.log(cat); // Jerry
function localScopeExample(){
var dog = 'Marley';
console.log(cat); // Jerry
}
console.log(cat); // Jerry
var cat = 'Jerry';
console.log(dog); // Uncaught ReferenceError: dog is not defined
function localScopeExample(){
var dog = 'Marley';
console.log(dog); // Marley
}
console.log(dog); // Uncaught ReferenceError: dog is not defined
function func1(){
var dog = 'Marley';
console.log(dog); // Marley
}
function func2(){
var dog = 'Shasta';
console.log(dog); // Shasta
}

Lexical Scope

// *GLOBAL*
var dog = 'Lewis';
function outerFunc(){
// *SCOPE 1*
var cat = 'Jerry';
function innerFunc(){
// *SCOPE 2*
console.log(cat); // Jerry
console.log(dog); // Lewis
}
}

Block Scope & let, const

let x = 1;{
let x = 2;
console.log(x); // 2
}
console.log(x); // 1
let x = 1;if (x !== 2) {
let x = 2;
console.log(x); // 2
}
console.log(x); // 1
{
let x = 1;
let x = 2;
}
Uncaught SyntaxError: Identifier 'x' has already been declared

Key Takeaways

Closing Notes:

If this post was helpful, please click the clap 👏 button below a few times to show your support! ⬇⬇

--

--

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Written by Brandon Morelli

Creator of @codeburstio — Frequently posting web development tutorials & articles. Follow me on Twitter too: @BrandonMorelli

Responses (7)

Write a response