Home > Web Front-end > JS Tutorial > Intro to JS Variable Declarations

Intro to JS Variable Declarations

PHPz
Release: 2024-09-04 14:32:02
Original
779 people have browsed it

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
    }
}
Copy after login

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;
}
Copy after login

Specifically the line:

    draggedElement = event.target;
Copy after login

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;
Copy after login

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")
  }
}
Copy after login

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
Copy after login

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")
  }
}
Copy after login
  • 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 (<anonymous>:9:3)
    at <anonymous>:1:1
Copy after login

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.)

The above is the detailed content of Intro to JS Variable Declarations. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template