Code highlights logo



Create a Variable: var

To create a variable using var, we use the following syntax:

1var variableName;

Variable Naming Rules:

  • Variable names must start with a letter, underscore, or dollar sign.
  • They can contain letters, numbers, underscores, or dollar signs.
  • They are case-sensitive, so myVariable and myvariable are different variables.

Assigning a Value to a Variable

We can assign a value to a variable during declaration or later in the code. Example:

1var message;
2message = "Hello, world!";
4var greeting = "Welcome!"; // We can initialize and declare a variable in a single line of code.

Variable usage

Once we have assigned a value to a variable, we can use it in our code. Example:

1var num1 = 10;
2var num2 = 5;
3var sum = num1 + num2;
4console.log(sum); // Output: 15



Declare a new variable called name and assign it the value of "John".


Print the value of the name variable to the console.


Declare another variable called numOfPets and assign it the value of 3.


Print the value of the numOfPets variable to the console.

Sign up to start coding

Already have an account?

Sign In

Course content