How do i save a variable in javascript?

If you mean in a web browser, there are two options:

  • Cookies

  • Web storage [in your case, specifically, "local storage" as opposed to "session storage"]

Cookies are universally supported by browsers, although users can turn them off. The API to them in JavaScript is really, really bad. The cookies also get sent to your server, so they increase the size of requests to your server, but can be used both client- and server-side.

Setting a cookie is easy, but reading a cookie client-side is a pain. Look at the MDN page above for examples.

Web storage is supported by all major modern browsers [including IE8 and up]. The API is much better than cookies. Web storage is purely client-side, the data is not sent to the server automatically [you can, of course, send it yourself].

Here's an example using web storage: Live Copy

Value: 


[function[] {
  // Use an input to show the current value and let
  // the user set a new one
  var input = document.getElementById["theValue"];

  // Reading the value, which was store as "theValue"
  if [localStorage && 'theValue' in localStorage] {
    input.value = localStorage.theValue;
  }

  document.getElementById["setValue"]. title = function [] {
    // Writing the value
    localStorage && [localStorage.theValue = input.value];
  };
}][];

  • Previous
  • Overview: First steps
  • Next

After reading the last couple of articles you should now know what JavaScript is, what it can do for you, how you use it alongside other web technologies, and what its main features look like from a high level. In this article, we will get down to the real basics, looking at how to work with the most basic building blocks of JavaScript — Variables.

Throughout this article, you'll be asked to type in lines of code to test your understanding of the content. If you are using a desktop browser, the best place to type your sample code is your browser's JavaScript console [see What are browser developer tools for more information on how to access this tool].

What is a variable?

A variable is a container for a value, like a number we might use in a sum, or a string that we might use as part of a sentence.

Variable example

Let's look at a simple example:

Press me

const buttonA = document.querySelector['#button_A'];
const headingA = document.querySelector['#heading_A'];

buttonA. title = [] => {
  const name = prompt['What is your name?'];
  alert[`Hello ${name}, nice to see you!`];
  headingA.textContent = `Welcome ${name}`;
}

In this example pressing the button runs some code. The first line pops a box up on the screen that asks the reader to enter their name, and then stores the value in a variable. The second line displays a welcome message that includes their name, taken from the variable value and the third line displays that name on the page.

Without a variable

To understand why this is so useful, let's think about how we'd write this example without using a variable. It would end up looking something like this:

Press me

const buttonB = document.querySelector['#button_B'];
const headingB = document.querySelector['#heading_B'];

buttonB. title = [] => {
    alert[`Hello ${prompt['What is your name?']}, nice to see you!`];
    headingB.textContent = `Welcome ${prompt['What is your name?']}`;
}

You may not fully understand the syntax we are using [yet!], but you should be able to get the idea. If we didn't have variables available, we'd have to ask the reader for their name every time we needed to use it!

Variables just make sense, and as you learn more about JavaScript they will start to become second nature.

One special thing about variables is that they can contain just about anything — not just strings and numbers. Variables can also contain complex data and even entire functions to do amazing things. You'll learn more about this as you go along.

Note: We say variables contain values. This is an important distinction to make. Variables aren't the values themselves; they are containers for values. You can think of them being like little cardboard boxes that you can store things in.

Declaring a variable

To use a variable, you've first got to create it — more accurately, we call this declaring the variable. To do this, we type the keyword let followed by the name you want to call your variable:

Here we're creating two variables called myName and myAge. Try typing these lines into your web browser's console. After that, try creating a variable [or two] with your own name choices.

Note: In JavaScript, all code instructions should end with a semi-colon [;] — your code may work correctly for single lines, but probably won't when you are writing multiple lines of code together. Try to get into the habit of including it.

You can test whether these values now exist in the execution environment by typing just the variable's name, e.g.

They currently have no value; they are empty containers. When you enter the variable names, you should get a value of undefined returned. If they don't exist, you'll get an error message — try typing in

Note: Don't confuse a variable that exists but has no defined value with a variable that doesn't exist at all — they are very different things. In the box analogy you saw above, not existing would mean there's no box [variable] for a value to go in. No value defined would mean that there is a box, but it has no value inside it.

Initializing a variable

Once you've declared a variable, you can initialize it with a value. You do this by typing the variable name, followed by an equals sign [=], followed by the value you want to give it. For example:

myName = 'Chris';
myAge = 37;

Try going back to the console now and typing in these lines. You should see the value you've assigned to the variable returned in the console to confirm it, in each case. Again, you can return your variable values by typing their name into the console — try these again:

