Git Product home page Git Product logo

javascript-intro-to-variable-assignment-and-declaration's Introduction

JavaScript Variables

Overview

In this lesson, we'll introduce variables and how to declare them in Javascript.

Objectives

  1. Explain how to declare a variable in JavaScript
  2. Explain what variables are good for
  3. Declare a variable without assigning a value
  4. Declare and define a variable
  5. Explain multi-line variable assignment

What are Variables?

Sometimes, we need to store a piece of information so that we can refer to it — often multiple times — later on. In real life, we would probably jot down a note in a notebook or on a post-it.

note

In programming, we use variables. Variables in JavaScript are used to store data that will be used in our program. A variable can point to almost any type of value including numbers, strings, arrays, objects, and functions.

Variables are assigned values using the = operator. Variable names are typically all lower case; in the case of multiple words, the words are joined together using lowerCamelCase.

You've already seen a couple of examples of variables being assigned:

var name = "Joe"
var height = 70

In the last two lessons, we asked you to modify name and height variables. By changing var name = "Joe" to var name = "Susan", you were able to modify the name variable assignment so that it equalled "Susan" instead of "Joe".

In this lesson, we'll look at a few additional examples of variable declaration.

Declaring Variables

One of the most basic ways to declare a variable is to write the variable name, followed by an equals sign (=) and then the value we want to assign to the variable. For instance, lets say I have the variable word. We could, if we wanted to, write:

word = 'bird'

This would declare a word variable and assign it the value of the string 'bird'. The thing is, now we've declared a global variable. Global variables can be accessed anywhere in an application, which can lead to strange behavior.

Using a global variable is like passing someone a note on a billboard. Sure, it gets the message across, but way more people than necessary now have the message.

What if, for example, we wanted word's value to be something other than 'bird' at some point in the application? Or what if we needed to make use of a variable called word but not this particular word?

In the browser, global variables are all properties of window. What is window? Well, it's the — erm — window in which the browser displays the current page. It holds a whole bunch of things (which is probably obvious), global variables among them.

Accidentally setting variables to "global" is a dangerous, imprecise coding mistake.

var

