Declaring Variables without Var, Let, Const - What Would Happen?

Code Tour
7 Mar 202113:52

Summary

TLDRIn this video, the speaker explores the consequences of declaring variables in JavaScript without using 'var', 'let', or 'const'. They explain that such variables are attached to the global object, which can lead to accidental overwrites of existing properties and affect the browser's default behavior. The speaker suggests using 'var', 'let', or 'const', creating a custom global object, or employing strict mode to avoid these issues. Additionally, they discuss the global execution context and how variables are managed within it, emphasizing the importance of understanding the call stack and function scope.

Takeaways

  • 🌐 In JavaScript, variables declared without `var`, `let`, or `const` are attached to the global object, which can lead to unintended behavior.
  • 🛠️ The global object in a browser environment is `window`, and modifying its properties can disrupt the browser's default functionality.
  • 🚫 Overwriting properties of the global object can weaken the resiliency of a program, making it harder to manage and extend.
  • 🔑 To avoid conflicts, it's recommended to use `var`, `let`, or `const` for variable declarations or to create a custom global object for application-wide properties.
  • 📚 Understanding the global object and its properties is crucial for preventing accidental overwrites and ensuring compatibility with third-party libraries.
  • 🔍 The `this` keyword in JavaScript refers to the global object, providing a way to access its properties and methods.
  • 🔒 Using strict mode in JavaScript can prevent the accidental creation of global variables and enforce more rigorous coding practices.
  • 📈 The call stack in JavaScript is a data structure that manages the execution of functions and helps visualize where variables are scoped.
  • 🛑 Functions in JavaScript are both executable code and objects, with the object part containing properties that can be accessed and manipulated.
  • 🔬 Tools like `console.dir` can be used to inspect the object properties of functions, including the global object.

Q & A

  • What happens if you declare a variable without using var, let, or const in JavaScript?

    -If you declare a variable without using var, let, or const, the variable gets placed onto the global object, which can lead to overwriting existing properties or creating new ones, potentially interfering with the runtime environment's native functionalities.

  • What is the global object in JavaScript?

    -The global object is an object that contains data and functionality allowing the runtime environment, such as a browser or Node.js, to perform various processes. In a browser, this is typically the 'window' object.

  • Why is it bad to overwrite properties of the global object?

    -Overwriting properties of the global object can change the default behavior of the runtime environment, leading to unexpected results and potentially conflicting with third-party libraries or future code.

  • What is global abatement and how does it help in managing global variables?

    -Global abatement is a process where you create a custom global object with properties and functionality that are accessible throughout your application. This prevents overwriting or creating new properties on the native global object.

  • How can you prevent accidentally writing variables onto the global object?

    -To prevent accidentally writing variables onto the global object, always use a variable declaration keyword (var, let, or const), use global abatement, or enable strict mode which prevents variable declarations without a keyword.

  • What is the call stack in JavaScript and how does it relate to variable scope?

    -The call stack is a data structure that follows a last-in, first-out rule and is used to manage the execution of functions. Variables declared with var, let, or const exist within the function portion of the global execution context or the function's scope.

  • How does strict mode prevent variables from being attached to the global object?

    -Strict mode prevents variables from being attached to the global object by throwing an error when a variable is declared without a keyword, thus enforcing the use of var, let, or const.

  • What are the different ways to access the global object in JavaScript?

    -You can access the global object in JavaScript using the 'this' keyword, by directly referencing 'window' in a browser environment, using 'global' in Node.js, or by inspecting the 'global' property in the 'scopes' tab of a function's object representation in the console.

  • Why is it important to understand the difference between function execution context and the global execution context?

    -Understanding the difference between function execution context and the global execution context helps in managing variable scope and avoiding conflicts or unintended side effects when declaring variables.

  • How can you ensure that your variables do not conflict with existing properties on the global object?

    -To ensure that your variables do not conflict with existing properties, use naming conventions that avoid common property names, always declare variables with var, let, or const, and consider using a custom global object for your application's global variables.

Outlines

