0% found this document useful (0 votes)
3 views11 pages

JavaScript Variables

Uploaded by

gaddemmit02
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views11 pages

JavaScript Variables

Uploaded by

gaddemmit02
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JavaScript Variables

Variables = Data Containers

JavaScript variables are containers for data.

JavaScript variables can be declared in 4 ways:

Modern JavaScript

 Using let
 Using const

Older JavaScript

 Using var (Not Recommended)


 Automatically (Not Recommended)

Example using let


let x = 5;
let y = 6;
let z = x + y;

Example using const


const x = 5;
const y = 6;
const z = x + y;

From the examples you can guess:

 x contains (or stores) the value 5

 y contains (or stores) the value 6

 z contains (or stores) the value 11

Variables are labels for data values.

Variables are containers for storing data.


JavaScript Identifiers
Variables are identified with unique names called identifiers.

Names can be short like x, y, z.

Names can be descriptive age, sum, carName.

The rules for constructing names (identifiers) are:

 Names can contain letters, digits, underscores, and dollar signs.


 Names must begin with a letter, a $ sign or an underscore (_).
 Names are case sensitive (X is different from x).
 Reserved words (JavaScript keywords) cannot be used as names.

Note
Numbers are not allowed as the first character in names.

This way JavaScript can easily distinguish identifiers from numbers.

JavaScript Underscore (_)


JavaScript treats underscore as a letter.

Identifiers containing _ are valid variable names:

Example
let _lastName = "Johnson";
let _x = 2;
let _100 = 5;

A convention among professional programmers is to start a name with


underscore for "private" variables.

JavaScript Dollar Sign $


JavaScript also treats a dollar sign as a letter.
Identifiers containing $ are valid variable names:

Example
let $ = "Hello World";
let $$$ = 2;
let $myMoney = 5;

Using the $ is not very common in JavaScript, but professional programmers


often use it as an alias for the main function in JavaScript libraries.

Declaring JavaScript Variables


Creating a variable in JavaScript is called declaring a variable.

You declare a JavaScript variable with the let keyword or the const keyword.

Declaring a Variable Using let


let carName;

After the declaration, the variable has no value (technically it is undefined).

To assign a value to the variable, use the equal sign:

carName = "Volvo";

Most often you will assign a value to the variable when you declare it:

Example
Create a variable called carName and assign the value "Volvo" to it:

let carName = "Volvo";

Declaring a Variable Using const


Always use const if the value should not be changed

const carName = "Volvo";


A Mixed Example
const price1 = 5;
const price2 = 6;
let total = price1 + price2;

The two variables price1 and price2 are declared with the const keyword.

The values of price1 and price2 cannot be changed.

The variable total is declared with the let keyword.

The value of total can be changed.

Declaring a Variable
Automatically
Undeclared variables are automatically declared when first used:

Example (Not Recommended)


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

It's a good programming practice to declare all variables at the beginning of


a script.

Declaring a Variable Using var


The var keyword was used in all JavaScript code before 2015.

The let and const keywords were new to JavaScript in 2015.

Using var (Not Recommended)


var x = 5;
var y = 6;
var z = x + y;
When to Use var, let, or const?
1. Always declare variables

2. Always use const if the value should not be changed

3. Always use const if the type should not be changed (Arrays and Objects)

4. Only use let if you cannot use const

5. Never use var if you can use let or const.

JavaScript Data Types


JavaScript variables can hold 8 datatypes, but for now, just think
of numbers and strings.

Strings are text written inside quotes.

Numbers are written without quotes.

If you put a number in quotes, it will be treated as a text string.

Example
const pi = 3.14;
let person = "John Doe";
let answer = 'Yes I am!';

One Statement, Many Variables


You can declare many variables in one statement.

Start the statement with let or constand separate the variables by comma:

Example
let person = "John Doe", carName = "Volvo", price = 200;

A declaration can span multiple lines:


Example
let person = "John Doe",
carName = "Volvo",
price = 200;

The Assignment Operator


In JavaScript, the equal sign (=) is an assignment operator, not an equal
to operator.

This is different from algebra. The following does not make sense in algebra:

x = x + 5

In JavaScript, however, it makes perfect sense: it assigns the value of x + 5


to x.

(It calculates the value of x + 5 and puts the result into x. The value of x is
incremented by 5.)

Note
The equal to operator is written like == in JavaScript.

JavaScript Arithmetic
As with algebra, you can do arithmetic with JavaScript variables, using
operators like = and +:

Example
let x = 5 + 2 + 3;

You can also add strings, but strings will be concatenated:

Example
let x = "John" + " " + "Doe";
Note
If you put a number in quotes, the rest of the numbers will be treated as
strings, and concatenated.

Examples
let x = "5" + 2 + 3;

let x = 2 + 3 + "5";

JavaScript has 8 Datatypes


A JavaScript variable can hold 8 types of data:

Type Description

String A text of characters enclosed in quotes

Number A number representing a mathematical value

Bigint A number representing a large integer

Boolean A data type representing true or false

Object A collection of key-value pairs of data

Undefined A primitive variable with no assigned value

Null A primitive value representing object absence

Symbol A unique and primitive identifier

The typeof Operator


You can use the JavaScript typeof operator to find the type of a JavaScript
variable.
The typeof operator returns the type of a variable or an expression:

Example
typeof "" // Returns "string"
typeof "John" // Returns "string"
typeof "John Doe" // Returns "string"

JavaScript Strings
A string (a text string) is a series of characters like "John Doe".

Strings are written with quotes. You can use single or double quotes:

Example
// Using double quotes:
let carName1 = "Volvo XC60";

// Using single quotes:


let carName2 = 'Volvo XC60';

You can use quotes inside a string, as long as they don't match the quotes
surrounding the string:

// Single quote inside double quotes:


let answer1 = "It's alright";

// Single quotes inside double quotes:


let answer2 = "He is called 'Johnny'";

// Double quotes inside single quotes:


let answer3 = 'He is called "Johnny"';

Note
You will learn a lot more about JavaScript Strings later in this tutorial.
JavaScript Numbers
All JavaScript numbers are stored as decimal numbers (floating point).

Numbers can be written with, or without decimals:

Example
// With decimals:
let x1 = 34.00;

// Without decimals:
let x2 = 34;

Exponential Notation
Extra large or extra small numbers can be written with scientific
(exponential) notation:

Example
let y = 123e5; // 12300000
let z = 123e-5; // 0.00123

JavaScript Booleans
JavaScript booleans can only have one of two values: true or false

The boolean value of an expression is the basis for JavaScript comparisons:

Description Expression Returns

Not equal to (x == 8) false

Unequal to (x != 8) true

Greater (x > 8) false


than
Less than (x < 8) true

Datatype undefined
In computer programs, variables are often declared without a value. The
value can be something that has to be calculated, or something that will be
provided later, like user input.

A variable without a value has the datatype undefined.

A variable without a value also has the value undefined.

Example
let carName;

Empty Values
An empty value has nothing to do with undefined.

An empty string has both a legal value and a type.

Example
let car = ""; // The value is "", the typeof is "string"

Class tasks

1. Declare firstName and lastName, then combine them into fullName and display it.
2. Store a temperature in Celsius in a variable and convert it to
Fahrenheit using the formula:
F = (C × 9/5) + 32.
3. Swapping Two Variables: Declare two variables a and b with different values. Swap
their values and print them.
4. Declare variables of type string, number, boolean, undefined, and
null. Use typeof to display their data types.

You might also like