In the olden days (1995), JavaScript had one way to declare a non-global variable: var. Using the keyword var creates a local variable, meaning that it is only accessible inside the current function in which it is declared. (However, this is a bit tricky - If var is not declared inside a function, it's actually still global!)

Flat fact: What's a function? Well, functions are ways of organizing our code so that we can run it repeatedly. We'll talk more about functions in a bit, but we need to mention them here because they're vital to understanding variable scope in JavaScript (which we will tackle in greater depth when we cover functions). Don't worry too much right now about what exactly a function is; we just want to get used to seeing the word.

Below is an example of how how this works. If you would like to follow along, in your terminal, type node. This will open Node and allow you to write JavaScript directly in the terminal. Alternatively, using Chrome, you can [open a console in your browser's developer tools][devtools] and paste JavaScript there as well.

// declare the variable
var word

// assign a value to the variable
word = 'bird'

console.log(word) // 'bird'

// assign another value to the variable
word = 'dog'

console.log(word) // 'dog'

Note that word = 'bird' is present here, but this time, it isn't automatically a global variable. This is because we've already declared word with var word. With this line present, word = 'bird' is just assigning a value to the existing variable.

Once we have declared a local variable word with var word, we can assign and reassign its value as we please.

We can perform variable declaration and assignment on the same line to save space:

var word = 'bird'

What does it mean that word is a local variable? Well, if we're just entering it in the console, not much — the variable still becomes a property of window, meaning... in this case, 'word" is a global variable (as mentioned above). (Go ahead, try typing window.word in the console — prepare to be amazed!)

We'll learn more about local and global variables in a later lesson. For now, know that you should always declare a variable with var.

Multi-line Variable Assignment

Let's say I needed to declare and define multiple variables. It feels like a lot to have to repeat var over and over again. JavaScript allows us to do multi-line variable assignment to alleviate this pain. Every variable must be separated with a comma, and the entire line must end with a semicolon.

Let's condense the below code into one line:

var a = 5
var b = 2
var c = 3
var d = 'hello'
var e = 'goodbye'

The above is equivalent to:

var a = 5,
    b = 2,
    c = 3,
    d = 'hello',
    e = 'goodbye';

which can be converted to:

var a = 5, b = 2, c = 3, d = 'hello', e = 'goodbye';

Try typing each variable in the console. You should see the appropriate values returned for each one.

Personally, we're of the opinion that it's best to declare each variable with its own var keyword. The comma fanciness saves a little bit of typing, but at the expense of nonstandard indentation (you're using two spaces, right?) and can introduce a bit of weirdness if we're doing anything other than simple assignment.

Changing values

Sometimes, information changes — we have to scratch out old notes and scribble in revisions.

In JavaScript, we can simply reassign the new value to the variable.

var myNote = "Get milk"

// later on

myNote = "Get cookies"

When we change the value of a variable, we do not use var again. We simply use the = to give the variable a new value.

View JavaScript Variable Assignment and Declaration on Learn.co and start learning to code for free.

javascript-intro-to-variable-assignment-and-declaration's People

Stargazers

 avatar  avatar  avatar  avatar

Watchers

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

javascript-intro-to-variable-assignment-and-declaration's Issues

Intro to functions lab

I am having a difficult time correcting the errors of this lab. I understand that the exercises be challenging to help learn through experience, yet I find there was not enough previous information given to successfully complete this lab within a reasonable time.

I have noticed that many recent users are experiencing difficulty with this lab as well. I feel that the lab is too vague. I would like more information on working with strings inside of functions as it pertains to the lab if that is possible.

Curriculum track/readme conflict

This lesson is deployed in both Intro to JavaScript and BCP. The following text from the README is true for the BCP curriculum but not for Intro to JS:

You've already seen a couple of examples of variables being assigned:

var name = "Joe"
var height = 70

In the last two lessons, we asked you to modify name and height variables.
By changing var name = "Joe" to var name = "Susan", you were able to modify
the name variable assignment so that it equalled "Susan" instead of "Joe".

The two lessons mentioned are not in the Intro to JS track. Perhaps this should be removed?

Sandbox

Im typing commands in the sandbox but Im not seeing any changes when I type window.word.

Am I using the sandbox correctly?

intended to leave off semi-colon?

I know that semi-colons are optional a lot, but should we be consistent?

// declare the variable
var word;

// assign a value to the variable
word = 'bird';

console.log(word); // 'bird'

// assign another value to the variable
word = 'dog';

console.log(word) // 'dog'

Missing semicolon in code example

In the code example of the multi-line variable assignment, I think the condensed version is missing a semicolon at the end.

var a = 5, b = 2, c = 3, d = 'hello', e = 'goodbye'

should be

var a = 5, b = 2, c = 3, d = 'hello', e = 'goodbye';

Javascript Variable assignment and declaration

In this module it says to try typing some variable names into the console and that I should see the value printed but for me it is not showing anything when I pull up the console. Does anybody know any common reasons I am not getting anything?

IDE

My IDE is missing from the browser.... Is there a way to retrieve/ restore it to continue following along?

Intro to Functions Lab help

I'm working the Intro to functions lab and am having trouble with the sayHiToGrandma function. I'm not entirely sure how to satisfy all 3 conditions

Missing semicolon

Section title: MULTI-LINE VARIABLE ASSIGNMENT
Sentence: ...which can be converted to: var a = 5, b = 2, c = 3, d = 'hello', e = 'goodbye'
Needed change: Missing semicolon at the end of variable declaration.

No semicolon

Not sure if this is of much contribution but the third console image under the multi line variable part of JavaScript Variable Assignment and Declaration free course doesn't end the line with a semicolon. Not sure if it is or isnt intentional. Just figured I'd bring it up...

Directions for following along are vague and unclear

The directions to follow along on this page are a bit unclear. Especially considering we have access to the sandbox site and the developer tools. It would be a little more helpful to let us know where we need to access the console from.

Just a thought!

Not seeing all errors

When I run the test it is not matching the screenshots. I am not seeing " 3 test failing" I am only seeing the third error "
Error: Expected 'space' to equal 'Let's talk about space.' " in the terminal. I am have run the test in the index-test.js and the index.js folders. Is there a different file I should be running them in?

Readme Mentions Functions

Using the keyword var creates local variable, meaning that it is only accessible inside the current function in which it is declared. (If it's not declared inside a function, it's actually still global!)

Students don't know what a function is in this point– maybe call it a 'code context' or something similar?

Directions a bit unclear

Instructs students to follow along in the console, but not clear as to what that means in this lesson. They can open dev tools and do it that way.

BreakPoint pushes console content below visible area inside Learn ide when minimizing window.

With the console docked in the editor and content filling the visible area of the console, If the window width is adjusted below approx 2/3 screen-width the console content is pushed below the bottom of the window and cannot be seen even when scrolled all the way down. It must be forced to redraw the content which can be seen by either adjusting font-size(ctrl-shift-"-" or "+") or undocking and redocking the console from the Editor. It will also return to normal if returning to fullscreen. This may prevent users from being able to view the llesson in the browser and work in the IDE on the same shared screen without forcing the redraw mentioned above. In the attached image, the page is scrolled to its lower limit and there is two lines that can not be viewed at the bottom of the console.
learnline

Text inconsistancies

Just letting you know that the last lesson completed did not go over this information:
In the last two lessons, we asked you to modify name and height variables. By changing var name = "Joe" to var name = "Susan", you were able to modify the name variable assignment so that it equalled "Susan" instead of "Joe".

I am taking the free javascript intro course, the last lesson was a console.log, console.error, and console.warn lab

No further action needed to assist me, just wanted to let yall know.

Thanks!

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.