00:00

🌐 Understanding Global Object in JavaScript

The paragraph discusses the implications of declaring a variable in JavaScript without using 'var', 'let', or 'const'. It explains that such variables are attached to the global object, which can vary depending on the runtime environment (browser or Node.js). In browsers, the global object is 'window', and adding or modifying properties on it can disrupt the browser's default functionality. The concept of global abatement is introduced as a strategy to mitigate this risk by creating a custom global object to hold application-wide properties, ensuring that the native functionalities of the runtime environment are not inadvertently altered.

05:02

📚 Exploring JavaScript's Call Stack and Variable Scope

This section delves into the JavaScript runtime's call stack, illustrating how it operates on a last-in, first-out principle. It explains that when running JavaScript, code executes within the global execution context, which consists of a function part and an object part, the latter being the global object ('window' in browsers). Variables declared with 'var', 'let', or 'const' exist within the function part of the global execution context, whereas undeclared variables are attached to the global object. The paragraph also touches on the importance of using strict mode to prevent accidental global variable declarations and provides methods to inspect the global object.

10:02

🛡️ Preventing Global Object Pollution in JavaScript

The final paragraph focuses on strategies to prevent accidental writing to the global object, which can lead to conflicts and reduced code resilience. It suggests always using a variable declaration keyword, employing global abatement by creating a custom global object, and utilizing strict mode to enforce good practices. The paragraph also outlines various methods to inspect the global object, such as using 'this', 'window', 'global', or the 'console.dir' method in the browser's developer tools. It concludes with an invitation for viewers to engage with the content by subscribing, liking, and commenting with questions.

Mindmap

Keywords

💡Global Object

The Global Object in JavaScript is a fundamental concept referring to the root object in the execution context of JavaScript code. In a web browser, this is typically the 'window' object. The video script discusses how declaring variables without 'var', 'let', or 'const' attaches those variables to the Global Object, which can lead to unintended behavior or conflicts with existing properties. For instance, the script mentions that in a browser environment, the Global Object contains properties like 'alert', 'document', and 'scrollX', which are essential for browser functionality.

💡Variable Declaration

Variable declaration in JavaScript is the process of defining a variable with a specific keyword such as 'var', 'let', or 'const'. The video script emphasizes the importance of using these keywords to prevent variables from being attached to the Global Object, which could lead to overwriting existing properties or creating new ones that might conflict with the application's intended behavior. The script gives an example of declaring a variable with 'const' within a function to keep it scoped to that function rather than the Global Object.

💡Global Abatement

Global Abatement is a strategy discussed in the script to mitigate the risk of polluting the Global Object with unnecessary properties. It involves creating a custom global object, separate from the native Global Object (like 'window'), to store application-wide variables and functions. This approach helps in maintaining a clean and organized codebase, preventing conflicts with native or third-party library functionalities. The script suggests using an empty object like 'const myGlobals = {}' and attaching necessary properties to it.

💡Call Stack

The Call Stack is a data structure in JavaScript that manages the execution of code by keeping track of function calls. It operates on a Last In, First Out (LIFO) principle, where the most recent function call is the first to be completed. The video script explains that the Call Stack is used to visualize the execution context, including the Global Execution Context and Function Execution Contexts. Variables declared with 'var', 'let', or 'const' exist within the function execution context, whereas undeclared variables are attached to the Global Object.

💡Scope

Scope in JavaScript refers to the accessibility of variables and functions within different parts of the code. The video script touches on how variables declared with 'var', 'let', or 'const' have their scope determined by the execution context they are created in. Variables declared globally (without 'var', 'let', or 'const') have a global scope, meaning they are accessible throughout the entire codebase, which can lead to potential conflicts and unintended side effects.

💡Resiliency

Resiliency in the context of the video script refers to the robustness and flexibility of a program, particularly its ability to handle changes without breaking. The script mentions that adding or modifying properties on the Global Object can weaken the resiliency of a program by making it more prone to conflicts and harder to maintain. Using proper variable declaration and global abatement can enhance resiliency by avoiding such conflicts.

