Code Highlights logo

Learn

Variables

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!";
3
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

Instructions

1.

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

2.

Print the value of the name variable to the console.

3.

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

4.

Print the value of the numOfPets variable to the console.

Sign up to start coding

Already have an account?

Sign In

Course content