You can declare and initialize a variable at the same time, like this:

This is probably what you'll do most of the time, as it is quicker than doing the two actions on two separate lines.

A note about var

You'll probably also see a different way to declare variables, using the var keyword:

Back when JavaScript was first created, this was the only way to declare variables. The design of var is confusing and error-prone. So let was created in modern versions of JavaScript, a new keyword for creating variables that works somewhat differently to var, fixing its issues in the process.

A couple of simple differences are explained below. We won't go into all the differences now, but you'll start to discover them as you learn more about JavaScript [if you really want to read about them now, feel free to check out our let reference page].

For a start, if you write a multiline JavaScript program that declares and initializes a variable, you can actually declare a variable with var after you initialize it and it will still work. For example:

myName = 'Chris';

function logName[] {
  console.log[myName];
}

logName[];

var myName;

Note: This won't work when typing individual lines into a JavaScript console, just when running multiple lines of JavaScript in a web document.

This works because of hoisting — read var hoisting for more detail on the subject.

Hoisting no longer works with let. If we changed var to let in the above example, it would fail with an error. This is a good thing — declaring a variable after you initialize it results in confusing, harder to understand code.

Secondly, when you use var, you can declare the same variable as many times as you like, but with let you can't. The following would work:

var myName = 'Chris';
var myName = 'Bob';

But the following would throw an error on the second line:

let myName = 'Chris';
let myName = 'Bob';

You'd have to do this instead:

let myName = 'Chris';
myName = 'Bob';

Again, this is a sensible language decision. There is no reason to redeclare variables — it just makes things more confusing.

For these reasons and more, we recommend that you use let in your code, rather than var. There is no reason to use var, unless you need to support Internet Explorer 10 or older with your code.

Note: If you are trying this code in your browser's console, prefer to copy & paste each of the code blocks here as a whole. There's a feature in Chrome's console where variable re-declarations with let and const are allowed:

> let myName = 'Chris';
  let myName = 'Bob';
// As one input: SyntaxError: Identifier 'myName' has already been declared

> let myName = 'Chris';
> let myName = 'Bob';
// As two inputs: both succeed

Updating a variable

Once a variable has been initialized with a value, you can change [or update] that value by giving it a different value. Try entering the following lines into your console:

myName = 'Bob';
myAge = 40;

An aside on variable naming rules

You can call a variable pretty much anything you like, but there are limitations. Generally, you should stick to just using Latin characters [0-9, a-z, A-Z] and the underscore character.

  • You shouldn't use other characters because they may cause errors or be hard to understand for an international audience.
  • Don't use underscores at the start of variable names — this is used in certain JavaScript constructs to mean specific things, so may get confusing.
  • Don't use numbers at the start of variables. This isn't allowed and causes an error.
  • A safe convention to stick to is so-called "lower camel case", where you stick together multiple words, using lower case for the whole first word and then capitalize subsequent words. We've been using this for our variable names in the article so far.
  • Make variable names intuitive, so they describe the data they contain. Don't just use single letters/numbers, or big long phrases.
  • Variables are case sensitive — so myage is a different variable from myAge.
  • One last point: you also need to avoid using JavaScript reserved words as your variable names — by this, we mean the words that make up the actual syntax of JavaScript! So, you can't use words like var, function, let, and for as variable names. Browsers recognize them as different code items, and so you'll get errors.

Good name examples:

age
myAge
init
initialColor
finalOutputValue
audio1
audio2

Bad name examples:

1
a
_12
myage
MYAGE
var
Document
skjfndskjfnbdskjfb
thisisareallylongvariablenameman

Try creating a few more variables now, with the above guidance in mind.

Variable types

There are a few different types of data we can store in variables. In this section we'll describe these in brief, then in future articles, you'll learn about them in more detail.

So far we've looked at the first two, but there are others.

Numbers

You can store numbers in variables, either whole numbers like 30 [also called integers] or decimal numbers like 2.456 [also called floats or floating point numbers]. You don't need to declare variable types in JavaScript, unlike some other programming languages. When you give a variable a number value, you don't include quotes:

Strings

Strings are pieces of text. When you give a variable a string value, you need to wrap it in single or double quote marks; otherwise, JavaScript tries to interpret it as another variable name.

let dolphinGoodbye = 'So long and thanks for all the fish';

Booleans

Booleans are true/false values — they can have two values, true or false. These are generally used to test a condition, after which code is run as appropriate. So for example, a simple case would be:

Whereas in reality it would be used more like this:

This is using the "less than" operator [

Chủ Đề