💡Strict Mode

Strict Mode is a feature in JavaScript that alters the runtime's behavior in specific ways to help prevent common coding mistakes. The video script explains that one of the benefits of using Strict Mode is that it prevents the accidental creation of global variables, thus avoiding potential conflicts with the Global Object. By declaring 'use strict' at the beginning of a script or function, developers can enforce stricter parsing and error handling, leading to more secure and predictable code execution.

💡Naming Conventions

Naming Conventions are a set of rules for choosing the names of variables, functions, and other identifiers in code. The video script highlights the importance of using naming conventions to avoid conflicts with existing properties on the Global Object or with third-party libraries. By adhering to a consistent naming scheme, developers can reduce the risk of inadvertently overwriting essential properties or creating variables that conflict with those from external libraries.

💡Runtime Environment

The Runtime Environment in JavaScript refers to the context in which the code is executed, such as a web browser or a server using Node.js. The video script discusses how the Global Object varies depending on the runtime environment, with 'window' being the Global Object in browsers and a different object in Node.js. Understanding the runtime environment is crucial for managing how variables and functions interact with the Global Object and its properties.

💡Function Execution Context

A Function Execution Context in JavaScript is created when a function is called. It includes the function's scope chain and variable environment. The video script explains that when a function is executed, a stack frame for that function is pushed onto the Call Stack, and any variables declared within the function using 'var', 'let', or 'const' are scoped to that function's execution context. This is contrasted with global variables, which are attached to the Global Object and can have broader implications on the application's behavior.

Highlights

Discussing the consequences of declaring a variable without using var, let, or const in JavaScript.

Exploring the concept of the global object in JavaScript and its role in the runtime environment.

The global object in browsers is 'window', which contains properties for browser functionality.

Overwriting properties of the global object can change the default browser behavior.

Global abatement as a strategy to create a custom global object and avoid conflicts.

Using strict mode to prevent accidental global variable declarations.

The call stack in JavaScript and its function in managing the execution context.

Variables declared with var, let, or const exist within the function scope, not on the global object.

How to prevent variables from being attached to the global object when not declared with var, let, or const.

The importance of naming conventions to avoid conflicts with existing global object properties.

Different ways to inspect the global object in a browser environment.

Using 'this', 'window', and 'globalThis' to access the global object in JavaScript.

The 'console.dir' method to explore the object portion of a function for understanding closures and the global object.

Encouraging viewers to subscribe, like, and comment for further engagement and questions.

Transcripts

play00:00

hey everyone how's it going today we're

play00:02

going to talk about what would happen

play00:04

if you declared a variable without using

play00:07

var let or const for example i'm here in

play00:10

the google chrome

play00:11

dev tools and what if i just said

play00:14

somewhere equals true

play00:18

without using constellat or var

play00:21

in front of it right so i'm just going

play00:22

to save that variable as is

play00:26

what just happened let's find out

play00:33

okay so let's jump into this what would

play00:34

happen if i did something like this

play00:37

in production code why is this bad well

play00:41

the reason why

play00:42

is probably not what you might think and

play00:43

it is because

play00:45

in javascript there exists something

play00:48

called the global object

play00:50

now depending on which javascript

play00:52

runtime you are currently running your

play00:54

code in that can either be

play00:55

a browser or node so kind of think of it

play00:58

as like front-end back-end so depending

play01:00

on where you are running your code at

play01:02

any given moment

play01:04

there's something called the global

play01:06

object and what the global object is

play01:09

is an object of data and all this data

play01:13

basically contains functionality that

play01:16

allows

play01:17

that runtime environment to do

play01:20

all of the various processes that it

play01:21

needs to do in the browser

play01:23

the global object is something called

play01:25

window

play01:27

and there are a bunch of properties on

play01:29

this window

play01:30

object that allow the browser window

play01:33

the one that we're currently using to do

play01:36

a whole bunch of different stuff

play01:37

so for example in this one we have

play01:39

something called alert

