"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Intro to JS Variable Declarations

Intro to JS Variable Declarations

Published on 2024-11-08
Browse:528

Writing this guide for by father who is building alis4ops.com.

  • I refer to as "Baba".
  • He is learning to build web applications, formerly an Electrical Engineer.
  • Will leave some notes around the article referring to him, so anyone on the interwebz reading this can ignore those lines. Hope you guys don't mind!

Context

We have the following functions:

  • handleStartTouch
  • handleMoveTouch

Baba defined in DragDrop.js

function handleStartTouch(event) {
    draggedElement = event.target;
    const touch = event.touches[0];
    touchStartX = touch.clientX - draggedElement.getBoundingClientRect().left;
    touchStartY = touch.clientY - draggedElement.getBoundingClientRect().top;
}

function handleMoveTouch(event) {
    event.preventDefault()
    if (draggedElement) {
        const touch = event.touches[0];
        // ..more code
    }
}

Notice that we are accessing draggedElement on line:

  • if (draggedElement) {

hanldeMoveTouch does not raise an error when it called.

Placing a breakpoint on if (draggedElement) in Chrome DevTools will show that draggedElement resolves to the same html element provided by event.target in handleStartTouch

Issue

Why can we can access draggedElement in handleMoveTouch even through it is defined in handleStartTouch

More generically, why can we access a variable which was defined in a function in another function in javascript?


Explanation

Look at handleStartTouch function:

function handleStartTouch(event) {
    draggedElement = event.target;
    const touch = event.touches[0];
    touchStartX = touch.clientX - draggedElement.getBoundingClientRect().left;
    touchStartY = touch.clientY - draggedElement.getBoundingClientRect().top;
}

Specifically the line:

    draggedElement = event.target;

It does not declare the variable name draggedElement using either one of the keywords

  • const
  • let
  • var

For example, we are not defining it like so:

    const draggedElement = event.target;

Variable Declaration (a.k.a Keywords)

In Javascript, when we do not use the variable declarations (also called keywords), javascript considers that variable a global variable.


Exercise

Consider the following example where we define two functions:

// Takes in two arguments and returns the sum
function add(x, y) {
  sum = x   y
  return sum
}

// prints sum if it is defined
function printStatus() {
  if (sum) {
    console.log("Sum: ", sum)
  } else {
    console.log("Sum does no exist")
  }
}

Open up DevTools in Chrome

  • navigate to "Console"
  • Copy and paste the code above
  • Press enter
  • It will return undefined, thats fine.

Intro to JS Variable Declarations

In the console, call add(1,1)

  • you will see the console return 2
add(1,1)
=> 2

Intro to JS Variable Declarations

Then call printStatus

  • You will see the output Sum: 2

Intro to JS Variable Declarations

We can see that printStatus() can access the variable sum defined in add(x, y)

This is because the variable sum is being declared without this following keywords:

  • sum = x y

Now lets change add(x, y) add to use a variable declaration for sum

// Takes in two arguments and returns the sum
function add(x, y) {
  const sum = x   y // use the variable declartion const
  return sum
}

// prints sum if it is defined
function printStatus() {
  if (sum) {
    console.log("Sum: ", sum)
  } else {
    console.log("Sum does no exist")
  }
}
  • Go to Chrome
  • Refresh the page with Ctrl R
    • you can also open a new tab and open up devtools console again.

Let's define the functions in the console log again.

  • Copy and paste the code snippet above into the console and press enter.

We need to redefine it because we are started a new dev console.

Intro to JS Variable Declarations

Now in the console, call add(2, 2)

  • you will see the console return 4

Intro to JS Variable Declarations

Call printStatus to see if can access the variable sum defined in add(x, y)

printStatus()
> Uncaught ReferenceError: sum is not defined
    at printStatus (:9:3)
    at :1:1

Intro to JS Variable Declarations

The error says sum is not defined

This confirms that when a variable is defined with a variable declaration (const, let, var) within a function, that variable's scope is only within the function

When a variable is defined without a variable declaration within a function, that variable's scope is global.

Hope this helps Baba (and anyone else reading this.)

Release Statement This article is reproduced at: https://dev.to/nerdherd/variable-declarations-14lg?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3