JavaScript Tutorial: Variables and Operators Explained

Variables and Operators in JavaScript

Lesson Details:
October 21, 2020


I: Introduction

Web development is a fascinating world, and it can be very profitable if you do it well. This course will teach you all you need to know to create web applications that work, and that people like to use. We'll start at the beginning with variables and operators and move through loops and functions before we get into object-oriented programming. We'll finish up by looking at events and how to handle them, and finally we'll look at how you can use javascript to make your web applications behave like desktop applications.

II: Body

1. Variables and operators in javascript

A variable in javascript is a location in memory where you store data. The data stored in the variable can be a number, a string of characters, or a reference to an object. The main difference between a variable and a constant is that a constant's value cannot be changed after it has been set while a variable's value can be changed.

The name of a variable must be a valid javascript identifier - that is, the first character must be a letter, the rest of the characters should be letters, numbers, or underscores, and the name should not contain spaces. For example, "myVariable" is a valid name, but "my_variable" is not. You can declare a variable by assigning it a value when it's created:

var myVariable = "This is a string";

String literals are surrounded by double quotes. They can be formed from multiple strings concatenated together using the "+" operator:

var multiString = "The Father + Son + Holy Ghost";

You can also include numbers inside strings:

var numberString = '2 + 3 = 5';

The + operator also works for other types of numbers. JavaScript treats integers and floating point numbers differently, so this code will work:

var integer = 2; var float = 3.14159; var mixed = 1 + 2.2; // mixed is equal to 3.2 in javascript

The last example shows the syntax for mixing different types in an expression. Mixed type expressions can sometimes lead to unexpected results because javascript doesn't know whether to treat the values as integers or floating point numbers when doing math on them. For example, consider this code:

var x = 2; var y = 3; var z = x + y; // What is the value of z?

The answer depends on whether x and y are treated as integers or floating point numbers when doing the addition. If they're treated as integers, the result of the addition is 5 (2+3=5). If they're treated as floating point numbers, the result is 6 (3.0+3.0=6.0). To avoid these ambiguities, always use explicit casts like this:

var x = 2; var y = 3; var z = (x + y) / 2; // z is now 1 or 6 depending on whether x and y are integers or floats

loader
Course content