play01:40

if we were to use that it'll show an

play01:42

alert pop-up modal

play01:44

we have document that'll give us access

play01:46

to the

play01:47

actual document object model what we see

play01:49

in the browser viewport over here on the

play01:51

left

play01:52

we have things like scroll x and scroll

play01:54

y

play01:55

those give us access to the various

play01:58

functionalities of how the scroll bars

play02:00

in your viewport work and where the

play02:03

cursor is at any given moment so let's

play02:05

jump back

play02:06

to here right what if we were to declare

play02:09

a variable without

play02:10

var let or const what will happen is

play02:13

that variable gets placed onto the

play02:16

global object

play02:17

now that might be fine it might work out

play02:20

okay

play02:21

but what if we were to do something like

play02:23

scroll

play02:24

x equals 100

play02:27

000 right then we are actually

play02:30

overwriting a property that already

play02:32

exists

play02:32

on the global object on window and

play02:35

what's gonna happen

play02:37

if we were to accidentally overwrite one

play02:39

of those properties

play02:40

is that what would happen is that the

play02:41

default what we would call the user

play02:43

agent

play02:43

functionality that is all the stuff that

play02:46

the browser has to do

play02:47

that default behavior would actually

play02:49

change so this could potentially be a

play02:51

really bad thing

play02:53

if we are running a program and it

play02:55

actually is messing with

play02:57

the runtime environment's native

play02:58

functionalities

play03:00

now aside from actually changing the

play03:01

functionality of the runtime environment

play03:03

creating new properties on the window

play03:05

object or potentially overwriting them

play03:07

will actually weaken what's called the

play03:09

resiliency of your program in this case

play03:11

that would be the ease of deleting and

play03:14

creating new functionality

play03:15

now one way to circumvent this is a

play03:17

process called global abatement and what

play03:20

that is

play03:21

is basically if you're familiar with the

play03:22

concept of state

play03:24

we are creating some sort of global

play03:27

object that's not

play03:28

the window object not the not the global

play03:31

object but we're creating our own global

play03:33

object

play03:34

with properties and functionality that

play03:36

will be available

play03:37

throughout our entire application our

play03:39

entire program

play03:40

so what we could do is i could do

play03:42

something like

play03:44

const my globals and that is just going

play03:47

to be an empty object

play03:49

and then anytime i have some

play03:51

functionality which i need

play03:52

access to throughout my entire program i

play03:55

can just place it on my global so i

play03:57

could do

play03:57

something like my globals dot sumvar

play04:00

equals true something like that and then

play04:03

that variable

play04:04

would be available to me throughout my

play04:05

entire program via the my global's

play04:08

global object also making sure that we

play04:11

are not

play04:12

overwriting or writing new properties

play04:14

onto the

play04:15

the global object the window object in

play04:18

this case means that we are also safe

play04:20

from potentially writing functionality

play04:22

that could conflict with other

play04:24

third-party libraries which we are using

play04:26

in our program

play04:27

now why is that the case because we

play04:29

could potentially have

play04:31

some third-party vendor logic which

play04:33

exists

play04:34

sort of at the same scope level as

play04:38

our global object so we want to make

play04:40

sure that

play04:41

this is where naming conventions come

play04:42

into because we want to make sure

play04:44

that none of these names conflict with

play04:46

names of

play04:48

functionality that already exists now

play04:50

something that's really important to

play04:51

understand

play04:52

is okay if we are creating properties

play04:55

without

play04:56

var let or const and they get put onto

play04:59

the window or the global object what

play05:02

happens when we create variables with

play05:03

var let or const where do those actually

play05:05

end up

play05:06

now in order to understand this we have

play05:08

to take a look at a feature of the

play05:11

javascript runtime called the call stack

play05:14

what the call stack is is it is a data

play05:17

structure

play05:18

which follows a last in first out rule

play05:20

meaning

play05:21

it's like a stack of pancakes so the

play05:23

last

play05:24

stack frame that gets put onto the top

play05:27

of the stack

play05:28

