DEV Community

Cover image for Values and Variables in JavaScript
aishwaryavasu0509
aishwaryavasu0509

Posted on

Values and Variables in JavaScript

variables

Variables in JavaScript

There are 3 ways to declare a JavaScript variable:

1.Using var

2.Using let

3.Using const

Variables are containers for storing data (values).

In this example, x, y, and z, are variables, declared with the var keyword:

Example
var x = 5;
var y = 6;
var z = x + y;

From the example above, you can expect:

x stores the value 5

y stores the value 6

z stores the value 11

example 2:

var price1 = 5;
var price2 = 6;
var total = price1 + price2;

In programming, just like in algebra, we use variables (like price1) to hold values.

In programming, just like in algebra, we use variables in expressions (total = price1 + price2).

From the example above, you can calculate the total to be 11.

the let and const ways of declaring variables are used and var is comparitively an old way of declaring variables in javascript.

Naming Conventions for variables and constants in JavaScript

Naming conventions

1.reserved keywords cannot be used as variable names
let new=27;
let function = 'fun'; //error as function cannot be a name

2.variable names can start with $ or underscores and alphabets
only.
let$function = 3; // this is allowed

3.conventionally variables must not start with caps until its a
class or constant
let Person = 'Jonas';

4.constants are writtern with upper case
let PI = 3.1233;

5.naming conventions that involve elaborate wordings are prefered
over including numbers in the declaration.

let myFirstJob = "programmer";
let myCurrentJob = "teacher";

let country = "India";
let continent = "Asia";
let population = 565756767687;

let job1="programmer";
let job2="teacher";
Enter fullscreen mode Exit fullscreen mode

More Examples on using variables

1.declaring a variable and assigning a value to the variable
   let js = 'amazing';

2. console.log() is used whenever we need to output something 
   to the browser

   console.log(40*8+23-10);
   console.log("Jonas");
   console.log(23);

   let firstName = "Jonas";  //first_name notation isalso used
   console.log(firstName);
Enter fullscreen mode Exit fullscreen mode

3.camel case is used when more than one words are used

let 3years=7;//variable name cannot start with a number 
let first_name ="aishwarya";

let jonas$natella ='JN'// error as we can have only 
 numbers,letters,and underscores
Enter fullscreen mode Exit fullscreen mode

Discussion (0)