From d964653d179d81b8cf6a8ffa41af96623e8620af Mon Sep 17 00:00:00 2001 From: sonedayan <67210349+sonedayan@users.noreply.github.com> Date: Thu, 9 Nov 2023 20:01:14 +0100 Subject: [PATCH 1/2] Create lexicalScope.md A summary of my understanding of lexical scope in javascript. --- lexicalScope.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 lexicalScope.md diff --git a/lexicalScope.md b/lexicalScope.md new file mode 100644 index 0000000..8637b3e --- /dev/null +++ b/lexicalScope.md @@ -0,0 +1,33 @@ +# Lexical Scope in JavaScript + +## Introduction +**Lexical Scope** (also known as Static Scope) in JavaScript is a fundamental concept that every developer should understand. It's the scope model that JavaScript follows and it's about how and where variables, constants, and functions can be accessed during the runtime of the code. + +## Understanding Lexical Scope +In JavaScript, a scope is created: +- At the global level (outside of all code blocks). +- Every time a function is created. + +When a variable is used in JavaScript, the JavaScript engine will try to find the variable's value in the current scope. If it can't find it, it will look in the outer scope and will continue to do so until it finds the variable or reaches the global scope. + +```javascript +let globalVar = "I'm a global variable"; + +function outerFunc() { + let outerVar = "I'm an outer variable"; + + function innerFunc() { + let innerVar = "I'm an inner variable"; + console.log(innerVar); // Output: I'm an inner variable + console.log(outerVar); // Output: I'm an outer variable + console.log(globalVar); // Output: I'm a global variable + } + + innerFunc(); +} + +outerFunc(); +``` +In the above example, innerFunc has access to variables in its own scope, the outer function's scope, and the global scope. +Conclusion +Understanding lexical scope is crucial for writing effective JavaScript code. It helps in understanding how variables are looked up and can help prevent potential bugs in the code. From 6ffed035f943ff289b024258c5b553dcf65125ed Mon Sep 17 00:00:00 2001 From: sonedayan <67210349+sonedayan@users.noreply.github.com> Date: Thu, 9 Nov 2023 20:02:46 +0100 Subject: [PATCH 2/2] Update Contributors.md Added my name to the list of contributors. --- Contributors.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Contributors.md b/Contributors.md index a9e9ede..a9a8f5f 100644 --- a/Contributors.md +++ b/Contributors.md @@ -5,4 +5,5 @@ 1. icodejsx 2. ogbon(Segun Amosu) 3. Solomon Eseme +4. Dayan Sone