will be the first one that has to come

play05:30

off when we want to take one off

play05:32

so it's like a stack of plates or

play05:33

pancakes we have to in order to reach

play05:35

the bottom ones we have to take the top

play05:37

ones off

play05:38

first anytime we are running code

play05:40

anytime we are running

play05:42

javascript we are running code in

play05:45

the global execution context so we

play05:48

visualize that by placing a stack frame

play05:51

representing the global context

play05:54

onto the call stack so that's going to

play05:58

be our first our sort of base

play05:59

layer stack frame so what is the global

play06:03

context the global execution context is

play06:06

where we are

play06:06

executing our code by default when we

play06:10

are running code in javascript and this

play06:11

kind of has two parts

play06:13

and the reason why is because what we

play06:16

use the call stack

play06:17

for is to visualize the execution of

play06:21

functions anytime we run a function so

play06:24

if i had

play06:25

you know a function

play06:28

say name right we have a function say

play06:31

name

play06:32

and it says it will return

play06:37

chris let's say okay that's what this

play06:39

function does

play06:40

so that when we call say name

play06:43

what we're going to do is we're going to

play06:45

place a stack frame onto the call stack

play06:48

for say name and then

play06:51

when we are running the code of say name

play06:54

in other words when we are

play06:56

when we are evaluating what this

play06:58

function's

play06:59

definition actually does all of the code

play07:02

that's happening

play07:03

within the scope of this function is

play07:06

considered to be running

play07:08

within that stack frame now something

play07:11

else that we have to understand

play07:13

about javascript is that when we are

play07:15

running functions

play07:16

we have to know that functions are sort

play07:19

of like a function

play07:20

and an object so it's kind of two things

play07:24

so anytime we're running a function we

play07:26

have to understand that a function is

play07:28

two parts

play07:29

a function has both the functionality of

play07:32

the function itself but it also has

play07:34

an associated object and so when we're

play07:37

talking about

play07:38

this global execution context it's sort

play07:41

of two parts right there's a function

play07:43

part of it

play07:44

and there's also an object part of it

play07:46

the object part of it

play07:47

is the global object in other words if

play07:50

we're in the browser

play07:51

it's going to be the window

play07:54

and the function bit of it is actually

play07:56

where any variables are going to exist

play07:59

if we were to create them using const

play08:02

let or var so we have our object portion

play08:05

we are going to have our function

play08:07

portion

play08:08

so if we were to use var

play08:11

let or const to create a variable

play08:15

those variables will exist within sort

play08:18

of that function portion

play08:20

that that temporary portion of the

play08:22

running

play08:23

of the global execution context whereas

play08:26

if we were to declare them

play08:27

without var let or const they'll be

play08:30

placed onto

play08:31

the window object and a sort of a

play08:33

similar thing is true

play08:35

whenever we run a function so let's say

play08:37

again that we're going to run a function

play08:40

this function is going to be let's let's

play08:42

just make it say

play08:44

create variable

play08:48

and what this function does is it's

play08:51

going to create a variable

play08:52

so i'm going to say const my

play08:56

variable

play08:59

equals true

play09:03

so when we actually run this function

play09:05

create

play09:07

variable we're going to place we're

play09:10

going to push

play09:11

a stack frame onto the call stack for

play09:13

create

play09:14

variable and inside of the running

play09:18

of that function execution context that

play09:21

that sort of top level stack frame on

play09:24

the call stack when we are running that

play09:25

code

play09:26

the code inside of that function's scope

play09:30

what's going to happen to that variable

play09:31

that we create inside of there

play09:33

well because we are creating it with

play09:36

const

play09:36

it is going to be created within that

play09:39

function

play09:39

that function portion of this function

play09:42

but we know

play09:43

that if we were to write this variable

play09:46

without

play09:47

const actually the first thing that it

play09:49

would do

play09:50

is it would look outside of the function

play09:52

to see

play09:53

whether there is already something

play09:56

called

play09:56

myvariable inside of the global

play10:00

execution context

play10:02

