JavaScript Variable

You are Here:

JavaScript Variable

A variable can be used to store temporary data that can be altered, or varied.

Where Variables are stored?

Unlike permanent storage, which might be saved to hard disk, JavaScript variables are held in the computer's memory (RAM). This means that it is much faster to store and retrieve the data.

Variables Lifetime

Javascript variables have a limited lifetime. When your visitors close the page or move to a new one, your variables are lost, unless you take some steps to save them somewhere.

Rules for declaring Variables

Each variable is given a name so that you can refer to it elsewhere in your code. These names must follow certain rules.

  • Each variable name should be unique, else, overriding will occur.
  • Variable names can contain letter, numbers, underscores and dollar sign.
  • Variable names must begin with a letter, underscores, or dollar sign.
  • Variable names are case sensitive (a and A are different variables)
  • Javascript Keywords (var, function, for, etc) cannot be used as variable names.

Syntax

var variableName;

More Examples

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <script> var x = 1; x = x + 1; document.write("x = "+x); </script> </body> </html>

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <script> var x = "Steve"; var y = "Smith"; var z = x + y; document.write("z = "+z); </script> </body> </html>

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <script> var x = 1 + 2 + "Steve"; var y = 1 + "Steve" + 2; var z = "Steve" + 1 + 2; document.write("x = "+x+"<br> y = "+y+"<br> z = "+z); </script> </body> </html>

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p> I like <span id="company">Honda</span></p> <button onclick="myFunction()">Change</button> <script> var x = "Harley Davidson"; function myFunction(){ document.getElementById("company").innerHTML = x; } </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author