Git Product home page Git Product logo

skills-based-js-intro-to-variables's Introduction

JavaScript Variables

Objectives

  • Explain how variables are tied to their contexts
  • Explain how local and global variables differ

Introduction

In JavaScript, variables become global when they aren't declared with the var keyword. The story is actually a little bit more interesting.

Think of variables as notes on pieces of paper. Local variables are written normally, maybe on a post-it — they're for one person to see. Global variables, contrastingly, are written on billboards in big, bold letters — they're for everyone to see!

Variables in JavaScript have function-level scope, meaning that variables are bound to the function context in which they're declared. An example will make what we mean clearer.

function speaker() {
  var sentence = 'Bird is the word.';

  console.log(sentence);
}

Above is an example of a local variable - it is defined within a function and will not be accessible outside of the function.

If we call speaker() in console, we'll see 'Bird is the word.' logged out — all is well. But if we call console.log(sentence) outside of the speaker function, we'll get an error — the variable sentence is bound to the context of the function speaker.

If, however, we write

function speaker() {
  sentence = 'Bird is the word.';
}

speaker();
console.log(sentence);

and run speaker(), we can now call console.log(sentence) outside of the speaker function because we have declared the variable sentence without the var keyword — it's now a global variable.

Same Variable, Different Scopes

Keep in mind too that the same variable name used in different scopes is effectively a different variable. We sometimes refer to repeating a variable name in an inner scope as "shadowing" — it's best to avoid, as you'll quickly see how confusing it can be:

var cuteAnimal = 'quokka';

function makeVariable() {
  var cuteAnimal = 'sugar glider';
  return cuteAnimal;
}

makeVariable();
// 'sugar glider'

cuteAnimal;
// 'quokka'

See? Nothing breaks, but if you have a lot of shadowed variables (or even just a lot of space between a variable's initial declaration and its subsequent change(s)), you're gonna have a bad time.

Changing Variable Values

Local variable assignment can overwrite global variable assignment:

volume = 10; //declares a global variable called volume and sets it to 10

function returnEleven() {
  var volume = 11;  //declares a local variable called volume and sets it to 11
  return volume;
}

returnEleven(); // returns 11
volume; // the global variable is still 10

function goToEleven(){
  volume = 11;  //changes the global variable to 11
  return volume;
}

goToEleven(); // returns 11
volume; // the global variable volume has been changed to 11

Notice that in the first function above, a local variable, var volume is declared and assigned to 11, but the global volume remains unchanged.

However, in the second function, the volume variable does not have var in front of it. JavaScript considers this to be a reassignment of the existing volume global variable. The result is that the global volume variable gets reassigned.

Moving in the opposte direction, global variable assignment cannot overwrite local variable assignment, rather it simply reassigns the value of the local variable:

function sayHello() {
  var greeting = "hola";
  greeting = "hello";
  return greeting;
}

sayHello()
// Returns "hello",
// This demonstrates that the variable greeting is now pointing to the string "hello" instead of "hola"

greeting
// ReferenceError: greeting is not defined
// This demonstrates that the variable greeting is still local instead of global

Since greeting = "hello" is in the same scope and follows var greeting = "hola" in sequence, JavaScript understands this to be a reassignment of the local greeting variable.

Resources

View Variables on Learn.co and start learning to code for free.

skills-based-js-intro-to-variables's People

Contributors

annjohn avatar curtisgreene avatar dom-mc avatar ipc103 avatar jessrudder avatar kthffmn avatar lizbur10 avatar maxwellbenton avatar pletcher avatar samnags avatar smulligan85 avatar spencerlepine avatar stephaniecoleman avatar victhevenot avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

skills-based-js-intro-to-variables's Issues

Can't solve funkyFunction

I tried every variation of changing funkyFunction, and still no luck. Can anyone out there help a frustrated coder? :)

var theFunk = funkyFunction(); <-- the best I came up with

Split into two

Raised earlier in another lesson, but splitting this so that we just talk about variables and creating variables and string interpolation with variables in an earlier lesson before functions would make the idea of arguments in functions easier for students to understand.

Then this lesson would only be about variables and scope

@jmburges

Sentence is not defined

function speaker() {
sentence = 'Bird is the word.';
}

console.log(sentence);

I think the "}" should go after the console.log(sentence); because in Chrome's console it gives an error the way it is currently written. Hope this helps, have a great day.

not getting same result

If we call speaker() in console, we'll see 'Bird is the word.' logged out — all is well. But if we call console.log(sentence) outside of the speaker function, we'll get an error — the variable sentence is bound to the context of the function speaker.

I am not getting an error when I test this so it does not make sense.

Local Variable is Global

In the CHANGING VARIABLE VALUES section, "Local variable assignment can overwrite global variable assignment" confused me and made me think it meant a local variable can overwrite a global one, when it really meant a global variable assignment inside a function can overwrite the one outside the function. Can be confusing for people just learning. It made me confused on what defines a local vs. global variable. First reading it made me thing that a variable assignment inside a function, but without var in front, was local, when it's actually global.

Minor Typo

'Ther esult' in readme, instead of 'The result'

keeping stuff updated

keeping stuff updated is what makes companies grow; var is a deprecated way of variables, you should teach let & const

Trouble with example in browser console

Hello,

When I typed in the first example in my browser's console, and typed in "console.log(speaker)", I did not get "Bird is the word." Rather, the console printed out the whole code. I know I typed the code exactly as it appeared in the lesson. Am I overlooking a syntax error?

Typo

Typo under the volume variable reassignment demo:
"Ther esult is that the global volume variable gets reassigned."
should read
"The result is that the global volume variable gets reassigned."

Const and Let?

Are they important this early on in the curriculum? Do you test it in following labs?

What does "binds the variable to the local scope" mean?

Bind is a super tehcnical word. I would just say "restrict" maybe?. Also what is local scope? Maybe mention it in the context of it's the function. They don't know if statements yet so we can't use that. The only scope they've seen is functions

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.