if it is it will overwrite it if it's

play10:05

not

play10:05

then it will go one level up it'll try

play10:08

to look on

play10:09

again the window so regardless of how

play10:12

many

play10:13

function execution contexts deep you are

play10:16

eventually still going to try to write

play10:19

that variable onto

play10:20

the global object in this case the

play10:22

window always something we have to be

play10:24

careful of

play10:25

so some ways that we can prevent

play10:28

ourselves from accidentally potentially

play10:30

writing

play10:30

variables onto the global object

play10:33

way number one always use a variable

play10:36

declaration keyword so var let or const

play10:39

way number two use that process of

play10:41

global abatement

play10:42

where we created another global object

play10:45

which would be

play10:46

accessible throughout the entirety of

play10:48

our app and then way number three is to

play10:50

actually prevent ourselves from writing

play10:52

that functionality in the first place

play10:54

we can do that using something called

play10:55

strict mode so one of the things that

play10:57

strict mode will do

play10:59

is it will actually prevent us from

play11:01

writing a variable

play11:02

without using a variable declaration

play11:04

keyword by the way

play11:05

all this talk of the global object if

play11:08

you ever want to see

play11:09

what is actually in the global object

play11:11

there are a couple different ways that

play11:13

you can do that way number one

play11:15

we can look at what this is so the

play11:18

reserved keyword this

play11:19

in javascript will by default

play11:22

point to the global object so that's one

play11:25

way we could

play11:26

type that in in our dev tools take a

play11:28

look pop this open

play11:29

you can see all of the data all of the

play11:32

functionality

play11:33

that exists for the global object for

play11:36

the browser

play11:36

another way we can call that

play11:40

runtimes global object by name so either

play11:43

window

play11:44

or the node global object which

play11:48

off the top of my head not sure but we

play11:50

can look at here in the browser we can

play11:52

look at window we can just

play11:53

say do window directly another way

play11:56

global this

play11:57

global this by default is going to point

play12:00

to

play12:01

this which points to the global object

play12:04

and then the fourth way is a little bit

play12:05

weird if you're familiar with the

play12:07

concept of closure

play12:09

this should look familiar to you if we

play12:11

have a function let's say i have a

play12:12

function

play12:13

say name and what this function will do

play12:17

is it will return chris

play12:22

now we know from before that functions

play12:26

are both functions and objects so what i

play12:29

want to do is actually see the

play12:30

object portion of this function object

play12:34

combo

play12:35

and i'm going to do that using

play12:38

a special console method called console

play12:42

der that stands for directory so that

play12:44

will allow us to see

play12:45

the object portion of a function object

play12:48

combo

play12:49

so i'm going to pass in my function here

play12:51

it was called

play12:52

say name and that will allow me to see

play12:54

all of the object

play12:56

methods and functionality and data

play12:58

associated

play12:59

with say name in this case

play13:02

it doesn't have anything except the

play13:04

default stuff but

play13:06

we can see down here that there's going

play13:07

to be something called scopes

play13:09

and again if you're familiar with

play13:10

closure you'll see your closures in

play13:12

the scopes tab here but you'll also see

play13:16

something called global and that is

play13:18

going to point sort of

play13:20

one level down to the global object

play13:24

so those are sort of the four ways that

play13:25

we can look at the global object

play13:28

at least in the browser all right i'm

play13:30

going to cap it there for today

play13:31

if you have found this useful helpful

play13:34

informative

play13:35

if you found value in this please feel

play13:36

free to give me a subscribe down below

play13:38

like this and leave me a comment if you

play13:41

have a question i'll be sure to answer

play13:43

that as soon as i can

play13:44

thanks for watching have a good one

play13:51

you

Rate This

5.0 / 5 (0 votes)

Etiquetas Relacionadas
JavaScriptGlobal ObjectVariable DeclarationWeb DevelopmentRuntime EnvironmentCode Best PracticesBrowser FunctionsGlobal AbatementStrict ModeCall Stack
¿Necesitas un resumen en inglés?