03. JavaScript Values literals and variables

Literals

Literals are fixed values of either numbers (with or without decimals), or strings.

// numerical literals
3.14;
48;
 
// Strings
"Hello World!";
'Hello Mars!'; 

Literals won't do much on its own, so let's take a look at variables, which are containers that can store literals.

Variables

Variables store data values such as literals. They can also be set to expressions, which are evaluated and placed into the variable.

To define a variable, we use the var keyword with the assignment operator = symbol.

// Initialize variable count and set it to 0
var count = 0;
// Or just initialize the variable 
var count;

In the second initialization, the variable count is initalized to undefined.

Declaring Multiple variables

You can also declare multiple variables while using the var keyword just once.

var price = 5, quantity = 23, total = 50;
var price, quantity, total;

A loosely typed language

JavaScript is not a strongly typed language, meaning you don't need to declare what type of data a variable will hold. So no matter what data type we're declaring, we use the var keyword. We'll talk about the different data types and typecasting in the next section.

Guidelines for variable

Here are some guidelines to follow when assigning a variable name:

  1. Variable names cannot start with a number.
  2. Valid characters only include letters, numbers, $ and _.
  3. Variables are case sensitive!
  4. There are some keywords in JavaScript that you cannot use.

Variable naming

When deciding on a variable name, it's important to be clear and descriptive. Names like p and pre are too short and don't convey any information.

Variables of more than one word should have a upperCamelCase format. This means that the first word is all lowercase, and any subsequent words have their first letters capitalized. For example, a variable that holds the number of remaining books would look like numRemainingBooks.

Aching back from coding all day?

Prism Glasses

Aching back from coding all day? Try Back Problems

Ever feel achy from sitting crunched up on your computer table? Try lying down with these optical glasses that allow you to work on your laptop while lying flat on your back. This is the perfect solution with those with limited mobility or those who wish to prevent neck cramps and back strains.

$ Check price
4.454.45Amazon 4 logo(128+ reviews)

More Back Problems resources

Build modern and responsive webpages

JavaScript & JQuery

Build modern and responsive webpages Try Front-end

This book was written for anyone who wants to use JavaScript to make their websites a little more interesting, engaging, interactive, or usable. In particular, it is aimed at people who do not have a degree in computer science (well, not yet anyway).

$ Check price
39.9939.99Amazon 4.5 logo(385+ reviews)

More Front-end resources

Ad